我想将 ViewStub
添加到我的布局中。 ViewStub
应该是这样的,如 xml:
<ViewStub
android:id="@+id/viewstub_id"
android:layout="@layout/use_this_layout"
android:inflatedId="@+id/inflated_stub"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
我已经想出了这段代码,但布局没有显示。
我正在重复使用 id
,因为我要删除并再次添加 stub 。我猜代码不起作用与约束或布局宽度/高度有关,但我不确定。我做错了什么?
ViewStub vs = new ViewStub(this);
vs.setId(R.id.viewstub_id);
vs.setLayoutResource(R.layout.use_this_layout);
vs.setInflatedId(R.id.inflated_stub);
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(0, 0);
vs.setLayoutParams(layoutParams);
ConstraintLayout cl = findViewById(R.id.viewStubWrapper);
ConstraintSet cs = new ConstraintSet();
cs.clone(cl);
cs.connect(ConstraintSet.PARENT_ID, ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM);
cs.applyTo(cl);
cl.addView(vs); // the ConstraintLayout is the ViewStub's parent
vs.inflate();
最佳答案
我发现了一些似乎有效的东西:
ViewStub vs = new ViewStub(this);
vs.setId(R.id.viewstub_id);
vs.setLayoutResource(R.layout.use_this_layout);
vs.setInflatedId(R.id.inflated_stub);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
vs.setLayoutParams(lp);
ConstraintLayout cl = findViewById(R.id.viewStubWrapper);
cl.addView(vs);
vs.inflate();
看来我毕竟不需要约束,我只需要使用 LayoutParams.MATCH_PARENT
作为宽度和高度,而不是 0。
关于java - 如何以编程方式创建 Android ViewStub?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59546254/