改变背景图像是随机的

时间:2013-09-08 11:43:21

标签: java android random

假设我的应用主屏幕有几张背景图片。每次应用程序启动时,我都希望随机选择背景图片,这在android中是否可能?

1 个答案:

答案 0 :(得分:2)

简短回答:是的。

答案很长:

private static final int NUM_BACKGROUNDS = 5; // or whatever
private Random mRandom = new Random();

public void onCreate(Bundle state) {
    View v = findViewById(/* your background view id */);
    int res;
    int i = mRandom.nextInt(NUM_BACKGROUNDS);
    switch (i) {
        case 0: res = R.drawable.bg0; break;
        case 1: res = R.drawable.bg1; break;
        case 2: res = R.drawable.bg2; break;
        case 3: res = R.drawable.bg3; break;
        case 4: res = R.drawable.bg4; break;
        default: throw new IllegalArgumentException("oops?");
    }
    v.setBackgroundResource(res);
}