In Java, How do I simplify my code using inheritan

2019-07-05 02:43发布

问题:

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.

回答1:

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


回答2:

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.



标签: java android oop