android - 在 Gridview 中居中对齐项目

标签 android gridview

我在 Android Studio 上制作游戏时遇到了 GridView 组件的问题。我无法将 GridView 中的项目居中对齐,例如 After图片。我尝试了几种方法,例如 android:stretchModeandroid:layout_centerHorizo​​ntal 但它没有帮助。这是我的 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

最佳答案

希望您使用 GridView 不是对您的严格要求,因为我相信您正在寻找的东西基本上是不可能的。但是,如果您愿意改用 RecyclerView,我有适合您的解决方案。

此解决方案将使用 FlexboxLayoutManager,它是 Google 的 FlexboxLayout 项目的一部分: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),它为每个项目 View 提供四分之一的可用宽度。如果您想要不同数量的列,只需将 4 更改为 8 等。

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

将它们放在一起,您会得到一个如下所示的应用:

enter image description here enter image description here

关于android - 在 Gridview 中居中对齐项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43407960/

相关文章:

gridview - 没有页面后代码的错误捕获

Android FrameLayouts 并排与独立的内部滚动

android - install_failed_no_matching_abis 更新到 android 8.0 oreo 后无法提取 native 库 res=-113

java - Nexus 5 通知灯光颜色

ajax - Internet Explorer错误

c# - 如何从 GridView 内的单元格中获取值

ASP.NET GridView排序升序标题样式不起作用

android - 如何将现有的基于 IDEA Scala 的 Android 项目迁移到 SBT?

java - JodaTime 无法标准化 periodType

javascript - JavaScript 中的 Gridview 行验证