ViewStub raises error while inflating more than one layouts conditionally

橙三吉。 提交于 2019-12-01 17:02:14

问题


In my app, I am having a spinner, and a ViewStub, depending upon the user item selection from spinner, I have to inflate different layouts and show the inflated layout below the spinner. When my app starts, ViewStub successfully inflates a layout on first time selection of any item from spinner. When I tries to select a new item from spinner, it raises Exception below

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

My code so far is

@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 is a ViewStub object created inside onCreate() of the Activity.

Here is my main layout xml code

<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>

Can anybody please tell me where I am going wrong. If you have any other solution to solve this please share.

Thanks.


回答1:


ViewStub is not designed to be used in scenarios like this one. After the stub is inflated, the stub is removed from the view hierarchy. That's why it has no parent and mentioned IllegalStateException raised. ViewStub can’t be used more than once. Also keeping long-lived reference to a ViewStub is unnecessary, if it is required, it's good practice to null it after inflating, so GC can eat it.

Consider using addView() / removeView() to replace your views. Or better use ViewFlipper.



来源:https://stackoverflow.com/questions/11578653/viewstub-raises-error-while-inflating-more-than-one-layouts-conditionally

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!