cdb*_*a89 8 java inheritance android relativelayout android-linearlayout
我有这个代码:
public class CopyOfLinearLayoutEntry extends LinearLayout implements Checkable {
private CheckedTextView _checkbox;
private Context c;
public CopyOfLinearLayoutEntry(Context context) {
super(context);
this.c = context;
setWillNotDraw(false);
}
public CopyOfLinearLayoutEntry(Context context, AttributeSet attrs) {
super(context, attrs);
this.c = context;
setWillNotDraw(false);
}
@Override
protected void onDraw(Canvas canvas) {
Paint strokePaint = new Paint();
strokePaint.setARGB(200, 255, 230, 230);
strokePaint.setStyle(Paint.Style.STROKE);
strokePaint.setStrokeWidth(12);
Rect r = canvas.getClipBounds();
Rect outline = new Rect(1, 1, r.right - 1, r.bottom - 1);
canvas.drawLine(r.left, r.top, r.right, r.top, strokePaint);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
// find checked text view
int childCount = getChildCount();
for (int i = 0; i < childCount; ++i) {
View v = getChildAt(i);
if (v instanceof CheckedTextView) {
_checkbox = (CheckedTextView) v;
}
}
}
@Override
public boolean isChecked() {
return _checkbox != null ? _checkbox.isChecked() : false;
}
@Override
public void setChecked(boolean checked) {
if (_checkbox != null) {
_checkbox.setChecked(checked);
}
}
@Override
public void toggle() {
if (_checkbox != null) {
_checkbox.toggle();
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在我还需要一个RelativeLayout的版本,所以我会复制类文件并将"extends LinearLayout"替换为"extends RelativeLayout".我认为那会很糟糕,因为我不想要任何重复的代码.
我怎样才能实现我的目标,看到Java不允许多重继承?
我读了一些关于合成设计模式的内容,但我不确定如何实现它.
也许有人可以给我一个关于如何最优雅地解决这个问题的起点?
根据我所学到和正在使用的,有两种方法:
您可以做您想要避免的事情(复制类文件并将“extends LinearLayout”替换为“extendsrelativelayout”)
您可以创建2个接口和1个类:一个扩展LinearLayout的接口,另一个扩展RelativeLayout的接口以及实现扩展接口的方法和变量的类。
我希望这有一点帮助
| 归档时间: |
|
| 查看次数: |
3310 次 |
| 最近记录: |