此文根据慕客网视频讲解而来,原视频地址http://www.imooc.com/learn/267
Handler是Android提供用来更新UI的一套机制,也是消息处理的机制,可以发送消息,也可以通过它处理消息。
1.布局文件:activity_main.xml中代码
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</RelativeLayout>
2.MainActivity中的代码:
package com.learning.handler.demo01;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
//一秒钟后更换文本信息
new Thread() {
@Override
public void run() {
try {
Thread.sleep(1000);
handler.post(new Runnable() {
@Override
public void run() {
textView.setText("Update");
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
}
Run,可以看到应用打开后页面上的Hello World!变成了Update。
特别注意:
如果MainActivity中没有使用Handler,应用打开后发生crash,原因是不能在一个非UI线程中执行更新UI。
错误的MainActivity代码:
package com.learning.handler.demo01;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView textView;
// private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
//一秒钟后更换文本信息
new Thread() {
@Override
public void run() {
try {
Thread.sleep(1000);
// handler.post(new Runnable() {
// @Override
// public void run() {
textView.setText("Update");
// }
// });
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
}
报错信息:
E/AndroidRuntime: FATAL EXCEPTION: Thread-113 android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.