向后兼容的LinearLayout构造函数

时间:2012-11-01 11:22:28

标签: java android android-linearlayout backwards-compatibility super

我正在编写一款需要在Android 2.3.3上运行的Android应用程序(yeay fragmentation!)。从那个版本开始,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)?显然我可能最终只会使用双参数版本,但我想知道是否有更好的方法。

1 个答案:

答案 0 :(得分:0)

你可以有两个构造函数,如下所示。在Gingerbread中使用一个,在Honeycomb及以上使用另一个。

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);
    }
}