1

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

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);
        }

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

4

3 回答 3

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);  
于 2013-02-02T06:25:55.027 回答
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)
于 2013-08-15T01:00:22.590 回答
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);        
}
于 2012-08-23T23:30:21.563 回答