简体   繁体   中英

Randomly change background image in Android

I have an activity in my quiz application and I want to change its background every 5 seconds. How can I randomize the images in my drawable folder and make them the background images of my activity. Note: It is only a single activity.

Any help would be greatly appreciated. Thank you.

You can create an array of your drawables like this:

<array name="myImages">
       <item>@drawable/img1</item>
       <item>@drawable/img2</item>
       <item>@drawable/img3</item>
</array>

You can get them like this:

Resources res = getResources();
TypedArray myImages = res.obtainTypedArray(R.array.myImages);

Now create random numbers:

Random r = new Random(myImages.length())
int i = r.nextInt();

Drawable drawable = icons.getDrawable(i);

Now set them as your background every 5 seconds(like in ρяσѕρєяs example).

use Handler or Timertask for changing background of activity in every 5 sec as:

public static int count=0;
int[] drawablearray=new int[]{R.drawable.One,R.drawable.Two,..};
new Handler().postDelayed(new Runnable() {
    public void run() {

       if(count<drawablearray.length){

           Your_Current_Activity.this.getWindow().
               setBackgroundDrawableResource(drawablearray[count]);

           count++;  //<<< increment counter here
        }
       else{
          // reset counter here
          count=0;
        }

      }
  }, 5000);
public class Test extends Activity{
    //instantiate a handler object
private Handler imageHandler = new Handler();
    //array containing drawables ids
int[] myarray = new int[]{R.drawable.image1,.....};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //add a runnable to the message queue
    imageHandler.post(handle);
}

private final Runnable handle = new Runnable(){
    public void run(){
        try {
            Random r = new Random();
            int i = r.nextInt(myarray.length);
            Test.this.getWindow().setBackgroundDrawableResource(myarray[i]);
            imageHandler.postDelayed(this, 5000);    
        }
        catch (Exception e) {
            Log.d("Test", e.toString());
        }   
    }
};

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM