单击按钮时如何显示随机活动

时间:2012-08-23 23:17:57

标签: android

我在主要活动中使用了以下代码

public void button(View v){

         //Create an intent to start the new activity.
            // Our intention is to start secondActivity
         Intent intent = new Intent();
         intent.setClass(this,Activity.class);
         startActivity(intent);
        }

单击按钮时如何显示随机活动?请帮我!

3 个答案:

答案 0 :(得分:2)

调试了上面的一些代码,因为setClass()中有一个错误..这个有效:

Random rnd = new Random();
int x=rnd.nextInt(3)+1;
Intent myIntent = new Intent();
switch(x){
case 1:
myIntent.setClass(view.getContext(),Scrn1.class);
break;
case 2:
myIntent.setClass(view.getContext(), Scrn2.class);
break;
case 3:
myIntent.setClass(view.getContext(), Scrn1.class);
break;
}
startActivity(myIntent);  

答案 1 :(得分:2)

将所有活动的名称存储在数组中,生成随机数并获取与随机生成的数字相对应的活动。示例代码段

    String[] title = new String[] { "Act1.class", "Act2.class","Act1.class","Act4.class","Act5.class"};

public String getRandomActivity(){
    Random randomGenerator = new Random();
            int randomInt = randomGenerator.nextInt(5);// pass number of elements as parameters
        return title[randomInt-1];//this should return class name

        }

Intent intent = new Intent(this,getRandomActivity())
startActivity(intent)

答案 2 :(得分:0)

试试这个,假设你有3个活动:

public void button(View v){
Random rnd = new Random();
int x=rnd.nextInt(3)+1;
         Intent intent = new Intent();
switch(x){
 case 1:
  intent.setClass(this,Activity1.class);
  break;
 case 2:
  intent.setClass(this,Activity2.class);
  break;
 case 3:
  intent.setClass(this,Activity3.class);
  break;
 }
 startActivity(intent);        
}