首页 > 代码库 > 横向滑动的GridView

横向滑动的GridView

思路:

GridView行数设置为一行,外面套一个HorizontalScrollView,代码中设置GridView宽度

xml代码

<HorizontalScrollView
  android:layout_width="match_parent"  android:layout_height="wrap_content"  android:scrollbars="none" > <LinearLayout   android:layout_width="match_parent"   android:layout_height="wrap_content"   android:orientation="horizontal" >   <GridView      android:id="@+id/gv"     android:layout_width="wrap_content"     android:layout_height="wrap_content" >   </GridView> </LinearLayout>
</HorizontalScrollView>

代码中设置

    // 得到像素密度        DisplayMetrics outMetrics = new DisplayMetrics();        getActivity().getWindowManager().getDefaultDisplay()                .getMetrics(outMetrics);        float density = outMetrics.density; // 像素密度        ViewGroup.LayoutParams params = gridView.getLayoutParams();        int itemWidth = (int) (100 * density);// 默认item宽度为100        int spacingWidth = (int) (5 * density);        params.width = (itemWidth + spacingWidth) * childCount + spacingWidth;        gridView.setStretchMode(GridView.NO_STRETCH); // 设置为禁止拉伸模式        gridView.setNumColumns(childCount);        gridView.setHorizontalSpacing(spacingWidth);        gridView.setColumnWidth(itemWidth);        gridView.setLayoutParams(params);