Explain in detail how Android enables GridView to scroll horizontally

Android provides us with a vertical scrolling control GridView, but if we want it to scroll horizontally, we need to implement it ourselves.

The test data sets used below are of type list < resolveinfo > and are used to store all apps in the phone

1、 Single line horizontal display

Realization idea

Concrete implementation

critical code

The dip2px method used here is to convert from DP unit to PX (pixel) according to the resolution of the mobile phone

In the layout file, wrap the GridView with horizontalscrollview

Through the above settings and the adapter, you can realize single line horizontal scrolling. The adapter can use the conventional implementation method, which is not posted here

2、 Multiline horizontal pagination display

Realization idea

Concrete implementation

When there is a large amount of data, paging is required, and the calculation method is different

Required pages = total quantity ÷ displayed quantity per page

For something that cannot be divided, you need to use the math. Ceil () function to round up

critical code

When the total quantity ÷ the quantity displayed on each page is exactly divided, a blank page will appear. At this time, the extra page needs to be removed

The adapter should control the displayed data at the initial stage of creation, because each GridView here has a separate adapter, so it is necessary to dynamically calculate the displayed data

Through the dynamic calculation of the data passed into the construction method, the position where the data starts to load and the position where the data ends to load can be obtained

Construction method of horizontalgvadapter:

If you need to add small round points, you can first use an empty LinearLayout as the container of small round points in the layout

Then use list < View > in the code to save the created dots

3、 Summary

The above is the way to realize the horizontal scrolling of GridView. In fact, we don't have to be so troublesome. Google provides us with the recyclerview control in the support-v7 package. To switch the horizontal and vertical scrolling, just let the layout manager use the setorientation method. It's very convenient. If the project allows, it is recommended to use recyclerview to realize such requirements.

I hope it will help you in your study, and I also 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
分享
二维码
< <上一篇
下一篇>>