我创建了一个保留方面的自定义MyAspectButton
:
public class MyAspectButton extends Button
{
private float m_aspect = -1.f;
// ...
// ... Constructors, setters/getters ...
// ...
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
if (aspect >= 0.f)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
final int measuredWidth = getMeasuredWidth();
widthMeasureSpec = MeasureSpec.makeMeasureSpec(measuredWidth, MeasureSpec.EXACTLY);
heightMeasureSpec = MeasureSpec.makeMeasureSpec(Math.round(measuredWidth * aspect), MeasureSpec.EXACTLY);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
现在我希望MyAspectLinearLayout
,MyAspectRelativeLayout
等等。他们的onMeasure
方法将是相同的。
如何使用尽可能少的复制粘贴实现一堆这些类?
我知道Java中泛型类的概念,但在这里我必须继承编译器不允许我做的模板参数:
public class MyAspectWidget<T> extends T
{
// ...
}
无法编译。
答案 0 :(得分:1)
如果我理解正确,你想从一堆不同的基类继承,但对所有基类应用相同的行为:
MyAspectButton extends Button
MyAspectLinearLayout extends LinearLayout
MyAspectRelativeLayout extends RelativeLayout
您正在寻找的是多重继承,Java不支持。您唯一的选择是拥有一个执行测量逻辑的类,您的每个子类的onMeasure
方法都会调用它:
public class MyAspectButton extends Button
{
private float m_aspect = -1.f;
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
super.onMeasure(MyMeasuringClass.MeasureWidth(this, widthMeasureSpec), MyMeasuringClass.MeasureHeight(this, heightMeasureSpec));
}
}