ScrollView and ListView (correct calculation of listview height) problem solving _android

Source: Internet
Author: User

First, ListView cannot be used directly, to customize one, and then rewrite the Onmeasure () method:

Copy Code code as follows:

@Override
protected void onmeasure (int widthmeasurespec, int heightmeasurespec) {
int expandspec = Measurespec.makemeasurespec (Integer.max_value >> 2,
Measurespec.at_most);
Super.onmeasure (Widthmeasurespec, Expandspec);
}

Step Two: Write a method to calculate ListView per item:

Copy Code code as follows:

public void Setlistviewheightbasedonchildren (ListView ListView) {

Gets the listview corresponding adapter

ListAdapter listadapter = Listview.getadapter ();

if (ListAdapter = = null) {

Return

}

int totalheight = 0;

for (int i = 0; i < Listadapter.getcount (); i++) {//Listadapter.getcount () returns the number of data items

View ListItem = Listadapter.getview (i, NULL, ListView);

Listitem.measure (0, 0); Calculate the height of a child view

Totalheight + + listitem.getmeasuredheight (); Statistics The total height of all subkeys

}

Viewgroup.layoutparams params = Listview.getlayoutparams ();

Params.height = Totalheight
+ (Listview.getdividerheight () * (Listadapter.getcount ()-1));

Listview.getdividerheight () Gets the height of the delimiter between subkeys

Params.height finally get the entire ListView full display required height

Listview.setlayoutparams (params);

}

Step three: ListView after adding the adapter to set the height:

Copy Code code as follows:

Listview.setadapter (adapter);
New Listviewutil (). Setlistviewheightbasedonchildren (ListView);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.