【发布时间】:2015-03-27 12:10:17
【问题描述】:
我在 ScrollView 中使用 ListView 并获取 ListView 总高度以使 Scrollview 高度等于 ListView 完整高度。我正在使用以下代码获取 ListView 总高度:
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null)
return;
int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.UNSPECIFIED);
int totalHeight = 0;
View view = null;
for (int i = 0; i < listAdapter.getCount(); i++) {
view = listAdapter.getView(i, view, listView);
if (i == 0)
view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth, LayoutParams.WRAP_CONTENT));
view.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
totalHeight += view.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
listView.requestLayout();
}
但问题是我有可变高度的 ListView 项目,当 ListView 项目中的一个 TextView 获得 3-4 行的内容时,ListView 项目的高度变大,而以上方法无法提供该项目的确切高度。因此,无法滚动到 ListView 的末尾。
所以请告诉我如何使用可变大小的项目获取 ListView 的正确高度。
【问题讨论】:
-
为什么在滚动视图中使用列表视图?
-
@jvrodrigues 我有一些理由使用它,如果您知道我的问题的解决方案,请帮助我。谢谢
-
看到这个问题我在我的一个项目中使用了它。 stackoverflow.com/questions/18813296/…
-
@Shabbir Dhangot - 非常感谢,这解决了我的问题。你得到了我的实际问题。如果可以,请将其作为答案,以便我将其标记为正确。
标签: android listview android-listview