Android线程处理之Handler总结

时间:2023-06-01 16:04:32

  上一篇为大家介绍了如何通过Handler对象把Message数据发送到主线程,我想大家一定都已经掌握了,本篇我将以一个例子的方式为大家总结一下Handler的使用,例子是通过Handler实现一个图片自动改变的效果,一般我们都是通过Viewpage来实现这个效果,不过本篇我们就一起来学习一下如何通过Handler实现这个效果吧。

  开始之前我们需要准备几张用来更新切换的图片,让后把这些图片放到res下面的drawable-hdpi下就可以了。有了这些我们就可以开始我们的效果实现了:

 1、布局文件:

<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"
tools:context="${relativePackage}.${activityClass}" > <ImageView
android:id="@+id/imageView1"
android:layout_width="300px"
android:layout_height="300px"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="87dp"
android:src="@drawable/abc_ab_share_pack_holo_light" /> <Button
android:id="@+id/stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/imgButton"
android:layout_alignParentTop="true"
android:layout_marginTop="36dp"
android:text="停止切换" /> </RelativeLayout>

  2、我们Activity代码:

public class ImgActivity extends Activity {

    private ImageView imageView;
private Button stop;
private Handler handler = new Handler();
private int ImageAll [] = {R.drawable.download1, R.drawable.download2, R.drawable.download3};
private int index = 1;
private MyRunable myRunable = new MyRunable(); @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_img);
stop = (Button) findViewById(R.id.stop);
imageView = (ImageView) findViewById(R.id.imageView1); stop.setOnClickListener(new OnClickListener() { @Override
public void onClick(View arg0) {
handler.removeCallbacks(myRunable);//停止切换
}
});
handler.postDelayed(myRunable, 1000);
} class MyRunable implements Runnable{
@Override
public void run() {
index = index%3;
imageView.setImageResource(ImageAll[index]);
index++;
handler.postDelayed(myRunable, 1000);
}
}
}

  好了我们的实例就完成了,简单为大家介绍一下代码:

  index = index%3;:控制我们的图片切换
  handler.postDelayed(myRunable, 1000);:每隔1s执行我们的myRunable对象
  
  handler.removeCallbacks(myRunable);:移除我们的myRunable对象,停止执行   ok我们的实例效果已经为大家介绍完毕,大家可以自己写一下,很有趣呦!