【问题标题】:Android - Center Grid View in Linear Layout AND use Horizontal SpacingAndroid - 线性布局中的中心网格视图并使用水平间距
【发布时间】:2015-02-16 07:39:04
【问题描述】:

我有一个 Android 应用程序,我试图在其中将网格视图以线性布局居中。我不必使用线性布局,但如果可能的话,我更喜欢。

我想在网格视图中设置水平间距(列之间的空间),以及在父级中设置网格视图的中心。

当我在 XML 中使用 android:stretchMode="none" 时,水平间距有效。但是,当我这样做时,网格视图是左对齐的。使用android:stretchMode="columnWidth" 网格视图居中,但水平间距不起作用。

我怎样才能两者兼得?

下面是我的 XML 示例(水平间距有效,居中无效):

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal">

    <GridView
        android:id="@+id/myList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:numColumns="auto_fit"

        android:horizontalSpacing="1dp"
        android:columnWidth="400dp"

        android:stretchMode="none"
        android:layout_gravity="center_horizontal">
    </GridView>


</LinearLayout>

【问题讨论】:

    标签: android android-layout gridview


    【解决方案1】:

    如果你想将一个组件作为 GridView 居中,最好的方法是使用 RelativeLayout。 您可以使用 layout_centerInParent 将水平和垂直居中或 layout_centerHorizo​​ntal 仅用于水平居中。

    例如:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    
        <GridView
            [...]
            android:layout_centerInParent="true"
            android:layout_centerHorizontal="true" >
        </GridView>
    </RelativeLayout>
    

    【讨论】:

    • @DJElbow 有用吗?或者您需要更多信息?
    • 这在我添加 android:horizontalSpacing="1dp", android:columnWidth="400dp", and android:stretchMode="none" 之前有效。我在线性布局中遇到了同样的问题。在我添加这些之前,网格视图实际上也以线性布局正确居中。
    • 您需要多少列?如果是 2,你可以将 gridlayout 的宽度设置为 802dp(columnWidth + Horizo​​ntalSpacing x2)并且它是 GridView 的中心
    • 好吧,如果可能的话,我想使用auto_fit。如果我无法弄清楚,那么我可能必须在布局上设置宽度。
    猜你喜欢
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 2013-07-08
    • 2015-07-27
    • 2016-11-25
    • 1970-01-01
    • 2012-09-27
    相关资源
    最近更新 更多