Skip to content Skip to sidebar Skip to footer

Thread Random Change Image On Imageview

I'm Beginner. I want change my image on imageview in Android and that images are periodically changed after some interval.

Solution 1:

You can use Handler class to do this.

publicclassImageSwitcherActivityextendsActivityimplementsRunnable{
privateHandlermHandler=newHandler();
ImageView imageView;
staticintidx=0;
int[] images;

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_image_switcher);
    images = newint[]{
            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);
}

@Overridepublicvoidrun() {
    idx = newRandom().nextInt(images.length - 1);
    imageView.setImageResource(images[idx]);

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

@OverridepublicvoidonStop()
{
    super.onStop();
    mHandler.removeCallbacks(this);
}
}

Solution 2:

Create a random function which return the position you can use to switch images...

publicclassMainActivityextendsActivity {
int[] img = {
        R.drawable.image1,
        R.drawable.app_background,
        R.drawable.app_background_p,
        R.drawable.list
};

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

    image.setBackgroundResource(img[get]);

}

publicintGetRemdom(int min,int max){
    Randomrandom=newRandom();
    intposition= random.nextInt(max - min + 1) + min;
            return position ;
}

Post a Comment for "Thread Random Change Image On Imageview"