One click return to the top example of linearlayoutmanager in Android

Previously, when learning recyclerview, we established a view list that can slide. However, when the sliding distance is too long, we need to manually return to the top, so we added a one click return to the top button.

design sketch

To achieve this effect, two points need to be achieved:

1. Control the sliding distance of lanyoutmanager, and set hidden or displayed according to the sliding state (distance).

2. Set the click event of top, and click to return to the top.

Unfortunately, layoutmanager only provides us with the method to obtain the height of the first visible item. What we need here is the total sliding distance from the beginning to the present, so we have to write it ourselves. There are many methods on the Internet. It's better to try it.

It is suggested that if you are not familiar with recyclerview, you can try some of its methods to obtain height, such as getchildat(), getheight(). For index, you can use findfirstvisibleitemposition(); At first, I naively thought that the official would provide a method, but I didn't go into the method source code. If you have a better method, please leave a message.

After obtaining the height

We need to get the height and set the effect

DIY can be a variety of effects, common effects, such as Alipay began to slide, title will gradually change, and finally slowly hide into other functions. All implemented in this method

If we only need to do the effect of returning to the top, we can directly set the distance here. This distance is the total sliding distance. When the sliding distance exceeds 400, the setting button is visible and hidden when it is less than 400.

Of course, this is only the simplest style. If it is more complex, it can be as follows:

Change the effect while sliding, or set a gradient effect

Wait, what kind of effect do you want? Just set it here.

Then we just need to add an effect to the sliding event.

Finally, don't forget to set the listening event of the return button

Only one line of code scrolltoposition (0); Each click to return to the initial position can complete the operation of one key return to the top.

Attach XML:

Source download: Android collection demo_ jb51.rar

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