2012-07-20 86 views
7

在我的應用程序中,我有一個微調和一個ViewStub,這取決於來自微調框的用戶項目選擇,我必須膨脹不同的佈局並在下面顯示膨脹的佈局微調。當我的應用程序啓動時,ViewStub在第一次從微調器中選擇任何項目時成功地擴展了佈局。當我試圖從紡紗一個新的項目,它提出了以下ViewStub引發錯誤,同時膨脹多個佈局有條件

java.lang.IllegalStateException: ViewStub must have a non-null ViewGroup viewParent 

我的代碼異常到目前爲止

@Override 
public void onItemSelected(AdapterView<?> pParent, View pView, int pPosition, long pId) { 

if(pPosition == 1){ 
    m_cStub.setLayoutResource(R.layout.text_form); 
}else if(pPosition == 2){ 
    m_cStub.setLayoutResource(R.layout.integer_form); 
} 
View inflated = m_cStub.inflate(); 
} 

m_cStub裏面的onCreate(創建)的一個ViewStub對象活動。

這是我的主要佈局的XML代碼

<RelativeLayout..................> 
    <spinner......................./> 

    <ViewStub android:id="@+id/dynamic_form_layout" 
    android:inflatedId="@+id/dynamic_form_inflated_id" 
    android:layout_alignParentBottom="true" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"/> 
</RelativeLayout> 

可有人請告訴我在哪裏,我錯了。如果您有任何其他解決方案來解決這個問題,請分享。

謝謝。

+0

這只是猜測嘗試這個'pView = m_cStub.inflate();' – MAC 2012-07-20 11:50:14

+0

@ gtumca-MAC它不會工作,因爲錯誤是與ViewStub不與View。 – 2012-07-20 11:54:12

回答

22

ViewStub不適用於像這樣的場景。存根充氣後,存根從視圖層次中刪除。這就是爲什麼它沒有父母,並提到IllegalStateException提出。 ViewStub不能使用多次。如果需要,也可以保留長期參考ViewStub,如果需要的話,充氣後null是很好的做法,所以GC可以吃它。

考慮使用addView()/removeView()來替換您的視圖。或者更好地使用ViewFlipper