【问题标题】:Android GridLayout: How to align child view to right with its column width proportionalAndroid GridLayout:如何将子视图与其列宽成比例地对齐
【发布时间】:2022-11-03 17:22:21
【问题描述】:

我有一个有两列的网格,每列都有一个标签。我希望第二列的标签向右对齐:

<androidx.gridlayout.widget.GridLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00FF00"
    app:columnCount="2">

    <TextView
        android:text="Cell 0"
        app:layout_column="0"
        app:layout_columnWeight="1"
        android:background="#FF0000" />

    <TextView
        android:text="Cell 1"
        app:layout_column="1"
        app:layout_columnWeight="1"
        app:layout_gravity="right"
        android:background="#0000FF"/>

</androidx.gridlayout.widget.GridLayout>

我怎样才能使第一列成为平等的到第二列,就像在下面的模型中一样?

我尝试设置android:gravity="right",但它解决了一半的问题。列的宽度相等,但蓝色标签填满了列:

        <TextView
            android:text="Cell 1"
            app:layout_column="1"
            app:layout_columnWeight="1"
            android:gravity="right"
            android:background="#0000FF"/>

GridLayout 计算比例大小的列的宽度的方式非常奇怪。它似乎考虑了子视图的宽度。该文档无助于描述 layout_columnWeight 的工作原理。

【问题讨论】:

  • 尝试android:gravity="right" 而不是app:layout_gravity="right"
  • @Omkar 谢谢,但它不会产生我期望的结果。两列相等,但蓝色 TextView 水平填充列。我需要它保持与右侧对齐。

标签: java android android-gridlayout


【解决方案1】:

试试下面的代码,这可能会产生你所期望的结果

 <androidx.gridlayout.widget.GridLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="#00FF00"
    app:columnCount="2"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView
        android:text="Cell 0"
        app:layout_column="0"
        app:layout_columnWeight="1"
        android:background="#FF0000" />

    <LinearLayout
        app:layout_column="1"
        app:layout_columnWeight="1"
        android:gravity="right">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Cell 1"
            android:background="#0000FF"/>
    </LinearLayout>

</androidx.gridlayout.widget.GridLayout>

【讨论】:

  • 谢谢,有没有包装LinearLayout的方法?如果我在 UI 的所有地方都这样做,它会使布局变得更加复杂。
猜你喜欢
  • 2021-05-01
  • 1970-01-01
  • 2014-11-02
  • 2018-02-05
  • 2014-05-19
  • 1970-01-01
  • 1970-01-01
  • 2016-10-14
  • 1970-01-01
相关资源
最近更新 更多