我正在尝试从抽象ClassB向ClassA传递一些视图,以便ClassA可以使用:ClassA extends ClassB
我希望继承/传递每个视图而不是使用类似的东西:
protected View getView1() {
return view1;
}
我想要一种批量方式让ClassX(在本例中为ClassA)知道它应该使用哪些视图。但是保留一些专用于ClassB的视图以供自己使用。
下面的代码确实有效,但是可以这样做吗?还是有更好的方法?
public abstract class ClassB extends Activity {
abstract void useTheseViews(View view1, View view2);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View view1 = findViewById(R.id.view1);
View view2 = findViewById(R.id.view2);
useTheseViews(view1, view2);
View view3 = findViewById(R.id.view3);
view3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// do something independent here
}
});
}
}
public class ClassA extends ClassB {
private View view1, view2;
@Override
void useTheseViews(View view1, View view2) {
this.view1 = view1;
this.view2 = view2;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
view1.setOnClickListener(..);
view2.setOnClickListener(..);
}
}
原因? ClassA和ClassX使用相同的基本布局,但在相同的视图上执行不同的功能。
我的ClassB拥有一个基本布局并初始化视图(按钮,开关......),并为自己使用一些视图,无论哪个类扩展它。
答案 0 :(得分:0)
我会这样做
public abstract class ClassB extends Activity {
private View view1, view2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view1 = findViewById(R.id.view1);
view2 = findViewById(R.id.view2);
}
protected View getView1(){
return view1;
}
protected View getView2(){
return view2;
}
}
public class ClassA extends ClassB {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getView1().setOnClickListener(..);
getView2().setOnClickListener(..);
}
}
如果您不想为每个视图创建受保护的getter,请使用holder类
public abstract class ClassB extends Activity {
protected class ViewHolder {
public final View view1, view2;
public ViewHolder(){
view1 = findViewById(R.id.view1);
view2 = findViewById(R.id.view2);
}
}
private ViewHolder viewHolder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewHolder = new ViewHolder();
}
protected ViewHolder getViewHolder(){
return viewHolder;
}
}
public class ClassA extends ClassB {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getViewHolder().view1.setOnClickListener(..);
getViewHolder().view2.setOnClickListener(..);
}
}
我建议的方式似乎与OOP一致,如果你说ClassA和ClassB,我会认为ClassA扩展了ClassB。如果要创建扩展ClassA的第三个类,会发生什么?