Android开发之RecyclerView详解(一)(依据官方文档)

关于RecyclerView

如果你需要实现一个可以滚动的列表视图,且列表元素数据量大,改变频繁,那么可以使用RecyclerView来描述你的页面
如:
在这里插入图片描述

这是官方的Demo:Android developer Demo大家可以参考一下
RecyclerView
的一个更高级和更灵活的版本。

在RecyclerView模型中,几个不同的组件一起工作来显示您的数据。用户界面的整体容器是一个RecyclerView对象,您可以将其添加到布局中。RecyclerView用您提供的布局管理器(LayoutManager)提供的视图填充自己。您可以使用的一个标准布局管理器(如LinearLayoutManager或GridLayoutManager),或者实现您自己的布局管理器。

The RecyclerView widget is a more advanced and flexibleversion of ListView.
In the RecyclerView model, severaldifferent components work together to display your data.
The overall container for your user interface is a RecyclerView object that you add to your layout. The RecyclerView fills itself with views provided by a
layout manager that you provide. You can use one of our standard layout managers (such as LinearLayoutManager or GridLayoutManager), or implement your own.

列表中的视图由ViewHolder对象表示。这些对象是通过继承 RecyclerView.ViewHolder定义的类的实例。每个ViewHolder负责显示带有视图的单个项。例如,如果列表显示音乐集合,每个ViewHolder可能代表一个专辑。RecyclerView只创建显示动态内容的屏幕部分所需的ViewHolder数量,外加一些额外的ViewHolder。当用户滚动列表时,RecyclerView获取屏幕外的视图,并将它们重新绑定到屏幕上滚动的数据。

The views in the list are represented by view holder objects. These objects are instances of a class you define by extending RecyclerView.ViewHolder. Each view holder is in charge of displaying a single item with a view. For example, if your list shows music collection, each view holder might represent a single album. The RecyclerView creates only as many view holders as are needed to display the on-screen portion of the dynamic content, plus a few extra. As the user scrolls through the list, the RecyclerView takes the off-screen views and rebinds them to the data which is scrolling onto the screen.

ViewHolder对象由适配器管理,您可以通过继承ReyclerView.ViewHolder创建该适配器。适配器根据需要创建ViewHolder。适配器还将ViewHolder绑定到他们的数据。它通过将ViewHolder分配到一个位置并调用适配器的onBindViewHolder()方法来实现这一点。该方法使用ViewHolder的位置,根据其列表位置确定内容应该是什么。

The view holder objects are managed by an adapter, which you create by extending RecyclerView.Adapter. The adapter creates view holders as needed. The adapter also binds the view holders to their data. It does this by assigning the view holder to a position, and calling the adapter’s onBindViewHolder() method. That method uses the view holder’s position to determine what the contents should be, based on its list position.

这个RecyclerView框架做了很多优化工作,所以你不必:
1.当列表第一次被填充时,它创建并绑定列表两边的一些ViewHolder。例如,如果视图正在显示列表位置0到9,那么RecyclerView将创建并绑定这些ViewHolder,还可能创建并绑定位置10的ViewHolder。这样,如果用户滚动列表,下一个元素就可以显示了。
2. 当用户滚动列表时,RecyclerView会根据需要创建新的ViewHolder。它还保存了已在屏幕外滚动的ViewHolder,因此可以重新用它们。如果用户切换滚动的方向,则可以将从屏幕上滚动下来的ViewHolder重新带回来。另一方面,如果用户继续在相同的方向滚动,离开屏幕时间最长的ViewHolder可以重新绑定到新数据。ViewHolder不需要创建或使其视图膨胀;相反,应用程序只是更新视图的内容,以匹配它绑定到的新项。
3. 当显示的项发生更改时,您可以通过调用适当的RecyclerView .adapter .notify…()方法通知适配器。然后适配器的内置代码仅重新绑定受影响的项。

This RecyclerView model does a lot of optimization work so you don’t have to:
When the list is first populated, it creates and binds some view holders on either side of the list. For example, if the view is displaying list positions 0 through 9, the RecyclerView creates and binds those view holders, and might also create and bind the view holder for position 10. That way, if the user scrolls the list, the next element is ready to display.
As the user scrolls the list, the RecyclerView creates new view holders as necessary. It also saves the view holders which have scrolled off-screen, so they can be reused. If the user switches the direction they were scrolling, the view holders which were scrolled off the screen can be brought right back. On the other hand, if the user keeps scrolling in the same direction, the view holders which have been off-screen the longest can be re-bound to new data. The view holder does not need to be created or have its view inflated; instead, the app just updates the view’s contents to match the new item it was bound to.
When the displayed items change, you can notify the adapter by calling an appropriate RecyclerView.Adapter.notify…() method. The adapter’s built-in code then rebinds just the affected items…

实现步骤

1.添加依赖库

To access the RecyclerView widget, you need to add the v7 Support Libraries to your project as follows:
Open the build.gradle file for your app module.
Add the support library to the dependencies section.

要使用RecyclerView,您需要将 v7 Support Libraries 添加到您的项目中,如下所示:
a. 打开build.gradle file(app module)
b. 将support library添加到dependencies部分

dependencies {
    implementation 'com.android.support:recyclerview-v7:28.0.0'
}

2.把RecyclerView加到你的布局里面

Now you can add the RecyclerView to your
layout file. For example, the following layout uses RecyclerView
as the only view for the whole layout:

现在,您可以将RecyclerView添加到布局文件中。例如,下面的布局使用RecyclerView作为整个布局的唯一视图:

<?xml version="1.0" encoding="utf-8"?>
<!-- A RecyclerView with some commonly used attributes -->
<android.support.v7.widget.RecyclerView
    android:id="@+id/my_recycler_view"
    android:scrollbars="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

Once you have added a RecyclerView widget to your layout,
obtain a handle to the object, connect it to a layout manager, and attach an adapter for the data
to be displayed:

一旦你在你的布局中添加RecyclerView,获得一个对象的句柄,将它连接到一个布局管理器,并为要显示的数据附加一个适配器:

public class MyActivity extends Activity {
    private RecyclerView recyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager layoutManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_activity);
        recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);

        // use this setting to improve performance if you know that changes
        // in content do not change the layout size of the RecyclerView
        recyclerView.setHasFixedSize(true);

        // use a linear layout manager
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        // specify an adapter (see also next example)
        mAdapter = new MyAdapter(myDataset);
        recyclerView.setAdapter(mAdapter);
    }
    // ...
}

3.添加一个List Adapter

To feed all your data to the list, you must extend the RecyclerView.Adapter class. This object creates views for items, and replaces the content of some of the views with new data items when the original item is no longer visible. The following code example shows a simple implementation for a data set that consists of an array of strings displayed using TextView widgets

要将所有数据提供给列表,您必须继承RecyclerView.Adapter 类。此对象为项创建视图,当原始项不再可见时,用新的数据项替换一些视图的内容。下面的代码示例显示了一个简单的数据集实现,该数据集由使用TextView显示的字符串数组组成

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
    private String[] mDataset;

    // Provide a reference to the views for each data item
    // Complex data items may need more than one view per item, and
    // you provide access to all the views for a data item in a view holder
    public static class MyViewHolder extends RecyclerView.ViewHolder {
        // each data item is just a string in this case
        public TextView textView;
        public MyViewHolder(TextView v) {
            super(v);
            textView = v;
        }
    }

    // Provide a suitable constructor (depends on the kind of dataset)
    public MyAdapter(String[] myDataset) {
        mDataset = myDataset;
    }

    // Create new views (invoked by the layout manager)
    @Override
    public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
                                                   int viewType) {
        // create a new view
        TextView v = (TextView) LayoutInflater.from(parent.getContext())
                .inflate(R.layout.my_text_view, parent, false);
        ...
        MyViewHolder vh = new MyViewHolder(v);
        return vh;
    }

    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        // - get element from your dataset at this position
        // - replace the contents of the view with that element
        holder.textView.setText(mDataset[position]);

    }

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return mDataset.length;
    }
}

The layout manager calls the adapter’s onCreateViewHolder() method. That method needs to construct a RecyclerView.ViewHolder and set the view it uses to display its contents. The type of the ViewHolder must match the type declared in the Adapter class signature. Typically, it would set the view by inflating an XML layout file. Because the view holder is not yet assigned to any particular data, the method does not actually set the view’s contents. The layout manager then binds the view holder to its data. It does this by calling the adapter’s onBindViewHolder() method, and passing the view holder’s position in the RecyclerView. The onBindViewHolder() method needs to fetch the appropriate data, and use it to fill in the view holder’s layout. For example, if the RecyclerView is displaying a list of names, the method might find the appropriate name in the list, and fill in the view holder’s TextView widget. If the list needs an update, call a notification method on the RecyclerView.Adapter object, such as notifyItemChanged(). The layout manager then rebinds any affected view holders, allowing their data to be updated.

布局管理器调用适配器的onCreateViewHolder()方法。该方法需要构造一个RecyclerView.ViewHolder。设置它用来显示内容的视图。ViewHolder的类型必须与适配器类签名中声明的类型匹配。通常,它会通过转换XML布局文件来设置视图。因为ViewHolder还没有分配给任何特定的数据,所以该方法实际上并不设置视图的内容。然后布局管理器将ViewHolder绑定到它的数据。它通过调用适配器的onBindViewHolder()方法来实现这一点,并传递ViewHolder在RecyclerView中的位置。onBindViewHolder()方法需要获取适当的数据,并用它填充ViewHolder的布局。
例如,如果RecyclerView显示一个名称列表,该方法可能会在列表中找到合适的名称,并填充视图持有者的TextView。如果列表需要更新,请调用RecyclerView上的通知方法。适配器对象,例如notifyItemChanged()。然后布局管理器重新绑定任何受影响的ViewHolder,允许更新他们的数据。
4.定做你的RecyclerView

You can customize the RecyclerView objects to meet your specific needs. The standard classes provide all the functionality that most developers will need; in many cases, the only customization you need to do is design the view for each view holder and write the code to update those views with the appropriate data. However, if your app has specific requirements, you can modify the standard behavior in a number of ways. The following sections describe some of the other common customizations.

您可以定制RecyclerView对象来满足您的特定需求。标准类提供了大多数开发人员需要的所有功能;在许多情况下,您需要做的惟一定制就是为每个ViewHoler设计视图,并编写代码用适当的数据更新这些视图。但是,如果您的应用程序有特定的需求,您可以通过多种方式修改标准行为。下面几节描述其他一些常见的定制。

Modifying the layout
The RecyclerView uses a layout manager to position the individual items on the screen and determine when to reuse item views that are no longer visible to the user. To reuse (or recycle) a view, a layout manager may ask the adapter to replace the contents of the view with a different element from the dataset. Recycling views in this manner improves performance by avoiding the creation of unnecessary views or performing expensive findViewById() lookups. The Android Support Library includes three standard layout managers, each of which offers many customization options:
LinearLayoutManager arranges the items in a one-dimensional list. Using a RecyclerView with LinearLayoutManager provides functionality like the older ListView layout.
GridLayoutManager arranges the items in a two-dimensional grid, like the squares on a checkerboard. Using a RecyclerView with GridLayoutManager provides functionality like the older GridView layout.
StaggeredGridLayoutManager arranges the items in a two-dimensional grid, with each column slightly offset from the one before, like the stars in an American flag.
If none of these layout managers suits your needs, you can create your own by extending the RecyclerView.LayoutManager abstract class.

使用布局管理器在屏幕上定位各个项目,并决定何时重用用户不再可见的项目视图。为了重用(或回收)视图,布局管理器可能会要求适配器用数据集中不同的元素替换视图的内容。以这种方式回收视图可以避免创建不必要的视图或执行大量的findViewById()查找,从而提高性能。Android支持库包括三个标准布局管理器,每个标准布局管理器都提供了许多定制选项:
a.LinearLayoutManager将项目排列在一维列表中。使用带有LinearLayoutManager的RecyclerView提供了与旧的ListView布局类似的功能。
b.GridLayoutManager在二维网格中排列项目,就像棋盘上的正方形一样。使用带有GridLayoutManager的可回收视图提供了与旧的GridView布局类似的功能。
c.StaggeredGridLayoutManager将项目排列在一个二维网格中,每一列与前一列稍微偏移,就像美国国旗中的星星一样。如果这些布局管理器都不适合您的需求,您可以通过扩展clerview来创建自己的布局管理器。LayoutManager抽象类。

5.添加item动画

Whenever an item changes, the RecyclerView uses an animator to change its appearance. This animator is an object that extends the abstract RecyclerView.ItemAnimator class. By default, the RecyclerView uses DefaultItemAnimator to provide the animation. If you want to provide custom animations, you can define your own animator object by extending RecyclerView.ItemAnimator.

每当一个项目发生变化时,RecyclerView就会使用一个animator来改变它的外观。这个animator是一个对象,它继承了抽象的RecyclerView.ItemAnimator类。默认情况下,RecyclerView使用DefaultItemAnimator来提供动画。如果希望提供自定义动画,可以通过扩展clerview . itemanimator来定义自己的animator对象。

6.使用list-item selection

recyclerview-selection库允许用户使用触摸或鼠标输入来选择可回收视图列表中的项目。您保留对所选项的可视表示形式的控制。您还可以保留对控制选择行为的策略的控制,例如可以进行选择的项,以及可以选择多少项。
如果要实现选择:
a.确定要使用哪种选择键类型,然后构建ItemKeyProvider。
您可以使用三种关键类型来标识选定的项:Parcelable(以及所有的子类,如 Uri)、String和Long。有关选择键类型的详细信息,请参见SelectionTracker.Builder。
b.实现ItemDetailsLookup
ItemDetailsLookup使选择库能够访问给定MotionEvent的RecycleView项的信息。它实际上是一个ItemDetails实例的工厂,这些实例由(或从)RecyclerView视图中提取ViewHolder实例。
c.在RecyclerView中更新项目视图,以反映用户已经选择或取消选择了它。
选择库不为所选项提供默认的视觉装饰。在实现onBindViewHolder()时,必须提供这一点。建议的方法如下:
在onBindViewHolder()中,对视图对象调用setactivate()(而不是setSelected()),使用true或false(取决于是否选择了该项)。
更新视图的样式以表示激活状态。我们建议您使用颜色状态列表资源来配置样式.
d. 使用ActionMode为用户提供对选择执行操作的工具
注册一个SelectionTracker。选择更改时通知SelectionObserver。当第一次创建一个选择时,启动ActionMode将其表示给用户,并提供特定于选择的操作。例如,您可以向ActionMode栏添加一个delete按钮,并连接栏上的back箭头以清除选择。当选择变为空时(如果用户上次清除了选择),不要忘记终止操作模式。
e.执行任何解释的辅助操作
在事件处理管道的末尾,库可能会确定用户正试图通过单击某个项来激活该项,或者正试图拖放某个项或一组选定的项。通过注册合适的listener来回应这些解释。有关更多信息,请参见SelectionTracker.Builder。
f.用SelectionTracker.Builder组装所有东西
下面的例子展示了如何使用长选择键将这些片段组合在一起:

SelectionTracker tracker = new SelectionTracker.Builder<>(
        "my-selection-id",
        recyclerView,
        new StableIdKeyProvider(recyclerView),
        new MyDetailsLookup(recyclerView),
        StorageStrategy.createLongStorage())
        .withOnItemActivatedListener(myItemActivatedListener)
        .build();

为了构建一个SelectionTracker实例,您的应用程序必须提供相同的RecyclerView适配器,您使用该适配器将RecyclerView初始化为SelectionTracker.Builder。出于这个原因,一旦创建了SelectionTracker实例,您很可能需要将它注入到RecyclerView中。适配器后的回收。创建适配器。否则,您将无法从onBindViewHolder()方法中检查项目的选定状态。
g.在活动生命周期事件中包含选择。
为了在活动生命周期事件中保持选择状态,应用程序必须分别从活动的onSaveInstanceState()和onRestoreInstanceState()方法中调用选择跟踪器的onSaveInstanceState()和onRestoreInstanceState()方法。您的应用程序还必须为SelectionTracker提供唯一的选择ID。构建器的构造函数。这个ID是必需的,因为一个活动或一个片段可能有多个不同的、可选择的列表,所有这些列表都需要以保存的状态持久化。

官方的的Demo:Demo官方

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值