Android Code - Radom number generation for calling activity
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
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
等等 ....
有人可以帮我这个代码吗?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 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); } }); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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); } } |