在Gridview中居中对齐项目

12

我正在使用Android Studio制作游戏,但是在Grid View组件中遇到了问题。我无法像After图像中那样使Grid View内部的项目居中对齐。我尝试了几种方法,如 android:stretchMode android:layout_centerHorizontal ,但都没有帮助。这是我的XML代码:

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

之前:

enter image description here

之后:

enter image description here


你有检查过这个吗?https://dev59.com/Dm445IYBdhLWcg3wg6xn - Sharath kumar
这个回答解决了您的问题吗?在GridView中居中元素 - Vega
2个回答

16
希望你不是必须使用GridView,因为我认为你正在寻找的基本上是不可能的。但是,如果您愿意改用RecyclerView,我有一个解决方案。
这个解决方案将利用Google的FlexboxLayout项目中的FlexboxLayoutManager部分:https://github.com/google/flexbox-layout 我的解决方案的完整代码在这里可见: https://gist.github.com/zizibaloob/0c44bfe59b371b5ae0bd2edcb4a7e592 我将在此介绍重要部分。首先,在MainActivity.onCreate()中设置FlexboxLayoutManager
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


0
在编程中,将图像和内容居中对齐的简单且更好的方法是在您的item_layout文件中使用重力属性作为中心,而不是在grid-view的父级中。

当然,这将使内容在项目中居中,但不会使网格视图中的最后一个或奇数项居中。@BenP的答案展示了您无法仅通过重力实现的解决方案。 - lostintranslation
还要添加TextView的宽度以匹配父级和textAlignment属性居中。 - Sandip Savaliya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接