A simple method of adding split lines to recyclerview based on Android

1. Foreword

When I first started learning recyclerview, I learned it from a video. At that time, I imported a Java class from the outside to add a split line, and then used the functions inside to create the split line, so I have always done this. It was not until a few days ago that we accidentally found that a divideritemdecoration class was provided in the original V7 package. Using it, we can easily implement the dividing line of recyclerview! What are you waiting for? Use it quickly.

2. Create a simple recyclerview

First of all, of course, there should be a recyclerview. I won't repeat it here. Just create some data. Direct code:

Code of recyclerviewadapter:

After running, it is as follows:

Obviously, there is no dividing line at this time.

3. Add default split line

Now let's add a split line. First, let's try the simplest one, that is, the split line comes with Android. Just add one line of code.

The additemdecoration method requires an object of divideritemdecoration. When creating its object, we need to pass in the context and the direction of the dividing line. Run again and you can see that the split line appears:

4. Custom split line

Sometimes the default light gray division line can not meet our requirements. At this time, we need to "write" a division line ourselves. How should we write it? Open divideritemdecoration to see its source code. There is a function:

We just need to call this method and pass in a drawable function object. You can now write a split line style using shape:

What I got here is a coquettish gradient dividing line. Then the code for adding the split line is changed as follows:

After running, you can see a colorful dividing line:

In this way, the scope of use is much wider. For example, if a certain interval is required between items, we can add a transparent dividing line.

5. Summary

The code for adding a split line is very simple. You can do this when you need to add a simple split line in the future. However, it should be noted that this is only applicable to recyclerview of linear layout, and grid layout and staggeredgridlayout are not applicable.

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
分享
二维码
< <上一篇
下一篇>>