Solution to sliding conflict of Scrollview nested listview

Scrollview and listview must be familiar to everyone, but there will be trouble when they are nested. For example, if we want to add other layouts or controls under the listview, and then want them to slide as a whole, the most common idea is to wrap them with a Scrollview. The idea seems beautiful, but the reality is a little cruel. We can write a small example to experience it.

First, create an activity and place a listview on its layout file:

Then use the for loop to generate some data in the code, and use the arrayadapter to adapt the data. Allow me to steal some slack here. The item layout of listview directly uses r.layout.simple provided by Android_ list_ item_ 1. Instead of customizing yourself.

Make sure your current activity is start activity, and then run the app. You can see the following effects:

OK, it seems that there is no problem, but what if we need to add some controls at the head or bottom of the listview so that they can slide as a whole? We can try this first:

Add several controls at the head and bottom of the listview, then wrap all the controls in a linear layout, change the layout of the outermost layer to Scrollview, and run again. The trouble arises:

God! Our listview has only a small line left! Try sliding and find that there is no problem with sliding, that is, only one line can be displayed. What should we do?

Don't worry, there is a simple way to bring the dead back to life. We can customize a listview:

In this ListView, we rewrite the onMeasure method, then redefine the heightMeasureSpec parameter, which takes 1/4 of the maximum value (general practice), takes the maximum value of the measurement mode, and then calls the parent class's construction method to retransmit the heightMeasureSpec parameter. These steps are to ensure that there is no problem with the height of the listview. After completion, we use the custom listview in the layout file:

After running, the problem was found and solved! Listview can be displayed completely, and it can also slide to the layout of the head and top.

In fact, if you want to display ListView's head or bottom layout or control, you don't have to use ScrollView. We can also use the head and bottom as a whole layout, that is, head layout or foot layout, and then call ListView's addHeaderView method or addFooterView method to add it to the head or bottom of ListView.

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