[英]ANDROID: Multiple Card Views inside recycler view
我認為實現附加圖像中描述的目標的正確方法是使用GridLayoutManager
而不是使用RecyclerView.LayoutManager
或LinearLayoutManager
。
我們在RecyclerView
上附加的LayoutManager
決定了列數。 有3個子類。
LinearLayoutManager
GridLayoutmanger
StaggeredGridLayoutmanger
在初始化RecyclerView.LayoutManager
活動中,進行更改
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManger(this);
至
GridLayoutManager mLayoutManager = new GridLayoutManger(this, 2);
2是網格的跨度計數。 每個項目都將放置在一個范圍內,因此您的回收站視圖中將有2列。
試試這個
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="300dp"
android:orientation="vertical">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/a"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Huming Bird"/>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="wrap_content">
<ImageView
android:layout_width="match_parent"
android:layout_height="300dp"
android:src="@drawable/b"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Huming Bird"/>
</android.support.v7.widget.CardView>
</LinearLayout>
</LinearLayout>
你的xml可以這樣做:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<android.support.v7.widget.CardView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content">
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content">
</android.support.v7.widget.CardView>
</LinearLayout>
要根據所需的列數動態設置,可以根據列數設置布局管理器。 這非常靈活。 具有相應布局的相同/相似代碼可以在平板電腦或手機上運行。
// Set the adapter
if (view instanceof RecyclerView) {
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
....
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.