【网上很多说使用动态修改listview高度的方法,然而并不能解决每个item高度不同的listview的显示不全的问题。如下第一种方法,建议使用第二种方法】
一、在数据适配器通知数据改变后调用以下方法,动态修改listview的高度
[代码]:
===================
/**
* 动态设置ListView的高度
* @param listView
*/
public static void setListViewHeightBasedOnChildren(ListView listView) {
if(listView == null) return;
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);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
===================
二、那么我们来介绍这个更强大的办法,重写ListView
代码:
===================
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;
public class MyListView extends ListView {
public MyListView(Context context) {
// TODO Auto-generated method stub
super(context);
}
public MyListView(Context context, AttributeSet attrs) {
// TODO Auto-generated method stub
super(context, attrs);
}
public MyListView(Context context, AttributeSet attrs, int defStyle) {
// TODO Auto-generated method stub
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
====================
接下来只要在布局使用就可以了
代码:
====================
<com.test.view.MyListView
android:id="@+id/lvComments"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="@dimen/dimen_20_dip"
android:divider="@null"
android:scrollbars="@null" >
</com.test.view.MyListView>
====================