Reputation: 287
I used following code in main activity
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);
}
How can I display random activity when click button? Please help me!
Upvotes: 1
Views: 3205
Reputation: 4547
Store the name of all your activities in an array, generate random number and get activity corresponding to random generated number. Sample snippet
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)
Upvotes: 2
Reputation: 56
debugged some codes above because there's an error in setClass().. this one works:
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);
Upvotes: 2
Reputation: 5322
Try this, assume you have 3 activities:
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);
}
Upvotes: 0