ListView与GridView自适应高度,与Bug解决gridView.getNumColumns() = -1

ListView自适应:
public static 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));
        listView.setLayoutParams(params);
    }
GridView自适应,存在Bug待解决
// listView.getNumColumns() = -1?; 始终返回 -1;
 
  
 public static void setListViewHeightBasedOnChildren(GridView listView) {
        // 获取listview的adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        // 固定列宽,有多少列
        int col = 3;
        // listView.getNumColumns() = -1?;
        // i每次加4,相当于listAdapter.getCount()小于等于4时 循环一次,计算一次item的高度,
        // listAdapter.getCount()小于等于8时计算两次高度相加
        /*for (int i = 0; i < listAdapter.getCount(); i += col) {
            // 获取listview的每一个item
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            // 获取item的高度和
            totalHeight += listItem.getMeasuredHeight();
        }*/
        View listItem = listAdapter.getView(0, null, listView);
        listItem.measure(0, 0);
        // 获取item的高度和
        int totalHeight = listItem.getMeasuredHeight();
        // 获取listview的布局参数
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        if (listAdapter.getCount() % col != 0) {
            totalHeight = totalHeight * (listAdapter.getCount() / col + 1);
        } else {
            totalHeight = totalHeight * (listAdapter.getCount() / col);
        }

        // 设置高度
        params.height = totalHeight;
        // 设置margin
        ((MarginLayoutParams) params).setMargins(10, 10, 10, 10);
        // 设置参数
        listView.setLayoutParams(params);
    }
* Set the number of columns in the grid
     *
     * @param numColumns The desired number of columns.
     *
     * @attr ref android.R.styleable#GridView_numColumns
     */
    publicvoid setNumColumns(intnumColumns) {
        if(numColumns != mRequestedNumColumns) {
            mRequestedNumColumns = numColumns;
            requestLayoutIfNecessary();
        }
    }
debug中在这里发现mRequestedNumColumns 能正确获得colums num值,所以想通过反射获取该值插入;

Field field = GridView.class.getDeclaredField("mRequestedNumColumns"); // 获得申明的字段
field.setAccessible(true); // 设置访问权限
column = Integer.valueOf(field.get(gridView).toString()); // 获取字段的值
剩下的就简单了!!!
 
  
 
  
 
 

你可能感兴趣的:(Android高级,实战经验)