使用Handler更新UI
1.handler使用步骤
1.创建handler对象,并实现handleMessage(Message msg)方法,处理子线程发送来的消息,并且更新UI
2.创建线程类,向handler发送msg消息,
3.在需要的地方启动线程
直接看示例,注释写的很详细
2.示例
1.activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/count_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp" />
<TextView
android:layout_below="@id/count_time"
android:id="@+id/count_time_two"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp" />
</RelativeLayout>
2.MainActivity.java
package com.example.handlechangetext;
import java.lang.ref.WeakReference;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.widget.TextView;
/**
* handler实时改变文本框的内容
*
* */
public class MainActivity extends Activity {
private TextView tv_one,tv_two;
public int what = 0;
static MyHandler myHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myHandler = new MyHandler(this);
//取得组件
tv_one = (TextView)findViewById(R.id.count_time);
tv_two = (TextView)findViewById(R.id.count_time_two);
//启动线程
thread.start();
}
//定义handler,处理消息,更新UI
private Handler handler = new Handler(){
//handler接收消息的方法
public void handleMessage(Message msg){
//改变文本框的内容
tv_one.setText("当前用时:"+msg.what);
}
};
//定义线程类,定时发送消息给handle
HandlerThread thread = new HandlerThread("thread"){
public void run(){
while (true) {
what++;
handler.sendEmptyMessage(what);
myHandler.sendEmptyMessage(what);
try {
thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
//内部线程类保持对Activity的弱引用实现实时更新UI
static class MyHandler extends Handler{
WeakReference mActivity;//保持对外部类的弱引用
//构造方法
MyHandler(MainActivity activity){
mActivity = new WeakReference(activity);
}
public void handleMessage(Message msg){
MainActivity theActivity = mActivity.get();
theActivity.tv_two.setText("当前用时:"+msg.what);
}
}
@Override
protected void onPause() {
if (thread.isAlive()) {
thread.quit();//当页面暂停时,停止线程
}
super.onPause();
}
}
3.效果图
本例是自己在开发中用到了一个计时功能,需要实时更新UI,显示剩余时间,所以做一个记录,方便以后翻阅个人感觉,handler的使用还是挺麻烦,一不小心就会导致内存泄漏,所以在使用的时候一定要注意,此处,本程序也还是存在一些问题,比如,页面退出后,再进入的时候程序会卡死等,但仅供个人笔记所用,关于handler,本人也正在研究中