java - 如何使 RecyclerView 水平居中?
问题描述
只是试图将我的 RecyclerView 水平居中,但像重力:“center”或 layout_centerHorizontal="true" 这样的线条不起作用。
这是xml:
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
这里是java代码:
mRecyclerView = findViewById(R.id.recycler_view);
itemLayoutManager = new GridLayoutManager(this, 3);
mRecyclerView.setLayoutManager(itemLayoutManager);
...
mItemAdapter = new ItemAdapter(MainActivity.this, mItemList);
mRecyclerView.setAdapter(mItemAdapter);
当我运行应用程序时,recyclerview 左对齐。[![图片][1]][1]
我究竟需要做什么才能使内容居中以使左右边距相同?谢谢。[1]:https ://i.stack.imgur.com/0LNoY.png
解决方案
它不居中,因为 layout_width 都是 match_parrent 尝试在 recyclerview 上使用 wrap_content 并在 recyclerview 上使用 layout_centerHorizontal=true 。重力属性用于线性布局。更多你为什么使用网格布局管理器?
更好的解决方案是以这种方式保留此代码,并在用于 RecyclerView 的行上将图像设置在行的中心:例如
行布局:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
对于布局管理器,如果您不使用这两列,请使用 LinearLayoutManager
推荐阅读
- php - FFmpeg - 不允许操作
- java - 使用 replaceAll() 修改现有元素时列表不更新
- xml - Powershell脚本将一个大文件拆分为多个文件,每个文件中有两对标签,文件名有命名约定
- apache-spark - 使用多列更新 Apache Spark / Databricks 中的表
- elasticsearch - ElasticSearch 批量插入导致 WriteStateException 和未分配的分片
- javascript - 如何将 GitHub 项目和时间线嵌入网站
- sql - 有没有办法在添加间隔的同时保留一个月的最后一天?
- angular-tree-component - 角树组件虚拟滚动不起作用
- mysql - 如何从 MySQL JSON 数组中选择行?
- python - 将排序表从熊猫数据框发送到前端?