ScrollView中嵌套GridView,ListView时只显示一行的解决办法,详见:http://blog.csdn.net/luohai859/article/details/39347583
方法一:自定义ListView、GridView
public class MyListView extends ListView {
public MyListView(Context context) {
super(context);
}
public MyListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
public class MyGridView extends GridView {public MyGridView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyGridView(Context context) {
super(context);
}
public MyGridView(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);
}
}
方法二:通过计算子列高度和进行显示
/**
* 通过计算出来ListView或者GridView中的子列高度和进行显示
*/
public void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();//获取ListView对应的Adapter
if (listAdapter == null) return;
int totalHeight = 0;
//遍历item,计算item的宽高,统计出所有item的总高度
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));//加上item间分隔符占用的高度
//((MarginLayoutParams) params).setMargins(10, 10, 10, 10); // 根据情况决定是否设置margin值
listView.setLayoutParams(params);
}
我使用第二种方式时遇到的小问题
注意:单独用一个ScrollView包住ListView时这种方法是无效的,此方法需要ScrollView的根节点是LinearLayout或者RelativeLayout。
<ScrollView
android:id="@+id/sv"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ListView
android:id="@+id/gv"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
</ScrollView>