Android之Handler子线程的简单使用(二)

来源:互联网 发布:最新网络语言 编辑:程序博客网 时间:2024/05/18 02:25

上一篇讲解了Handler的处理机制,但是没有给例子,这次就给个例子

先看效果图:


我没隔3秒就换个图片

布局:

<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:gravity="center">    <ImageView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:id="@+id/iv"         android:src="@drawable/coin03"/></RelativeLayout>
activity:

public class MainActivity extends Activity {    private ImageView iv;    private int[] images={R.drawable.coin03,R.drawable.coin04,    R.drawable.coin05,R.drawable.coin06,R.drawable.coin07};    //保存当前显示的图片    private int currentImage=0;    //获取主线程的Looper对象    Looper looper=//Looper.getMainLooper();    Looper.myLooper();    //Looper.myQueue();    //接收消息与处理消息    private Handler handler =new Handler(looper){    public void handleMessage(Message msg) {    //更新UI组件    if(msg.what==0x123){    iv.setImageResource(images[++currentImage%(images.length)]);    }    }    };@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);iv=(ImageView) findViewById(R.id.iv);//启动子线程new Thread(){public void run() {while(true){try {Thread.sleep(3000);//三秒} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}//修改了UI组件/*iv.setImageResource(images[++currentImage%(images.length)]);*///利用消息机制更新UI组件//发送消息,参数是标识符//handler.sendEmptyMessage(0x123);Message msg=//new Message();handler.obtainMessage();msg.what=0x123;msg.obj="更新图片";handler.sendMessage(msg);}}}.start();}}


想要源码的可以:代码链接

免费的哦~~




0 0