E.Akio
E.Akio

Reputation: 2388

How to pass an Activity as parameter in function

I want to create a function that receives an Activity as parameter and with it, it will change to that activity. But if I use the .class of an Activity to call the function, it changes the parameter of that function to a Class<{Name}Activity>, and so it will only accept that activity.

For example. Calling the function:

sendUserToActivity(MainActivity.class);

How it is defined:

private void sendUserToActivity(Class<MainActivity> activityClass) {
    Intent intent = new Intent(RegisterActivity.this, activityClass);
    startActivity(intent);
}

And if I try another call:

sendUserToActivity(LoginActivity.class);

It gets an error. Since the parameter of the function is established as the Class MainActivity, of course it won't accept another Activity, so how it should be defined to accept another Activity?

Upvotes: 0

Views: 1292

Answers (3)

Johannes Schidlowski
Johannes Schidlowski

Reputation: 112

xyz(XActivity.class);

void xyz(Class<?> cls)
{
    Intent intent = new Intent(MainActivity.this, cls);
    startActivity(intent);
}

does the job. I tried this now.

Upvotes: 0

Dmytro Ivanov
Dmytro Ivanov

Reputation: 1310

Here is an example, how to do it in your case:

private void sendUserToActivity(MainActivity activityClass) {
    Intent intent = new Intent(activityClass, activityClass.getClass());
    startActivity(intent);
}

Upvotes: 0

Maybe you can try this:

private void sendUserToActivity(Class<? extends Activity> activityClass) {
    Intent intent = new Intent(RegisterActivity.this, activityClass);
    startActivity(intent);
}

This way you're using generics and everyone that extends activity will be accepted, so your code is adaptable to every activity that you want.

Upvotes: 5

Related Questions