Android 中 GridView嵌套在ScrollView里只有一行的解决方法
程序员文章站
2024-03-04 17:24:29
在做android项目中遇到一个bug,gridview嵌套在scrollview里只有一行的问题。下面小编在网上找到了解决方法,具体方法如下所示:
方法一:就是上面说的...
在做android项目中遇到一个bug,gridview嵌套在scrollview里只有一行的问题。下面小编在网上找到了解决方法,具体方法如下所示:
方法一:就是上面说的通过计算出来listview或者gridview中的子列高度和 进行显示:
public void setlistviewheightbasedonchildren(listview listview) { listadapter listadapter = listview.getadapter(); if (listadapter == null) { 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)); ((marginlayoutparams)params).setmargins(15, 15, 15, 15); listview.setlayoutparams(params); }
方法二:重写gridview和listview的onmeasure方法,直接给它一个足够大的高度:
重写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); } }
重写gridview:
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); } }
xml中的布局:
<com.xxx.mygridview android:id="@+id/mygridview" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:horizontalspacing="5dp" android:numcolumns="4" android:stretchmode="columnwidth" android:verticalspacing="6dp" />
以上所述是小编给大家介绍的android 中 gridview嵌套在scrollview里只有一行的解决方法,希望对大家有所帮助