android:解决安卓ListView只显示一行的问题 - 简书 (jianshu.com)
这里是对 上面连接的一个补充说明,也可以说是我的使用说明,我用的是第一中方法
1.把下面这个函数放进代码里面,随意一个class文件都可以,我放进我的hyh_toastutil.jave文件里面
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter(); if (listAdapter == null) { // pre-condition
return;
}
int totalHeight = 0; for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView); // listItem.measure(0, 0);
listItem.measure(
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
2.然后在自己设置设配器之后 viewById.setAdapter(adapter); 之后在使用adapter.notifyDataSetChanged();
hyh_toastutil.setListViewHeightBasedOnChildren(viewById);
去动态调整高度
List<hyh_user> list = mHelper.hyhqueryAll();
cursor=hyhUserDBHelper.hyhcursor_ex;
adapter = new SimpleCursorAdapter(hyhsjk.this, R.layout.list_item, cursor, from, to, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
viewById.setAdapter(adapter);
adapter.notifyDataSetChanged();
hyh_toastutil.setListViewHeightBasedOnChildren(viewById);
3.我使用之后发现一个问题就是 发现在一个矩形内不能展示数据库的所有内容,终会有一两个行的数据看不到,所有我在作者上面的代码上改了一点,加了一点高度,下面是我改了之后的代码。
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter(); if (listAdapter == null) { // pre-condition
return;
}
int totalHeight = 0; for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView); // listItem.measure(0, 0);
listItem.measure(
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
// 如果发现在一个矩形内不能展示数据库的所有内容,可以加这个 2*listItem.getMeasuredHeight()/listAdapter.getCount() 还不行可以把数字改大
totalHeight += listItem.getMeasuredHeight()+2*listItem.getMeasuredHeight()/listAdapter.getCount() ;
}