Listview或者GridView嵌套在ScrollView中只显示一行item解决方法。
页面里有ListView(GridView)和一些固定布局让他们一起在整个屏幕上滚动方法:
一、解决办法。(可用)
(1)自定义ListView(GridView),重写onMeasure()方法,我以GridView为例(ListView只需要extends ListView)具体代码如下:
1 public class AntGridView extends GridView { 2 3 public AntGridView(Context context) { 4 super(context); 5 } 6 7 public AntGridView(Context context, AttributeSet attrs) { 8 super(context, attrs); 9 } 10 11 public AntGridView(Context context, AttributeSet attrs, int defStyle) { 12 super(context, attrs, defStyle); 13 } 14 /*重点在这里重写onMeasure()*/ 15 @Override 16 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 17 int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, 18 MeasureSpec.AT_MOST); 19 20 super.onMeasure(widthMeasureSpec, expandSpec); 21 } 22 23 24 }
(2)在布局文件中将整个布局放在ScollerView中,要使用的GridView或者ListView使用自定义的HeaderGridView,具体xml代码如下:
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:orientation="vertical"> 6 7 <ScrollView 8 android:layout_width="match_parent" 9 android:layout_height="match_parent"> 10 11 <LinearLayout 12 android:layout_width="match_parent" 13 android:layout_height="wrap_content" 14 android:orientation="vertical"> 15 <LinearLayout 16 android:layout_width="match_parent" 17 android:layout_height="180dp" 18 android:background="#00aa00"> 19 20 </LinearLayout> 21 22 <!-- 一定要是自定义View的包名和类名 --> 23 <top.ant.view.AntGridView 24 android:id="@+id/ant_live_index_gridview" 25 android:layout_width="match_parent" 26 android:layout_height="match_parent" 27 android:numColumns="2"> 28 29 30 </top.ant.view.AntGridView> 31 </LinearLayout> 32 </ScrollView> 33 34 35 </LinearLayout>
二、 动态计算子view的高度,传给ScrollView
1 public void setListViewHeightBasedOnChildren(ListView listView) { 2 ListAdapter listAdapter = listView.getAdapter(); 3 if (listAdapter == null) { 4 return; 5 } 6 7 int totalHeight = 0; 8 for (int i = 0; i < listAdapter.getCount(); i++) { 9 View listItem = listAdapter.getView(i, null, listView); 10 listItem.measure(0, 0); 11 totalHeight += listItem.getMeasuredHeight(); 12 } 13 14 ViewGroup.LayoutParams params = listView.getLayoutParams(); 15 params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); 16 ((MarginLayoutParams)params).setMargins(10, 10, 10, 10); 17 listView.setLayoutParams(params); 18 }