[英]How to set the dynamic height to list view
大家好,我需要幫助將動態高度設置為列表視圖。
在我的任務中,滾動視圖內有一個listView,因此我需要將動態高度設置為列表視圖,以使任務在滾動視圖中完全可行。
我在下面的代碼中使用了如何在andrtoid中動態更改ListView的高度 。 這段代碼運行良好,但是此代碼存在問題,它使列表視圖的高度增加了。
假設如果列表視圖中只有3個項目 ,那么它使listview的高度等於6個項目 。
我想知道如何解決它。
這是我的代碼。
public class Utility {
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
// pre-condition
return;
}
int totalHeight = 0;
int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.AT_MOST);
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
listView.requestLayout();
}
}
我在listview活動中使用它,例如:
SimpleAdapter simpleadapter = new SimpleAdapter(getApplicationContext(), alist, R.layout.fragmentsrow, getItems, setItems);
ListViewWelcomePage.setAdapter(simpleadapter);
Utility.setListViewHeightBasedOnChildren(ListViewWelcomePage);
您可以使用ExpandableHeightListView代替普通的ListView。 請參閱此github庫https://github.com/PaoloRotolo/ExpandableHeightListView
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.