我有这个代码:
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();
}
}
}
现在我还需要一个RelativeLayout 版本,所以我会复制类文件并将“扩展LinearLayout”替换为“扩展RelativeLayout”。我认为那会很糟糕,因为我不想要任何重复的代码。
看到 Java 不允许多重继承,我将如何实现我的目标?
我读了一些关于组合设计模式的东西,但我不知道如何实现它。
也许有人可以给我一个关于如何最优雅地解决这个问题的起点?