public class Music extends Activity {
private int [] layouts = {
R.layout.question_selector,
R.layout.question_selector2,
R.layout.question_selector3,
R.layout.queston_selector4,
R.layout.question_selector5,
};
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
int i = layouts.length;
Random r = new Random();
while (--i > 0) {
int j = r.nextInt(i + 1);
//swap values
int temp = layouts[j];
layouts[j] = layouts[i];
layouts[i] = temp;
}
setContentView(layouts[i]);
}
}
这是我到目前为止所做的:它运作得很好,但我注意到有些布局会一遍又一遍地显示出来。我想要的是,当我按下按钮并随机生成一个布局时,下次我再次按下按钮时,它不应重复之前显示的布局。我该怎么办?
答案 0 :(得分:1)
你可以创建一个arrayList
然后shuffle
而不是一个带有Random的数组,这会使它随机但只使用每个项目一次
编辑,代码示例:
ArrayList<int> mArrayList = new ArrayList<int>;
//OR ArrayList<int> mArrayList = new ArrayList<int>(Arrays.asList(mOrdinaryArray));
mArrayList.put(R.blabla.blabla);
mArrayList.put(R.blabla.blablatwo);
Collections.shuffle(mArrayList);
Log.d(TAG, "output after shuffle: " + mArrayList);