Android ViewStub change layouts programmatically

前端 未结 2 600
长发绾君心
长发绾君心 2021-01-03 08:24

This is my use case:

I want to change my inflated layout at run time, say first I inflate layout a, then after some time I want to show layout B, then layout C etc.<

2条回答
  •  死守一世寂寞
    2021-01-03 09:00

    A ViewStub is a placeholder, which is replaced by an inflated layout as soon as ViewStub.inflate() is called. It doesn't make sense to call inflate a second time, as the ViewStub will no longer be in the hierarchy. Instead, you should obtain a reference to your LinearLayout, remove its views, and add your second layout as a child.

    ViewStub stub = (ViewStub) findViewById(R.id.layout_stub);
    LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
    stub.setLayoutResource(layoutId);
    stub.inflate(); // inflate 1st layout
    
    ll.removeAllViews(); // remove previous view, add 2nd layout
    ll.addView(LayoutInflater.from(context).inflate(secondLayoutId, ll, false));
    

提交回复
热议问题