【问题标题】:Backwards compatible LinearLayout constructor向后兼容的 LinearLayout 构造函数
【发布时间】:2012-11-01 11:22:28
【问题描述】:

我正在编写一个需要在 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)?显然我最终可能会一直使用双参数版本,但我想知道是否有更好的方法。

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2014-08-25
      • 2013-02-23
      • 1970-01-01
      • 2013-03-03
      • 2015-01-18
      • 1970-01-01
      • 1970-01-01
      • 2018-12-09
      相关资源
      最近更新 更多