并排两个按钮,水平自动填充

问题描述

这是我要实现的目标:如果按钮标题较短,则按钮的宽度应相等,但是较长的文本应以相应的按钮为代价来拉伸相应的按钮。

enter image description here

enter image description here

这是我的布局,可用于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>

这是失败的结果,显示在布局检查器中。在这种情况下如何使这种布局起作用的任何想法?

enter image description here

解决方法

在此复制布局以存档所需的结果。

<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>

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...