自定义视图子类丢失引用

时间:2013-07-17 22:29:10

标签: android nullpointerexception android-custom-view

我正在尝试这样的事情

public class CustomViewSubclass extends HorizontalScrollView{

private LinearLayout layout;

public CustomViewSubclass(Context context) {
    this(context,null,0);
}

public CustomViewSubclass(Context context, AttributeSet attrs) {
    this(context,attr,0);
}

public CustomViewSubclass(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);

    layout = new LinearLayout(context);
}

// This is called from the `Activity`
public void startAsyncTask() { // code }

// This method is called in the `onPostExecute()` of an `AsyncTask` subclass
public void doSomething(Context context) {
    ImageView image = ImageView(context);

    layout.addView(image); // NullPointerException here, layout seems to be null
}

但似乎layout上的doSomething()为空。这怎么可能呢?我正在构造函数中初始化它......我再也没有重新初始化它;

我正在通过XML

添加自定义视图
<com.mypackage.CustomViewSubclass
    android:layout_width="wrap_content"
    android:layout_width="match_parent" />

1 个答案:

答案 0 :(得分:0)

好的我修好了,这是我犯的一个愚蠢的错误:

我在3种方法上使用super(),而不是使用this()

public CustomViewSubclass(Context context) {
    super(context,null,0);
}
public CustomViewSubclass(Context context, AttributeSet attrs) {
    super(context,attr,0);
}
public CustomViewSubclass(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);

    layout = new LinearLayout(context);
}

解决方案:

public CustomViewSubclass(Context context) {
    this(context,null,0);
}
public CustomViewSubclass(Context context, AttributeSet attrs) {
    this(context,attr,0);
}
public CustomViewSubclass(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);

    layout = new LinearLayout(context);
}