Encapsulation and resolution of recyclerview adapter in Android

preface

As for the encapsulation of adapter, there are many open source libraries on the Internet, which can be used directly during development, saving a lot of things.

I have nothing to do recently. I want to package an adapter myself.

problem

1. Generally, when we package, we can simplify to this step:

2. From the above code, we can see that when dealing with multiple layout types, we need to solve the following problems:

3. When we update iteratively, we can only modify the adapter, so the coupling is a little strong.

However, when simplified to this step, it can actually be used in the project

solve

1. For the above problem, we know that if iterative update is required, we can only modify the viewtype, layout, onbind and other specific data. In this case, we can extract and encapsulate these specific data. Instead of directly processing the data, the adapter is handed over to the encapsulation class, and the logic is handed over to the encapsulation class for processing. In this way, the adapter only needs to maintain the encapsulation class.

2. This encapsulated class is temporarily called item

In adpatter, what needs to be dynamically adjusted is

Therefore, these methods are extracted and encapsulated, and then the adapter maintains the item list

3. The above interface item

First, if there is no data, we need to provide data setting and obtaining methods in the implementation class;

Second: we need to implement four methods at the same time

In this case, we can simplify the operation through a base class baseitem

4. In the item interface, there is only oncreateviewholder() method, which does not need to be implemented every time. Because it is fixed, baseitem can be written as follows:

5. Now, we only need to implement three methods. Let's look at getitemviewtype again. This returns the current layout type and int type. It is unique and cannot be repeated. Layout in Android maintains a unique ID of int type. Can we use this ID as viewtype? In this way, the implementation class can be further simplified. Now we only need to implement two methods.

6. Next, we will construct an adapter so that it no longer maintains specific data, but a baseitem list

epilogue

The above briefly introduces the packaging idea. As for the head layout, foot layout, empty layout, load more layout, etc., they are actually a viewtype layout in the adapter. The specific implementation code is GitHub: baseadapter

The following figure shows the data structure in an adapter:

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>