viewtype
Up until now we’ve displayed same type of Views within a RecyclerView. In this tutorial, we’ll implement heterogeneous layouts inside a RecyclerView.
到目前为止,我们已经在RecyclerView中显示了相同类型的View。 在本教程中,我们将在RecyclerView中实现异构布局。
回收站视图 (RecyclerView)
RecyclerView with heterogeneous layouts is commonly used in to display section headers and details(Both require different layouts, hence different view type). Also, it’s used in a Newsfeed Application(like Facebook, Instagram) that display essentially different views for different types. Example: text, image, gif, video etc. Each of these requires a different layout type inside the RecyclerView.
具有不同布局的RecyclerView通常用于显示节标题和详细信息(两者都需要不同的布局,因此需要不同的视图类型)。 此外,它还用于Newsfeed应用程序(例如Facebook,Instagram)中,该应用程序针对不同类型显示本质上不同的视图。 例如:文本,图像,gif,视频等。每一个在RecyclerView内都需要不同的布局类型。
It’s also used in a NavigationDrawer to separate the Header from the rest of the section.
Without wasting any time, let’s implement it in our application.
它在NavigationDrawer中也用于将Header与本节的其余部分分开。
不浪费时间,让我们在应用程序中实现它。
Android RecyclerView多个ViewType项目结构 (Android RecyclerView Multiple ViewType Project Structure)
We’ll be implementing three view types (text, image, audio) that are inflated by three different layouts. Each has its own implementation specified in the adapter class.
我们将实现三种视图类型(文本,图像,音频),这些视图类型将通过三种不同的布局进行放大。 每个适配器都有在适配器类中指定的自己的实现。
码 (Code)
Our activity_main.xml contains the CoordinatorLayout as the root and the RecyclerView acts as it’s child view.
我们的activity_main.xml包含CoordinatorLayout作为根,而RecyclerView充当其子视图。
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.journaldev.recyclerviewmultipleviewtype.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimar