Android开发之RecyclerView嵌套ListView自动计算高度的方法

老套路看图:下面是我在我爱我家在职时候做的一个小需求记录下

最外层是个RecylerView子布局里面的房屋描述信息是个listview根据后台返回字段动态显示的高度。

解决思路:可以计算每个listview的子布局的高度相加起来就是整个listview的告诉。

方法一:

自定义ListView:

package com.wiwj.itNew5iwork.view;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;

/**
 * @author lenovo
 * 2020年12月16日15:30:07
 * 自定义ListView实现高度自适应
 */
public class HeightListView extends ListView {
    public HeightListView(Context context) {
        super(context);
    }

    public HeightListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public HeightListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int heightSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, heightSpec);
    }
}

方法二:动态计算

 public void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

方法二的调用方法:

setListViewHeightBasedOnChildren(listview);

再次非常感谢如下博主:方法一博主方法二博主

猜你喜欢

转载自blog.csdn.net/xiayiye5/article/details/111280617