我的测验应用程序中有一个活动,我想每5秒更改一次背景。如何将可绘制文件夹中的图像随机化,并使其成为我活动的背景图像。注意:这只是一项活动。
非常感谢任何帮助。谢谢。
答案 0 :(得分:2)
您可以像这样创建一个drawable数组:
<array name="myImages">
<item>@drawable/img1</item>
<item>@drawable/img2</item>
<item>@drawable/img3</item>
</array>
你可以这样得到它们:
Resources res = getResources();
TypedArray myImages = res.obtainTypedArray(R.array.myImages);
现在创建随机数:
Random r = new Random(myImages.length())
int i = r.nextInt();
Drawable drawable = icons.getDrawable(i);
现在每隔5秒将它们设置为背景(例如ρяσѕρєяs)。
答案 1 :(得分:1)
使用Handler
或Timertask
每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);
答案 2 :(得分:1)
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());
}
}
};
}