实现了按住界面上的button后,TextView每隔一秒连续增加。抬起后,停止。
package com.myapp.androidtest2; import java.util.Timer; import java.util.TimerTask; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.widget.Button; import android.widget.TextView; public class MainActivity extends Activity { private Button mButton; static TextView mTextView; static int i = 1; /** Called when the activity is first created. */ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 如果是字switch 就设置OnTouchLisenner ButtonListener b = new ButtonListener(); mButton = (Button) findViewById(R.id.button); mButton.setOnClickListener(b); mButton.setOnTouchListener(b); mTextView = (TextView) findViewById(R.id.textview); } static class MyTask extends TimerTask { public void run() { Message message = new Message(); message.what = 1; mHandler.sendMessage(message); } } private static Handler mHandler = new Handler() { // 接收到消息后处理 public void handleMessage(Message msg) { switch (msg.what) { case 1: mTextView.setText("" + (i++)); break; } super.handleMessage(msg); } }; class ButtonListener implements OnClickListener, OnTouchListener { public void onClick(View v) { if (v.getId() == R.id.button) { Log.d("test", "cansal button ---> click"); } } // 你需要复写onTouch事件,需要开启一个线程 sleep 1秒 执行加一操作,更新数据需要放到ui线程里面。 // 停止的时候 可以直接跳出线程break Timer timer; public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: timer = new Timer(true); System.out.println("++++++key_down"); timer.schedule(new MyTask(), 1000, 1000); break; case MotionEvent.ACTION_UP: System.out.println("++++++key_UP"); timer.cancel(); break; case MotionEvent.ACTION_CANCEL: System.out.println("++++++key_CANCEL"); timer.cancel(); break; } return true; } } }
参考文章:
本文出自 “信息安全-数据库安全” 博客,请务必保留此出处http://fergusj.blog.51cto.com/8835051/1687825
原文地址:http://fergusj.blog.51cto.com/8835051/1687825