0

我在扩展 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);
}
4

2 回答 2

1

尝试这个:

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);
    }
}
于 2013-07-04T11:13:54.007 回答
0

你必须改变它:

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);
}
于 2013-07-04T10:37:46.067 回答