[英]How to center a RecyclerView horizontal?
只是試圖將我的 RecyclerView 水平居中,但像 Gravity:"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 。 Gravity 屬性用於線性布局。 更多你為什么使用網格布局管理器?
更好的解決方案是保持此代碼並在用於 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.