我在滚动视图中有列表视图,并计算孩子的高度基础。这是我使用的代码:
public static void SetListViewHeightBasedOnChildren (ListView listView)
{
IListAdapter listAdapter = listView.Adapter;
if (listAdapter == null) {
// pre-condition
return;
}
int totalHeight = listView.PaddingTop + listView.PaddingBottom;
for (int i = 0; i < listAdapter.Count; i++) {
View listItem = listAdapter.GetView (i, null, listView);
listItem.LayoutParameters = new Android.Views.ViewGroup.LayoutParams (
ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent);
listItem.Measure (0, 0);
totalHeight += listItem.MeasuredHeight;
}
ViewGroup.LayoutParams params_ = listView.LayoutParameters;
params_.Height = totalHeight + (listView.DividerHeight * listAdapter.Count) + 50;
listView.LayoutParameters = params_;
listView.RequestLayout ();
}
一般来说,它工作得很好,但在某些情况下(如果 listview 项目太大等)它修剪的最后一行。
.xml 中的层次结构
滚动视图->RelativeLayout->LinearLayout->ListView