我正在为 Android 创建自定义布局。 布局实现完全相同,但是一次我需要从RelativeLayout 扩展,一次需要从LinearLayout 扩展。
class Layout1 extends LinearLayout {
// methods and fields
}
class Layout2 extends RelativeLayout {
// the same EXACT methods and fields
}
如何使用继承来避免代码重复并一次性实现我的方法。
最佳答案
您可以使用组合和类似“策略”模式的东西:
class YourLayout extends ViewGroup {
ViewGroup strategy;
public YourLayout( Condition someCondition ) {
if( someCondition.useLinear() ) {
strategy = new LinearLayout(); // or Layout1
} else {
strategy = new RelativeLayout();
}
}
public View findFocus() {
return strategy.findFocus();
}
.... rest of the methods:
/ rest of specific EXACT methods and fields
}
您甚至可以在运行时更改策略
。
这样您的 YourLayout
类就可以使用这两种方案。
关于java - 继承问题/问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2981451/