可能重复:
Generating random number in a range with Java
How can I generate random number in specific range in Android?
这是我的情景 来自Mainactivity;单击按钮我想生成1到4的随机数 根据输出,我想写一个if-else,它将调用4个不同的活动
因此,点击,如果生成4,则调用活动4 下一次可以生成1并且应该调用活动1 等等....
有人可以帮我解释一下这段代码吗?
答案 0 :(得分:0)
public void test1(){
Random r = new Random();
int index = r.nextInt(4)+1;
Intent intent = null;
switch(index){
case 1: intent = new Intent(this, Activity1.class);
break;
case 2: intent = new Intent(this, Activity2.class);
break;
case 3: intent = new Intent(this, Activity3.class);
break;
case 4: intent = new Intent(this, Activity4.class);
break;
default:
Log.e("ERROR", "");
return;
}
if(intent != null){
this.startActivity(intent);
}
}
答案 1 :(得分:0)
myBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Random r = new Random();
int index = r.nextInt(4)+1;
Intent intent;
if (index == 4) {
intent = new Intent(Activity.this, Activity4.class);
}
else if (index == 3) {
intent = new Intent(Activity.this, Activity3.class);
}
else if (index == 2) {
intent = new Intent(Activity.this, Activity2.class);
}
else
intent = new Intent(Activity.this, Activity1.class);
startActivity(intent);
}
});