线程实时刷新TextView值:
思路:
1)使用handler通知view修改值;
2)标志位控制线程的停止/开始;
/**
* 1、刷新线程
*
* @author wxm
*
*/
class RefreshThread implements Runnable {
public void run() {
while (isStop) {
try {
handler.sendMessage(handler.obtainMessage());
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
备注:sendMessage发送消息
/**
* 2、实时刷新界面
*/
Handler handler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
System.out.println("count--->" + count);
if (count == 5) {
isStop = false;
try {
Thread.sleep(3000);
isStop = true;
count = 0;
new Thread(mRefreshThread).start();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
textview.setText(String.valueOf(count++));
}
};
备注:接收消息,并修改停止/开始标志位
3、初始化控件
private TextView textview = null; // TextView 控件
private int count = 0;//初始化数值
private RefreshThread mRefreshThread = null;//刷新线程
private boolean isStop = true;// 线程控制标志
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview = (TextView) findViewById(R.id.textview);
mRefreshThread = new RefreshThread();
textview.setText(String.valueOf(count));
new Thread(mRefreshThread).start();// 开始进程
}
本文出自 “android-王晓敏” 博客,请务必保留此出处http://wxmgcs.blog.51cto.com/6955256/1381827