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官方

发布了5 篇原创文章 · 获赞 4 · 访问量 514
展开阅读全文

Recyclerview嵌套recyclerview的深坑,我坐在Recyclerview这个坑里很久了,仰望天空希望能把我拉上去。

10-07

Recyclerview嵌套recyclerview的深坑,对于一个新手来说怎么也上不去,特来邀请键盘中的高手高高手,拉拉我; ## 第一个Recyclerview布局: ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/area_LinearLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:focusable="true" android:focusableInTouchMode="true" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="40dp" android:background="@drawable/drawable_black_one" android:orientation="horizontal" android:layout_margin="3dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="5dp" android:layout_gravity="center" android:text="" android:textColor="@drawable/drawable_white_pure" android:lines="1" android:layout_weight="1"/> <TextView android:layout_width="1dp" android:layout_height="30dp" android:layout_gravity="center" android:layout_margin="5dp" android:background="@color/whiteness" /> <TextView android:id="@+id/peers_location_TextView" android:layout_width="70dp" android:layout_height="40dp" android:layout_marginLeft="5sp" android:layout_marginRight="10dp" android:ellipsize="end" android:gravity="center" android:text="" android:textColor="@color/whiteness" android:textSize="14sp" android:lines="1" android:textStyle="bold" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="3dp" > <RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content" > <ImageView android:layout_width="20dp" android:layout_height="20dp" android:layout_alignParentTop="true" android:layout_alignParentEnd="true" android:layout_marginTop="0dp" android:layout_marginEnd="10dp" android:scaleType="fitStart" android:src="@drawable/location" /> </RelativeLayout> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="40dp" android:background="@drawable/drawable_black_one" android:layout_gravity="center" android:focusable="true" android:focusableInTouchMode="true" android:layout_margin="3dp"> <EditText android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_margin="1dp" android:background="@color/text_white" android:hint="行业人员" android:textSize="13dp" android:gravity="center" android:lines="1" android:layout_weight="1"/> <TextView android:layout_width="50dp" android:layout_height="wrap_content" android:text="搜索" android:textSize="14dp" android:layout_marginLeft="14dp" android:layout_gravity="center" android:textColor="@color/whiteness" android:layout_margin="5dp" android:gravity="center"/> </LinearLayout> <android.support.v7.widget.RecyclerView android:id="@+id/user_info_layout" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> ``` ## 在第一个Recycleview的item里面嵌套了第二个Recyclerview不知道这样对不对? ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <LinearLayout android:id="@+id/portrait" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> <ImageView android:id="@+id/user_portrait" android:layout_width="50dp" android:layout_height="50dp" android:layout_margin="5dp" android:src="@drawable/em_default_avatar" /> <LinearLayout android:layout_width="fill_parent" android:layout_height="match_parent" android:layout_weight="1" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="20dp" android:layout_marginTop="5dp" android:gravity="clip_horizontal"> <TextView android:id="@+id/user_industry" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:background="@drawable/dialog_circular_whiteness" android:ellipsize="end" android:gravity="center" android:text="建筑" android:textColor="@color/colorPrimary" android:textSize="14sp" android:textStyle="bold" /> <TextView android:id="@+id/user_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom" android:layout_marginLeft="5dp" android:background="@drawable/dialog_circular_whiteness" android:ellipsize="end" android:gravity="center" android:text="努力改变自己" android:textColor="#323232" android:textSize="10sp" android:textStyle="bold" /> <TextView android:id="@+id/name_voip" android:layout_width="20dp" android:layout_height="wrap_content" android:layout_gravity="center" android:ellipsize="end" android:gravity="center" android:text="voip" android:textColor="@color/text_pink" android:textSize="7sp" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="35dp"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="努力改变自己" android:textSize="12dp" /> </LinearLayout> </LinearLayout> <RelativeLayout android:layout_width="60dp" android:layout_height="match_parent" android:gravity="center"> <TextView android:id="@+id/user_location" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:background="@drawable/dialog_circular_whiteness" android:text="" android:textSize="12dp" android:textStyle="bold" /> </RelativeLayout> </LinearLayout> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <LinearLayout android:layout_width="fill_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1"> **<!-- 导入RecyclerView-->** <android.support.v7.widget.RecyclerView android:id="@+id/user_peesr_info" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> <LinearLayout android:layout_width="fill_parent" android:layout_height="10dp"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="right" android:text="访问:10000人" android:textSize="8dp" /> </LinearLayout> </LinearLayout> </LinearLayout> ``` ## 第一个Recyclerview的适配器: ``` public class Home_RecyclerView_Adapter extends RecyclerView.Adapter<Home_RecyclerView_Adapter.myViewHodler> { private Context context; private LinkedList<Home_list_get_set> LinkedList; public LinkedList<User_Recruitment_get_set> mLinkedList; public Home_list_get_set mHome_list_get_set; //创建构造函数 public Home_RecyclerView_Adapter(Context context, LinkedList<Home_list_get_set> industrytitlegetsetList) { //将传递过来的数据,赋值给本地变量 this.context = context;//上下文 this.LinkedList = industrytitlegetsetList;//实体类数据ArrayList } /** * 创建viewhodler,相当于listview中getview中的创建view和viewhodler * * @param parent * @param viewType * @return */ @Override public myViewHodler onCreateViewHolder(ViewGroup parent, int viewType) { RecyclerView user_peesr_info;//自定义recyclerveiw的适配器 //创建自定义布局 // View itemView = View.inflate(context, R.layout.peers_list_item, null);//用这个布局item宽高无效 // myViewHodler itemView = new myViewHodler(LayoutInflater.from(context).inflate(R.layout.peers_list_item, parent, false)); View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.peers_list_item, parent, false); user_peesr_info = view.findViewById (R.id.user_peesr_info); //给嵌套的RecyclerView设置适配器 User_Recruitment_Adapter user_recruitment_adapter = new User_Recruitment_Adapter (context,mLinkedList); user_peesr_info.setAdapter (user_recruitment_adapter); user_peesr_info.setLayoutManager (new LinearLayoutManager (context, LinearLayoutManager.HORIZONTAL, false)); //给嵌套的RecyclerView设置item的分割线 user_peesr_info.addItemDecoration (new DividerItemDecoration (context, DividerItemDecoration.HORIZONTAL)); return new myViewHodler(view); // return itemView; } /** * 绑定数据,数据与view绑定 * * @param holder * @param position */ @SuppressLint("ClickableViewAccessibility") @Override public void onBindViewHolder(myViewHodler holder, int position) { //根据点击位置绑定数据 mHome_list_get_set = LinkedList.get(position); // holder.mItemGoodsImg; holder.user_name.setText(mHome_list_get_set.getUser_name()); holder.user_industry.setText(mHome_list_get_set.getUser_work()); // holder.user_portrait.setImageDrawable (data.getHead_portait ());//改为下面Glide获取图上 Glide.with(context) .load(mHome_list_get_set.getHead_portait ())//图片信息 .apply(RequestOptions.bitmapTransform(new CircleCrop ()))//设置圆形 .into(holder.user_portrait);//设置到那个部位 holder.name_voip.setText(mHome_list_get_set.getUser_Vip()); holder.user_location.setText(mHome_list_get_set.getUser_location()); } /** * 得到总条数 * * @return */ @Override public int getItemCount() { // return LinkedList.size(); return LinkedList == null ? 0 : LinkedList.size(); } //自定义viewhodler class myViewHodler extends RecyclerView.ViewHolder { private ImageView user_portrait; private TextView user_name; private TextView user_industry; private TextView name_voip; private TextView user_location; public RecyclerView user_peesr_info;//自定义recyclerveiw的适配器 public myViewHodler(View itemView) { super(itemView); user_peesr_info = itemView.findViewById (R.id.user_peesr_info); user_portrait = itemView.findViewById(R.id.user_portrait); user_name = itemView.findViewById(R.id.user_name); user_industry = itemView.findViewById(R.id.user_industry); name_voip = itemView.findViewById(R.id.name_voip); user_location = itemView.findViewById(R.id.user_location); user_portrait.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //可以选择直接在本位置直接写业务处理 //Toast.makeText(context,"点击了xxx",Toast.LENGTH_SHORT).show(); //此处回传点击监听事件 if (onItemClickListener != null) { onItemClickListener.OnItemClick(v, LinkedList.get(getLayoutPosition())); } } }); } public View getItemView() { return itemView; } } /** * 设置item的监听事件的接口 */ public interface OnItemClickListener { /** * 接口中的点击每一项的实现方法 * * @param view 点击的item的视图 * @param data 点击的item的数据 */ public void OnItemClick(View view, Home_list_get_set data); } //需要外部访问,所以需要设置set方法,方便调用 private OnItemClickListener onItemClickListener; public void setOnItemClickListener(OnItemClickListener onItemClickListener) { this.onItemClickListener = onItemClickListener; } ``` ## 第二个Recyclerview的适配器: ``` public class User_Recruitment_Adapter extends RecyclerView.Adapter<User_Recruitment_Adapter.myViewHodler> { public LinkedList<User_Recruitment_get_set> m_LinkedList; private Context context; public User_Recruitment_get_set mUser_Recruitment_get_set; //创建构造函数 public User_Recruitment_Adapter(Context context, LinkedList<User_Recruitment_get_set> mLinkedList) { //将传递过来的数据,赋值给本地变量 this.context = context;//上下文 this.m_LinkedList = mLinkedList; } @NonNull @Override public myViewHodler onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.user_peers_recruitment_item, viewGroup, false); return new myViewHodler(view); } @Override public void onBindViewHolder(@NonNull myViewHodler myViewHodler, int i) { mUser_Recruitment_get_set = m_LinkedList.get(i); myViewHodler.recruitment.setText (mUser_Recruitment_get_set.getRecruitment ()); } @Override public int getItemCount() { return m_LinkedList == null ? 0 : m_LinkedList.size(); } public class myViewHodler extends RecyclerView.ViewHolder { private TextView recruitment; public myViewHodler(@NonNull View itemView) { super (itemView); recruitment = itemView.findViewById(R.id.recruitment); } } } ``` ## 现问题是嵌套里面的Recyclerview无显示内容?我该如何写? 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览