Created
May 3, 2016 11:20
-
-
Save shau-lok/6dd5e5bbaf689b7d7f83f070a1463efd to your computer and use it in GitHub Desktop.
ListView 设置高度根据item高度
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Sets ListView height dynamically based on the height of the items. | |
* | |
* @param listView to be resized | |
* @return true if the listView is successfully resized, false otherwise | |
*/ | |
public static boolean setListViewHeightBasedOnItems(ListView listView) { | |
ListAdapter listAdapter = listView.getAdapter(); | |
if (listAdapter != null) { | |
int numberOfItems = listAdapter.getCount(); | |
// Get total height of all items. | |
int totalItemsHeight = 0; | |
for (int itemPos = 0; itemPos < numberOfItems, itemPos++) { | |
View item = listAdapter.getView(itemPos, null, listView); | |
item.measure(0, 0); | |
totalItemsHeight += item.getMeasuredHeight(); | |
} | |
// Get total height of all item dividers. | |
int totalDividersHeight = listView.getDividerHeight() * | |
(numberOfItems - 1); | |
// Set list height. | |
ViewGroup.LayoutParams params = listView.getLayoutParams(); | |
params.height = totalItemsHeight + totalDividersHeight; | |
listView.setLayoutParams(params); | |
listView.requestLayout(); | |
return true; | |
} else { | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment