【问题标题】:LinearLayout super(context) exception on android 2.3.3android 2.3.3 上的 LinearLayout 超级(上下文)异常
【发布时间】:2013-07-02 07:47:29
【问题描述】:

我在扩展 LinearLayout 的自定义视图类的构造函数中的 super(context) 行上有一个 NullPointerException。使用android 4.1.2虚拟设备测试没有出现问题。

public class customView extends LinearLayout {
  private NavigationBar navigationBar;
  private Activity activity;
  public customView(Context context) {
    super(context);
    activity = (Activity) context;
    navigationBar = new NavigationBar(context);
    LayoutParams Params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    setLayoutParams(Params);
    setOrientation(LinearLayout.VERTICAL);
    this.addView(navigationBar);
}

【问题讨论】:

    标签: android android-linearlayout superclass android-2.3-gingerbread


    【解决方案1】:

    你必须改变它:

    public class customView extends LinearLayout {
          private NavigationBar navigationBar;
    
          public customView(Context context)
       {
             super(context);
    
    
         navigationBar = new NavigationBar(context);
         LayoutParams Params = new LayoutParams(LayoutParams.FILL_PARENT,   LayoutParams.FILL_PARENT);
         setLayoutParams(Params);
         setOrientation(LinearLayout.VERTICAL);
    
         this.addView(navigationBar);
    }
    

    【讨论】:

    • 没有必须定义隐式超级构造函数LinearLayout()。
    【解决方案2】:

    试试这个:

    public class MyLinearLayout extends LinearLayout
    {
    
        public MyLinearLayout(Context context)
        {
            super(context);
            Init(context);
        }
    
        public MyLinearLayout(Context context, AttributeSet attrs)
        {
            super(context, attrs);
            Init(context);
        }
    
        private void Init(Context context)
        {
            activity = (Activity) context;
    
            navigationBar = new NavigationBar(context);
            LayoutParams Params = new LayoutParams(LayoutParams.FILL_PARENT,         LayoutParams.FILL_PARENT);
            setLayoutParams(Params);
            setOrientation(LinearLayout.VERTICAL);
    
            this.addView(navigationBar);
        }
    }
    

    【讨论】:

    • 我发现了错误。我在自定义 LinearLayout 类中错误地覆盖了 invalidate() 方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-28
    • 2013-10-14
    • 2017-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多