在Java中,如何使用继承简化代码? (Android开发.) [英] In Java, How do I simplify my code using inheritance? (Android Dev.)
问题描述
在各种活动中,我都有非常相似的方法.
In various activities I have very similar methods.
例如:
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.ibHome:
Intent menuIntent = new Intent(v.getContext(),Menu.class);
startActivity(menuIntent);
break;
}
}
和
@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;
是否有一种方法(我认为将使用继承)来防止在每个类中明确声明 menuIntent ?
is there a way (which I assume would be using inheritance) to prevent the menuIntent being explicitly stated in each each class?
谢谢.
推荐答案
您可以使用继承,但这实际上并不是最佳选择,特别是如果两个活动不是直接以"Is-A"关系关联的话.
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.
在这种情况下,最好声明一个实现OnClickListener接口的新类.然后,您可以实例化该类并将其绑定到按钮的单击事件,无论它们在何处使用.
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.
这是一个例子:
public class HomeButtonHandler implements OnClickListener{
@Override
public void onClick(View v) {
Intent menuIntent = new Intent(v.getContext(),Menu.class);
v.getContext().startActivity(menuIntent);
}
}
在您的活动中,您只需将HomeButtonHandler绑定到按钮的onClickListner:
And in your activities, you can just bind the HomeButtonHandler to the onClickListner of the button:
homeButton.setOnClickListener(new HomeButtonHandler());
这篇关于在Java中,如何使用继承简化代码? (Android开发.)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!