首页 > 解决方案 > Android 设置 ListView 高度依赖于项目高度

问题描述

我有一个 ListView 与高度总是不同的项目。但我不想计算 ListView 的总高度,因为 ListView 高度应该取决于项目。

我在 ListView 中添加了这个:

@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    ListAdapter listAdapter = getAdapter();
    if (listAdapter == null) {
        return;
    }
    int totalHeight = 0;
    for (int i = 0; i < listAdapter.getCount(); i++) {
        View listItem = listAdapter.getView(i, null, JOListView.this);
        totalHeight += listItem.getMeasuredHeight();
    }
    ViewGroup.LayoutParams params = getLayoutParams();
    if (withTollerance) {
        params.height = Math.round(totalHeight * 1.05f);
    } else {
        params.height = totalHeight;
    }
    setLayoutParams(params);
    requestLayout();
}

它没有给我真正的高度。有谁知道如何获得每件物品的正确高度?

标签: androidlistviewandroid-listview

解决方案


推荐阅读