Well, my question is: Can I make a function call a Random Activity?
Well, my question is: Can I make a function call a Random Activity?
Random r = new Random();
int randomIndex = r.nextInt(5); // Index aleatorio de 0 a 4
Class<?>[] activities = new Class<?>[]{
Activity1.class,
Activity2.class,
Activity3.class,
Activity4.class,
Activity5.class
};
Intent intent = new Intent(this, activities[randomIndex]);
startActivity(intent);
Yes, it is possible.
The way to open an activity on Android is through Intents , as below:
Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
myIntent.putExtra("key", value); //Parametros opcionais
CurrentActivity.this.startActivity(myIntent);
In this case, the way I find it more interesting to open a random activity would be to use the nextInt()
function of the Random class.
Random r = new Random();
int i = r.nextInt(numero de resultados possiveis) + resultado inicial;
// Por exemplo, gerar um numero de 65(incluído)-80(excluido), você usaria nextInt(80 - 65) + 65
With the random decision made, we can launch the Activity, you could do something like this:
switch (randomNumber) {
case 1: abre activity 1; break;
case 2: abre activity 2; break;
.
.
.
}
I've used this answer and this other answer .