该实例主要做的是,实现每隔几秒更新图片的例子。
1.放图片
在自己的drawable中放几张图片,这里分别为iamge1.jpg、iamge2.jpg、iamge3.jpg、iamge4.jpg。
2.activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
3.MainActivity.java
package com.learning.handler.demo2;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
private ImageView image;
private int images[]={R.drawable.image1,R.drawable.image2,
R.drawable.image3,R.drawable.image4};//图片数组
private int index;//更新图片的索引
private Handler handler= new Handler();
private MyRunnable myRunnable = new MyRunnable();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (ImageView) findViewById(R.id.imageView);
handler.postDelayed(myRunnable,1000);
}
class MyRunnable implements Runnable {
@Override
public void run() {
index++;
index = index%4;
image.setImageResource(images[index]);
handler.postDelayed(myRunnable,1000);
}
}
}
运行,即可看到四张图片每隔一秒更新一次。