After nested ScrollView in ListView, set the dividerHeight attribute and calculate the height. listviewdivider
When we need to nest ScrollView in the outer part of the listView, the two scroll effects will affect each other. To avoid this, we usually disable listView scrolling,
Calculate the total height of the ListView and display it completely.
To calculate the total height of a listView, you only need to customize a mylistView to inherit the listView and override the onMeasure (...) method.
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, expandSpec); }
However, when the dividerHeight attribute is set in listView, the preceding method becomes invalid because the preceding method does not add the interval dividerHeight between each Item.
What should we do? By searching on the internet, we find that other users share the information. We can first load the listView data, then calculate the height of each item through the for loop, and then add
Get the total height of the listView we want.
The Code is as follows:
Public static void setListViewHeightBasedOnChildren (ListView listView) {// obtain the Adapter ListAdapter listAdapter = ListView corresponding to the listView. getAdapter (); if (listAdapter = null) {// pre-condition return;} int totalHeight = 0; for (int I = 0, len = listAdapter. getCount (); I <len; I ++) {// listAdapter. getCount () returns the number of data items. View listItem = listAdapter. getView (I, null, listView); listItem. measure (0, 0); // calculate the width and height of the subitem View totalHeight + = listItem. getMeasuredHeight () + listView. getDividerHeight ()/2; // calculate the total height of all subitems + dividerheight} ViewGroup. layoutParams params = listView. getLayoutParams (); params. height = totalHeight + (listView. getDividerHeight () * (listAdapter. getCount ()-1); // listView. getDividerHeight () obtains the height occupied by separators between subitems. // params. the height finally shows the required height for the entire ListView. setLayoutParams (params );}
Note: 1. setListViewHeiBasedOnChildren (listView). Use
if (addressResult != null && addressResult.size() >= 0) { addressadapter = new AddressItemAdapter(getApplicationContext(), addressResult); addressadapter.addressListener(AddressActivity.this); addressListView.setAdapter(addressadapter); setListViewHeightBasedOnChildren(addressListView); }
2. the root directory of the ListView Item must be LinearLayout.
3. Remember addressadapter. notifyDataSetChanged (); call