在imageview上线程随机更改图像

时间:2015-08-14 09:14:45

标签: android multithreading image random imageview

我是初学者。我希望在Android中的imageview上更改我的图像,并且在一段时间后定期更改图像。

<LinearLayout
    android:id="@+id/la_01"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#eb68a3"
    android:orientation="vertical" >        
    <ImageView
        android:id="@+id/ig1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center|center"
        android:src="@drawable/a03" />     
</LinearLayout>
public class MainActivity2 extends Activity {
    private ImageView ig1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_activity2);           
        int[] imageArray = new int[] {
            R.drawable.a01, R.drawable.a02, R.drawable.a04, R.drawable.a05, R.drawable.a06
        };
        ig1.setImageResource(R.drawable.a06);

我该怎么办? 请帮帮我,谢谢

2 个答案:

答案 0 :(得分:0)

创建一个随机函数,返回可用于切换图像的位置......

public class MainActivity extends Activity {
int[] img = {
        R.drawable.image1,
        R.drawable.app_background,
        R.drawable.app_background_p,
        R.drawable.list
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ImageView image = (ImageView)this.findViewById(R.id.image);
    int get = GetRemdom(0,3);   // 0 to (length of your array -1)

    image.setBackgroundResource(img[get]);

}

public int GetRemdom(int min,int max){
    Random random = new Random();
    int position = random.nextInt(max - min + 1) + min;
            return position ;
}

答案 1 :(得分:0)

您可以使用Handler类来执行此操作。

public class ImageSwitcherActivity extends Activity implements Runnable{
private Handler mHandler = new Handler();
ImageView imageView;
static int idx = 0;
int[] images;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_image_switcher);
    images = new int[]{
            R.drawable.img1,
            R.drawable.img2,
            R.drawable.img3,
            R.drawable.img4,
            R.drawable.img5,
            R.drawable.img6,
            R.drawable.img7
    };
    imageView = (ImageView) findViewById(R.id.ig1);

    mHandler.removeCallbacks(this);
    mHandler.postDelayed(this, 100);
}

@Override
public void run() {
    idx = new Random().nextInt(images.length - 1);
    imageView.setImageResource(images[idx]);

    mHandler.postDelayed(this, ( 2 * 1000)) ;
}

@Override
public void onStop()
{
    super.onStop();
    mHandler.removeCallbacks(this);
}
}