我正在使用包含子视图的
ConstraintLayout
。
我希望这个子视图居中,但保持纵横比。
布局(横向)变体:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/previewParent"
tools:context=".PeakerActivity">
<androidx.appcompat.widget.LinearLayoutCompat
android:layout_width="0px"
android:layout_height="0px"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintDimensionRatio="16:9"
android:background="@color/black"
android:gravity="center"
android:id="@+id/flexbox2">
</androidx.appcompat.widget.LinearLayoutCompat>
</androidx.constraintlayout.widget.ConstraintLayout>
添加
android:gravity="center"
没有效果,子视图仍然不居中。
编辑:添加图像,如您所见,左侧紫色边大于右侧。
要将子视图在 ConstraintLayout 中居中,同时保持其纵横比,您可以将其包装在另一个布局中,并将约束应用于该包装器布局。以下是修改布局的方法:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/previewParent"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".PeakerActivity">
<androidx.appcompat.widget.LinearLayoutCompat
android:id="@+id/wrapperLayout"
android:layout_width="0px"
android:layout_height="0px"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.appcompat.widget.LinearLayoutCompat
android:layout_width="0dp"
android:layout_height="0dp"
android:gravity="center"
app:layout_constraintDimensionRatio="16:9"
android:background="@color/black">
<!-- Your child views here -->
</androidx.appcompat.widget.LinearLayoutCompat>
</androidx.appcompat.widget.LinearLayoutCompat>
</androidx.constraintlayout.widget.ConstraintLayout>
在此修改后的布局中,我将子视图包装在另一个 LinearLayoutCompat 中,并将宽高比约束应用于此包装器布局。然后,我使用重力属性将子视图在此包装器布局中居中。这应该使子视图居中,同时保持其纵横比。