问题描述
这是我的用例:
我想在运行时更改膨胀的布局,例如首先膨胀a的布局,然后过一段时间,我要显示B的布局,然后显示C的布局,等等.
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.
我读了某个地方,而不是在主布局中包括布局,然后隐藏/取消隐藏,我应该使用viewtub和inflate.
I read somewhere that rather than including layouts in main layout and then hiding/unhiding I should use viewstub and inflate.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ViewStub
android:id="@+id/layout_stub"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
我现在的问题是,当我为第一个布局充气时,它可以正常工作,但是下次,当我尝试为第二个布局充气时,则存根为空.
My issue now is when I inflate the first layout it works fine but the next time when I try to inflate the second layout I get the stub null.
ViewStub stub = (ViewStub) findViewById(R.id.layout_stub);
stub.setLayoutResource(layoutId);
View inflated = stub.inflate();
我的理解是Viewstub是一个在其中加载布局的容器(如果有的话)为什么在尝试加载第二个布局时没有得到ViewStub?(因此,这意味着当我放大第一个布局(A)时,已完全删除放置ViewStub的布局吗?)
My understanding is the Viewstub is a container in which the layouts are being loaded, if sowhy am I not getting the ViewStub when trying to load the second layout?(So this means when I inflated the first layout (A) the layout in which the ViewStub was placed was removed completely?)
我正在寻找使用Viewstub或替代方案实现用例的任何指针.
I'm looking for any pointers to implementing my usecase with Viewstub or alternatives.
推荐答案
一个 ViewStub是一个占位符,当调用ViewStub.inflate()时,该占位符将由膨胀的布局替换.再次调用inflate没有意义,因为ViewStub将不再位于层次结构中.相反,您应该获得对LinearLayout的引用,删除其视图,然后将第二个布局添加为子布局.
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));
这篇关于Android ViewStub以编程方式更改布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!