我有一个ConstraintLayout,其中包含ViewStub
,其中app:constraintHeight_default
属性设置为XML中的spread
。我需要能够在运行时更新此属性以使其值为wrap
,但到目前为止,没有任何内容对我有用。这是布局:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/constraint_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipChildren="false"
android:clipToPadding="false"
>
<ViewStub
android:id="@+id/view_stub"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="@+id/bottom_view"
app:layout_constraintTop_toBottomOf="@+id/top_view"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHeight_default="spread"
/>
<com.example.TopView
android:id="@+id/top_view"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toTopOf="@id/view_stub"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHeight_default="wrap"
/>
<com.example.BottomView
android:id="@+id/bottom_view"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="@id/fields_stub"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHeight_default="wrap"
/>
到目前为止,我已尝试使用ConstraintSet
以编程方式设置constraintHeight_default
,但从ViewStub
膨胀的布局最终有0宽度和0高度,所以它不是'在布局中呈现。
ConstraintLayout constraintLayout = root.findViewById(R.id.constraint_layout);
ConstraintSet constraintSet = new ConstraintSet();
constraintSet.clone(constraintLayout);
constraintSet.constrainHeight(R.id.view_stub, ConstraintSet.MATCH_CONSTRAINT_WRAP);
constraintSet.applyTo(constraintLayout);
ViewStub viewStub = root.findViewById(R.id.view_stub);
viewStub.setLayoutResource(R.layout.custom_layout);
viewStub.inflate();
如何设置ViewStub
的高度以编程方式包裹其高度?
答案 0 :(得分:1)
尝试更改以下行:
constraintSet.constrainHeight(R.id.view_stub, ConstraintSet.MATCH_CONSTRAINT_WRAP);
to constrainDefaultHeight
constraintSet.constrainDefaultHeight(R.id.view_stub, ConstraintSet.MATCH_CONSTRAINT_WRAP);
请参阅ConstraintSet documentation。
constrainDefaultHeight
void constrainDefaultHeight(int viewId, int height)
设置如何计算高度以太MATCH_CONSTRAINT_WRAP或MATCH_CONSTRAINT_SPREAD。默认是传播。