Search code examples
androidandroid-activity

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?


Solution

  • 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.