Android線程處理之Handler總結,android線程handler
上一篇為大家介紹了如何通過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我們的執行個體效果已經為大家介紹完畢,大家可以自己寫一下,很有趣呦!