1.handler是什么
handler是android给我们提供用来更新UI的一套机制,也是一套消息处理的机制,我们可以发送消息,也可以通过它处理消息。
2.为什么要用handler
Android在设计的时候,就封装了一套消息创建、传递、处理机制,如果不遵循这种机制,就没有办法更新UI信息的,就会抛出异常信息。(就是规定)
3.handler怎么用
sendMessage,sendMessageDelayed,
post(Runnable),postDelayed(Runnable,long)
handler的基本用法
MainActivity.java
package com.example.handlertext;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.view.Menu;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView textView;
private Handler handler=new Handler();
private ImageView imageView;
private int images[]={R.drawable.a,R.drawable.b,R.drawable.c};
private int index;
private MyRunnable myRunnable=new MyRunnable();
class MyRunnable implements Runnable{
@Override
public void run() {
index++;
index=index%3;
imageView.setImageResource(images[index]);
handler.postDelayed(myRunnable, 1000);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=(TextView) findViewById(R.id.textview);
imageView=(ImageView) findViewById(R.id.imageView1);
/*
* new Thread(){
public void run() {
try {
Thread.sleep(1000);
handler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
textView.setText("update text");
}
});
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
*/
handler.postDelayed(myRunnable, 1000);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
activity_main.java
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:layout_marginTop="162dp"
android:src="@drawable/ic_launcher" />
</RelativeLayout>
注释去掉:
可以将原本存在的helloworld通过handler线程更改为update text
注释不去掉:
可以再界面内每隔一秒钟刷新一张照片。