安卓Handler实例

本文介绍了一个简单的Android应用程序,该程序能够每隔两秒自动切换显示不同的图片。通过使用Handler和Thread,实现了图片的定时轮播效果。

创建一个程序,每隔两秒钟,自动切换图片

xml文件

<LinearLayout 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=".MainActivity" 
    android:orientation="vertical">


    <ImageView android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal|center_vertical"
        android:src="@drawable/img1"/>
   
</LinearLayout>

.java文件

package com.example.handlertest;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.widget.ImageView;


public class MainActivity extends Activity {


int currentIndex=0;

//图片数组
int[] imageIds=new int[]{
R.drawable.img1,
R.drawable.img2,
R.drawable.img3,
R.drawable.img4
};




@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

final ImageView img=(ImageView) super.findViewById(R.id.img);

final Handler myHandler=new Handler(){


@Override
public void handleMessage(Message msg) {
if(msg.what==0x123){
img.setImageResource(imageIds[currentIndex]);
}
}
};

//定义一个定时器
new Thread(){


@Override
public void run() {
try {
while(true){
Thread.sleep(2000);
if(currentIndex>=imageIds.length-1){
currentIndex=0;
}
else{
currentIndex++;
}
Message m=new Message();
m.what=0x123;
myHandler.sendMessage(m);
}

} catch (InterruptedException e) {
e.printStackTrace();
}
}

}.start();

}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值