Reputation: 7463
I have to start activity that makes use of some Variables as the Class Names. Is there a Solution out?
public void something(int position) {
someVar = "MyActivity"+position;
startActivity(new Intent(Main.this,someVar.class));
}
Upvotes: 0
Views: 1427
Reputation: 1
For anyone still confused and looking for "The Solution" not the "Work-Arounds", it's very simple to pass a class reference as a variable, put into consideration that this example is derived from an Android context: Variable is: Class<? extends package.ClassNameHere> variableName;
Upvotes: 0
Reputation:
You can use reflection to get the class type. Just make sure you include the package name in the string.
public void something(int position) throws ClassNotFoundException {
Class<?> theClass = Class.forName("com.example.Activity" + position);
startActivity(new Intent(this, theClass));
}
Upvotes: 0
Reputation: 14458
If there aren't too many activities, you can always do this:
Class myclass;
Switch(position){
case 1:
myclass = Activity1.class;
break;
case 2:
myclass = Activity2.class;
break;
case 3:
myclass = Activity3.class;
break;
}
startActivity(new Intent(Main.this,myclass));
Upvotes: 2
Reputation: 39403
You don't actually need the class
of the Activity you are starting. You can use a setClassName
:
Intent i = new Intent();
i.setClassName(this, "MyActivity" + position);
startActivity(i);
Upvotes: 0