Skip to content Skip to sidebar Skip to footer

How Can I Display Random Activity When Click Button

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

Solution 1:

debugged some codes above because there's an error in setClass().. this one works:

Random rnd = newRandom();
int x=rnd.nextInt(3)+1;
Intent myIntent = newIntent();
switch(x){
case1:
myIntent.setClass(view.getContext(),Scrn1.class);
break;
case2:
myIntent.setClass(view.getContext(), Scrn2.class);
break;
case3:
myIntent.setClass(view.getContext(), Scrn1.class);
break;
}
startActivity(myIntent);  

Solution 2:

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 = newString[] { "Act1.class", "Act2.class","Act1.class","Act4.class","Act5.class"};

publicStringgetRandomActivity(){
    Random randomGenerator = newRandom();
            int randomInt = randomGenerator.nextInt(5);// pass number of elements as parametersreturn title[randomInt-1];//this should return class name

        }

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

Solution 3:

Try this, assume you have 3 activities:

publicvoidbutton(View v){
Random rnd = newRandom();
int x=rnd.nextInt(3)+1;
         Intent intent = newIntent();
switch(x){
 case1:
  intent.setClass(this,Activity1.class);
  break;
 case2:
  intent.setClass(this,Activity2.class);
  break;
 case3:
  intent.setClass(this,Activity3.class);
  break;
 }
 startActivity(intent);        
}

Post a Comment for "How Can I Display Random Activity When Click Button"