RecyclerView的使用之多种Item加载布局

2019-12-10 18:49:12王旭
本文给大家介石介绍下如何利用RecyclerView实现多Item布局的加载,多Item布局的加载的意思就是在开发过程中List的每一项可能根据需求的不同会加载不同的Layout  

本文给大家介石介绍下如何利用RecyclerView实现多Item布局的加载,多Item布局的加载的意思就是在开发过程中List的每一项可能根据需求的不同会加载不同的Layout。

下面给大家展示下演示效果图:

 RecyclerView,加载布局

* 图片资源版权归属于Facebook dribbble

RecyclerView实现加载不同的Layout的核心就是在Adapter的onCreateViewHolder里面去根据需求而加载不同的布局。

具体的实现步骤:(以Android Studio作为开发工具)

1:Gradle配置 build.gradle

这里cardview也是一种新的布局容器,上一篇有介绍。

compile 'com.android.support:recyclerview-v7:23.1.1'
compile 'com.android.support:cardview-v7:23.1.1'

2:建立列表的布局 activity_recyclerview.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://www.easck.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
xmlns:android="http://www.easck.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/rv_list"
/>
</LinearLayout>

由于需要多种item Layout的加载,我们需要建立2个item布局

3:建立列表Item项的布局(1) item1.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:card_view="http://www.easck.com/apk/res-auto"
xmlns:android="http://www.easck.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:id="@+id/cv_item"
android:foreground="?android:attr/selectableItemBackground"
card_view:cardCornerRadius="4dp"
card_view:cardBackgroundColor="#ffffff"
card_view:cardElevation="4dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<ImageView
android:id="@+id/iv_item1_pic"
android:layout_width="match_parent"
android:layout_height="120dp"
android:layout_weight="1"
android:background="@mipmap/lighthouse"
/>
<TextView
android:id="@+id/tv_item1_text"
android:padding="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</android.support.v7.widget.CardView>