0

我正在尝试这样的事情

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
}

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

我正在通过添加我的自定义视图XML

<com.mypackage.CustomViewSubclass
    android:layout_width="wrap_content"
    android:layout_width="match_parent" />
4

1 回答 1

0

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

我使用super()了 3 种方法,而不是使用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);
}
于 2013-07-17T23:01:45.260 回答