我想在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
,因为我正在删除并再次添加存根。我猜代码不起作用与约束或布局宽度/高度有关,但我不确定。我究竟做错了什么?
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();