3

In various activities I have very similar methods.

For example:

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.ibHome:
        Intent menuIntent = new Intent(v.getContext(),Menu.class);
        startActivity(menuIntent);
        break;
    }

}

and

@Override
public void onClick(View v) {
     /**  */

    //
    switch(v.getId()){
        case R.id.bNew:
            Intent newSwimmerIntent = new Intent(v.getContext(),NewSwimmer.class);
            startActivity(newSwimmerIntent);
            break;
case R.id.ibHome:
            Intent menuIntent = new Intent(v.getContext(),Menu.class);
            startActivity(menuIntent);
            break;

is there a way (which I assume would be using inheritance) to prevent the menuIntent being explicitly stated in each each class?

Thanks.

Sheldon
  • 9,639
  • 20
  • 59
  • 96

2 Answers2

2

You could use inheritance, but that actually may not be the best choice, especially if the two activities are not directly related in an "Is-A" relationship.

In this case, you're probably better off declaring a new class that implements OnClickListener interface. You can then instantiate that class and bind it to your buttons' click events wherever they're used.

Here's an example:

public class HomeButtonHandler implements OnClickListener{

        @Override
        public void onClick(View v) {
            Intent menuIntent = new Intent(v.getContext(),Menu.class);
            v.getContext().startActivity(menuIntent);            

        }

    }

And in your activities, you can just bind the HomeButtonHandler to the onClickListner of the button:

homeButton.setOnClickListener(new HomeButtonHandler());
Chris
  • 22,923
  • 4
  • 56
  • 50
  • Could you give a code example for this? I'm new to Java and although I understand the concept, I'm not really sure how to implement it. Thanks. – Sheldon Nov 19 '11 at 12:22
  • I tried to implement this but it crashes the app. I think it's because HomeButtonHandler would have have to inherit from Activity to use the startActivity method. – Sheldon Nov 19 '11 at 13:55
  • 2
    it would, you can adapt this to take the context from the view passed in to onClick and call startActivity using that. I edited my answer to illustrate. – Chris Nov 19 '11 at 15:16
1

Create a common BaseActivity for all your activities, then override only the BaseActivity.onClick() method.

In this way you will have a single switch for all your activities.

Dalmas
  • 26,409
  • 9
  • 67
  • 80