我是Android / Java新手,我有一个基于以下场景的问题:
问题:我是否应该在 BaseActivity 或 A1 和 A2 活动中实施 PartDialogFragment 界面?
基本上,我正在考虑做这样的事情:
class PartDialogFragment extends DialogFragment{
private PartListener mPartListener;
public interface PartNumberListener{
void onPartEntered(String part#);
}
...
...
@Override
public void onAttach(Activity activity){
super.onAttach(activity);
try{
mPartListener = (PartListener) activity;
} catch(ClassCastException e){
throw new ClassCastException(activity.toString() + " must implement PartListener");
}
}
...
...
}
public abstract class BaseActivity
implements PartDialogFragment.PartNumberListener { //**should I implement it here?**
...
...
public void ShowPartNumberDialog(){
//creates and shows PartDialogFragment defined above
}
}
public class A1 extends Activity
implements PartDialogFragment.PartNumberListener { //**or in A1 and A2?**
...
...
if (something){
ShowPartNumberDialog(); //this is defined in BaseActivity
}
}
public class A1 extends Activity
implements PartDialogFragment.PartNumberListener { //**or in A1 and A2?**
...
...
if (something){
ShowPartNumberDialog(); //this is defined in BaseActivity
}
}
public class A3 extends Activity{
...
...
//**this will never ask for Part#, so no need to implement PartDialogFragment.PartNumberListener here.**
}
答案 0 :(得分:1)
您可以拥有abstract PartActivity
来实现onPartEntered
逻辑。 A1
和A2
将对PartActivity
进行扩展,A3
会直接扩展BaseActivity
,因此不会有此逻辑。
答案 1 :(得分:1)
A1和A2活动需要实现接口,因为如果基类是抽象的,那么根据定义,您需要创建它的子类来实例化。子类(由编译器)将需要实现抽象类遗漏的任何接口方法。