一、在res/drawable放入须要的图片资源android
二、res/layout界面布局ide
代码布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"this
xmlns:tools="http://schemas.android.com/tools"spa
android:layout_width="match_parent"线程
android:layout_height="match_parent"xml
tools:context="${relativePackage}.${activityClass}" >图片
<ImageView资源
android:id="@+id/imageview"it
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RelativeLayout>
==========================
三、MainActivity 类
代码
public class MainActivity extends Activity {
//须要切换的图片资源
private int[] images = { R.drawable.bg01, R.drawable.bg02, R.drawable.bg03,
R.drawable.bg04, R.drawable.bg05, };
private ImageView imageView;
private int index;
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 1:
imageView.setImageResource(images[index++]);
if (index > 4) {
index = 0;
}
break;
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.imageView = (ImageView) this.findViewById(R.id.imageview);
/*// 方法1 -- 使用线程的休眠来定时切换
new Thread(new Runnable() {
@Override
public void run() {
while(true){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.sendEmptyMessage(1);
}
}
}).start();*/
//方法2 -- 计时器
//第一个参数 -- 计时器线程
//第二个参数 -- 从何时开始执行
//第三个参数 -- 多久执行一次
new Timer().schedule(new TimerTask() {
@Override
public void run() {
handler.sendEmptyMessage(1);
}
}, 0, 2000);
}
}