2

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);
}
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193

1 Answers1

11
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().

Diogo Correia
  • 43
  • 3
  • 6
Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68