Reputation: 300
I have a switch case that starts different activities depending on user selection. I do not want to keep repeating the code for creating an intent like this:
switch(choice) {
case "option1":
Intent intent = new Intent(context, MyActivity1.class);
case "option2":
Intent intent = new Intent(context, MyActivit2.class);
}
I want to create a function where I can pass the context and my activity like:
private void startMyActivity(Context ctx, Type what_do_I_pass_here) {
Intent intent = new Intent(context, Type.class);
startActivity(intent);
}
I have tried
private void startMyActivity(Context ctx,Class<Activity> cls)
but it's not working
Upvotes: 0
Views: 121
Reputation: 1332
you have to define function like this
public void startActivity(Context ctx, Class<?> activityClass) {
Intent intent = new Intent(ctx, activityClass);
startActivity(intent);
}
and you can call it like this
startActivity(this, MainActivity.class);
Upvotes: 1
Reputation: 898
Try this code:
public void startSpecificActivity(Class<?> otherActivityClass) {
Intent intent = new Intent(getApplicationContext(), otherActivityClass);
startActivity(intent);
}
Usage:
startSpecificActivity(MyActivity1.class);
Upvotes: 1