2013-07-17 108 views
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 
} 

的東西,但它似乎layoutdoSomething()爲空。這怎麼可能呢?我正在初始化它的構造函數...並且我不再重新初始化它;

我通過XML

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

嘗試實例化它的onCreate(),而不是構造 – invertigo

+0

你能後的堆棧跟蹤? – Vikram

回答

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

如果調用構造函數「CustomViewSubClass(Context)」和「CustomViewSubClass(Context,AttributSet)」,'layout'是否爲'null'?如果你現在的問題確實得到解決,我建議你看看你的代碼中的其他地方,因爲把'this'改爲'super'很可能不能解決問題。 – Vikram

+0

不,我的意思是我使用super()而不是this() –