How do i create a custom start activity method in android?

2.2k views Asked by At

I want to create a method to start multiple activities. I have set setOnClickListener on every button. I have implemented onClick() method that looks like this:

public void onClick(View view) {
    switch (view.getId()) {
        case R.id.firstActivityButton:
            Intent i1 = new Intent(getApplicationContext(), FirstActivity.class);
            startActivity(i1);
            break;

        case R.id.secondActivityButton:
            Intent i2 = new Intent(getApplicationContext(), SecondActivity.class);
            startActivity(i2);
            break;

        //and so on
    }
}

I want to use a method in every case like this: startSpecificActivity(FirstActivity.class) This is my method:

public void startSpecificActivity(Context context) {
    Intent intent = new Intent(getApplicationContext(), context.class);
    startActivity(intent);
}
1

There are 1 answers

1
Pavneet_Singh On BEST ANSWER
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.firstActivityButton:
            startSpecificActivity(FirstActivity.class);
            break;

        case R.id.secondActivityButton:
            startSpecificActivity(SecondActivity.class);
            break;

        // And so on
    }
}

Create method like this where Class<?> is a generic class object holder and ? is a wildcard character:

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

And I also encourage to use the context or YourActivityName.this of current Activity, instead of getApplicationContext().