2

我正在编写一个需要在 Android 2.3.3 上运行的 Android 应用程序(是的,碎片化!)。由于那个版本,LinearLayout引入了一个额外的构造函数,所以我希望能够做这样的事情:

public class ActionMenuTextItemView extends LinearLayout
{
    public ActionMenuTextItemView(Context context, AttributeSet attrs, int defStyle)
    {
        if (android.os.Build.VERSION.SDK_INT >= 11)
            super(context, attrs, defStyle);
        else
            super(context, attrs);
    }

它不起作用,因为super必须是第一行。有没有办法解决这个问题(除了构建两个版本的 APK)?显然我最终可能会一直使用双参数版本,但我想知道是否有更好的方法。

4

1 回答 1

0

您可以有两个构造函数,如下所示。在姜饼中使用一种,在蜂窝及更高版本中使用另一种。

public class ActionMenuTextItemView extends LinearLayout
{
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public ActionMenuTextItemView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
    }

    public ActionMenuTextItemView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }
}
于 2013-10-08T09:33:07.317 回答