Android多行gridview横向滑动的实现

关键代码

    /**
     * 设置GridView的宽度
     *
     * @param defaultColumns 设置列数 4
     * @param defaultRows    设置行数 2
     */
    private void setGridViewValue(GridView gridView, int postion, int defaultColumns, int defaultRows) {

        int count = recomGameAdapter.getCount();
        gridView.setAdapter(recomGameAdapterList.get(postion));
        int columns = 0;
        if (count >= 8) {
           //当count大于8时  如下排列
           //| 1 | 3 | 5 | 7 |
           //| 2 | 4 | 6 | 8 |
            columns = (count % 2 == 0) ? count / 2 : count / 2 + 1;
        } else {
           //当count小于于8时  如下排列
           //| 1 | 2 | 3 | 4 |
           //| 5 | 6 | 7 | 8 |
            columns = (count % defaultRows == 0) ? count / defaultRows : count / defaultRows + 1;
            if (columns < defaultColumns) {
                columns = defaultColumns;
            }
        }

        int columnWidth = (dm.widthPixels - mContext.getResources().getDimensionPixelOffset(R.dimen.home_common_margin) * 2) / defaultColumns;
        RelativeLayout.LayoutParams params =
                new RelativeLayout.LayoutParams
                        (columns * columnWidth, RelativeLayout.LayoutParams.WRAP_CONTENT);
        gridView.setLayoutParams(params);
        gridView.setColumnWidth(columnWidth);
        // gridView.setHorizontalSpacing(hSpacing);
        gridView.setStretchMode(GridView.NO_STRETCH);
        gridView.setNumColumns(columns);
    }

布局文件

xml version="1.0" encoding="utf-8"?>
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scrollView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:fillViewport="true"
    android:scrollbars="none">


    <GridView
        android:id="@+id/recom_game_gv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/day_recom_rl"
        android:numColumns="4"
        android:scrollbars="none"
        android:stretchMode="columnWidth">GridView>

    <
HorizontalScrollView>

你可能感兴趣的:(Android基础,Android技巧)