在Gridview中居中对齐项目

时间:2017-04-14 08:29:30

标签: android gridview

我正在使用Android Studio制作游戏,但网格视图组件存在问题。我无法将网格视图中的项目居中对齐,如After图像。我尝试了几种方式,例如android:stretchModeandroid:layout_centerHorizontal,但它没有帮助。这是我的XML代码:

<RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="@android:color/holo_orange_light"
        android:layout_weight="8"
        android:layout_gravity="center">

        <GridView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="10px"
            android:id="@+id/gridAnswersChar"
            android:numColumns="8"
            android:gravity="center">
        </GridView>

</RelativeLayout>

在:

enter image description here

后:

enter image description here

2 个答案:

答案 0 :(得分:13)

希望您使用GridView并不严格要求,因为我相信您所寻找的内容基本上是不可能的。但是,如果您愿意使用RecyclerView,我会为您提供解决方案。

此解决方案将使用FlexboxLayoutManager,这是Google的 FlexboxLayout 项目的一部分:https://github.com/google/flexbox-layout

我的解决方案的完整代码在此处可见: https://gist.github.com/zizibaloob/0c44bfe59b371b5ae0bd2edcb4a7e592

我将在这里介绍重要的内容。首先,在FlexboxLayoutManager中设置MainActivity.onCreate()

FlexboxLayoutManager manager = new FlexboxLayoutManager(this, FlexDirection.ROW);
manager.setJustifyContent(JustifyContent.CENTER);

RecyclerView recycler = (RecyclerView) findViewById(R.id.recycler);
recycler.setLayoutManager(manager);

当我们创建布局管理器时,我们传递FlexDirection.ROW告诉它我们希望它将我们的项目水平放置(即填充一行然后流到下一行,而不是填满列和然后流到下一栏。)

然后我们使用setJustifyContent()致电JustifyContent.CENTER告诉经理我们希望部分填充的行居中。

第二个重要的部分是我们模仿GridView的行为及其具有一定数量列的能力的方式。此代码位于MyAdapter.onCreateViewHolder()

ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) itemView.getLayoutParams();
layoutParams.width = (parent.getWidth() / 4) - layoutParams.leftMargin - layoutParams.rightMargin;
itemView.setLayoutParams(layoutParams);

此处的关键是(parent.getWidth() / 4),它为每个项目提供了可用宽度的四分之一。如果您想要不同数量的列,只需将4更改为8等。

我们还从宽度中减去leftMarginrightMargin,因为我们的项目视图有边距,我们需要为它们留出空间。如果您的观点没有边距,则可以跳过此处。

将所有内容放在一起,您就会得到一个如下所示的应用:

enter image description here enter image description here

答案 1 :(得分:0)

在中心对齐图像和内容的简单方法是使用重力作为item_layout文件的中心,而不是网格视图的父级。

相关问题