问题描述
这是我要实现的目标:如果按钮标题较短,则按钮的宽度应相等,但是较长的文本应以相应的按钮为代价来拉伸相应的按钮。
这是我的布局,可用于Fragment或Activity的布局。但是它不能正确显示在AlertDialog
<androidx.gridlayout.widget.GridLayout
android:layout_width="match_parent"
app:columnCount="2"
app:rowCount="1"
app:alignmentMode="alignBounds"
app:useDefaultMargins="true"
android:layout_height="wrap_content">
<com.google.android.material.button.MaterialButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="0dp"
app:layout_columnWeight="1"
app:layout_gravity="fill_horizontal"
android:text="Cancel" />
<com.google.android.material.button.MaterialButton
app:layout_columnWeight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_gravity="fill_horizontal"
android:text="Very long button title" />
</androidx.gridlayout.widget.GridLayout>
这是失败的结果,显示在布局检查器中。在这种情况下如何使这种布局起作用的任何想法?
解决方法
在此复制布局以存档所需的结果。
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.5" />
<Button
android:id="@+id/button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="32dp"
android:layout_marginEnd="8dp"
android:text="Button"
app:layout_constraintEnd_toStartOf="@+id/guideline"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="32dp"
android:layout_marginEnd="8dp"
android:text="large text Button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="@+id/guideline"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>