In Java, How Do I Simplify My Code Using Inheritance? (android Dev.)
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 =
Solution 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:
publicclassHomeButtonHandlerimplementsOnClickListener{
@OverridepublicvoidonClick(View v) {
IntentmenuIntent=newIntent(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(newHomeButtonHandler());
Solution 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.
Post a Comment for "In Java, How Do I Simplify My Code Using Inheritance? (android Dev.)"