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);
}
2
  • What seems to be the problem? Commented Jan 5, 2017 at 18:32
  • My error is: Error:(78, 61) error: cannot find symbol class context
    – Alex Mamo
    Commented Jan 5, 2017 at 18:33

1 Answer 1

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

1
  • @AlexM. i am glad that i could help , happy coding Commented Jan 5, 2017 at 18:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.