我试图将两个布局一个接一个地放置,并将下一个布局保持在第一个布局的中心。 XML中的布局类似于下图
<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"
tools:context=".MainActivity">
<com.google.android.material.button.MaterialButton
android:id="@+id/button"
android:layout_width="100dp"
android:layout_height="100dp"
android:text="@string/app_name"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.button.MaterialButton
android:id="@+id/button1"
android:layout_width="100dp"
android:layout_height="70dp"
android:text="@string/app_name"
app:layout_constraintBottom_toBottomOf="@+id/button"
app:layout_constraintStart_toEndOf="@+id/button"
app:layout_constraintTop_toTopOf="@+id/button" />
</androidx.constraintlayout.widget.ConstraintLayout>
输出如下
问题是第二个布局的高度是可变的,如果它比第一个更大(假设是 170dp 而不是 70dp),那么输出是
第二版的部分内容被剪掉了。我怎样才能把它们都带进去并保持第二个布局仍然在第一个的中心。
答案 0 :(得分:2)
您的问题的一种可能解决方案是在按钮底部使用 Barrier
并将 constraintBottom
设置为 Barrier
并将 constraintTop
设置为父到两个按钮。喜欢代码:
<?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"
tools:context=".MainActivity">
<com.google.android.material.button.MaterialButton
android:id="@+id/button"
android:layout_width="100dp"
android:layout_height="100dp"
android:text="@string/app_name"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toTopOf="@id/barrier"
app:layout_constraintStart_toStartOf="parent" />
<com.google.android.material.button.MaterialButton
android:id="@+id/button1"
android:layout_width="100dp"
android:layout_height="70dp"
android:text="@string/app_name"
app:layout_constraintBottom_toTopOf="@id/barrier"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toEndOf="@+id/button" />
<androidx.constraintlayout.widget.Barrier
android:id="@+id/barrier"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:barrierDirection="bottom"
app:constraint_referenced_ids="button,button1"/>
</androidx.constraintlayout.widget.ConstraintLayout>
答案 1 :(得分:0)
将constraintlayout的布局重力设置为center可以帮到你