KMarto
KMarto

Reputation: 300

How to create a method to start an activity?

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

Answers (2)

Vinay Rathod
Vinay Rathod

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

Arty
Arty

Reputation: 898

Try this code:

public void startSpecificActivity(Class<?> otherActivityClass) {
    Intent intent = new Intent(getApplicationContext(), otherActivityClass);
    startActivity(intent);
}

Usage:

startSpecificActivity(MyActivity1.class);

Upvotes: 1

Related Questions