方法1、网上很多流行的方法,先测量listview或gridview的高度,然后再scrollview中设为定值
public static void setListViewHeightBasedOnChildren(ListView listView) { ListAdapter listAdapter = listView.getAdapter(); if (listAdapter == null) { listView.setVisibility(View.GONE); 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); }
这个方法好像只能测量list item为linearlayout为根布局的情况(因为其他的Layout(如RelativeLayout)没有重写onMeasure(),所以会在onMeasure()时抛出异常),比较容易才出现测量不准,和一些未知错误。
方法2、网上流行的另一种方法
1.在ScrollView中添加一属性 android:fillViewport="true" ,这样就可以让ListView全屏显示了
2.指定ListView的高度 android:layout_height="420dp" ;
方法3、重写listview或gridview(个人认为最好的方法,也是我一直在用的)
package com.caiying.idota.view; import android.content.Context; import android.util.AttributeSet; import android.widget.GridView; public class MultiGridView extends GridView { public MultiGridView(Context context, AttributeSet attrs) { super(context, attrs); } public MultiGridView(Context context) { super(context); } public MultiGridView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, expandSpec); } }
package com.caiying.idota.view; import android.content.Context; import android.util.AttributeSet; import android.widget.ListView; public class MultiListView extends ListView { public MultiListView(Context context, AttributeSet attrs) { super(context, attrs); } public MultiListView(Context context) { super(context); } public MultiListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, expandSpec); } }