listview自适应高度

时间:2022-10-01 19:33:56

首先自定义一个listview

public class MlistView extends ListView {

public MlistView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}

public MlistView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}

public MlistView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// TODO Auto-generated constructor stub
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
int hms = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, hms);
}

}

在计算每一个item的高设置list

import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;

/*获取并设置listeview高度
* */
public class SetmListeViewHeight {

public void setHegiht(ListView listView){
/*获取adapter*/
ListAdapter listAdapter = listView.getAdapter();
if(listAdapter == null){
return;
}
int totalHeight = 0;
/* listAdapter.getCount()返回数据项的数目*/
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0); // 计算子项View 的宽高
totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
}

/*
* listView.getDividerHeight()获取子项间分隔符占用的高度
* params.height最后得到整个ListView完整显示需要的高度
* */
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}

}

使用:

lv.setAdapter(mAdapter);
svh.setHegiht(lv);