简体   繁体   English

在Android中随机更改背景图片

[英]Randomly change background image in Android

I have an activity in my quiz application and I want to change its background every 5 seconds. 我的测验应用程序中有一个活动,我想每5秒更改一次背景。 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). 现在每隔5秒钟将它们设置为背景(如ρяσsρєяs示例)。

use Handler or Timertask for changing background of activity in every 5 sec as: 使用HandlerTimertask每5秒更改活动背景为:

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());
        }   
    }
};

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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