Horizontally center Views inside Android GridLayout

余生长醉 提交于 2019-12-08 18:54:05

问题


We are writing an app targeting ICS+ and believe a GridLayout is the best layout paradigm, but it seems very little has been written about it, and we are having some alignment issues.

<GridLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/row_background"
    android:rowCount="1"
    android:columnCount="3"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:useDefaultMargins="true"
    android:background="@drawable/list_item_bg">

    <ImageView
        android:id="@+id/visibilityIcon"
        android:layout_row="0"
        android:layout_column="0"
        android:src="@drawable/visibility_icon" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"/>

    <ImageView
        android:id="@+id/windIcon"
        android:layout_row="0"
        android:layout_column="1"
        android:src="@drawable/wind_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"/>

    <ImageView
        android:id="@+id/crosswindIcon"
        android:layout_row="0"
        android:layout_column="2"
        android:src="@drawable/cloud_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"/>

</GridLayout>

However, the left 2 icons remain left-aligned, and the right-most icon centers with the remaining space.

Essentially what we need to do is specify the size of each column to be 1/3 (since 3 columns) of the total screen size. I thought this is what GridLayout did, but it appears 'wrap_content' causes this behavior (makes sense), but 'match_parent' causes the first column to fill the entire screen, rather than fill its cell which is the behavior I would have expected.

We seem to have tried every combination of gravity, layout_gravity, etc., but either we fundamentally are doing something wrong, or have found a limitation of the GridLayout.

Thanks for your help!


回答1:


Only one row and one column is allowed to grow in a GridLayout, and that is the one with gravity along that axis. If more than one row or column specify gravity only one will get it (if I remember it is the "last" one). Choose another layout or write your own. If you only want a row with equally split icons you can use a LinearLayout where the widths of the components are 0px and the weight are all the same, e.g. 1.



来源:https://stackoverflow.com/questions/12379012/horizontally-center-views-inside-android-gridlayout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!