recyclerview 实现中间的item 居中
时间: 2024-02-06 09:10:08 浏览: 45
要让 RecyclerView 中间的 item 居中,可以使用 `SnapHelper` 和 `LinearLayoutManager`。
1. 在 Activity 或 Fragment 中,找到 RecyclerView 并设置 LayoutManager:
```java
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(layoutManager);
```
2. 创建一个 `SnapHelper` 对象,并将其附加到 RecyclerView 上:
```java
SnapHelper snapHelper = new LinearSnapHelper();
snapHelper.attachToRecyclerView(recyclerView);
```
3. 在 RecyclerView 的 Adapter 中,为每个 item 添加 `android:layout_gravity="center_horizontal"` 属性,使其水平居中。例如:
```xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 1"
android:layout_gravity="center_horizontal"/>
```
现在当用户滚动 RecyclerView 时,最接近中心的 item 将自动对齐到中心位置。