我发现了一个非常简单的解决方案。只需获取listview的适配器并在显示所有项目时计算其大小。 优点是这个解决方案也适用于ScrollView。
例子:
public static void justifyListViewHeightBasedOnChildren (ListView listView) {
ListAdapter adapter = listView.getAdapter();
if (adapter == null) {
return;
}
ViewGroup vg = listView;
int totalHeight = 0;
for (int i = 0; i < adapter.getCount(); i++) {
View listItem = adapter.getView(i, null, vg);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams par = listView.getLayoutParams();
par.height = totalHeight + (listView.getDividerHeight() * (adapter.getCount() - 1));
listView.setLayoutParams(par);
listView.requestLayout();
}
调用此函数掠过你的ListView对象:
justifyListViewHeightBasedOnChildren(myListview);
上面显示的功能是一个后在modidication: Disable scrolling in listview
请注意,以在将适配器设置为列表视图后调用此函数。如果适配器中条目的大小已更改,则还需要调用此函数。
检查: http://stackoverflow.com/questions/4338185/how-to- get-a-non-scrollable-listview –
是的,但是如果我使用LinearLayout而不是ListView,我不会收到OnItemSelected事件,这会导致更多不必要的编码。 – razielsarafan
嗨检查链接,仔细阅读。在LinearLayout中使用listview。将ScrollContainer设置为false,并且可以将OnClickListener或OnTouchListener绑定到点击或触摸时将触发的视图 –