<a target=_blank href="http://www.cnblogs.com/_ymw/p/4147163.html" style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">原帖地址</a>
通过 HorizontalScrollView嵌套GridView来实现横向滚动的GridView
主界面布局代码:activity_main.xml
a.包裹HorizontalScrollView控件是GirdView横向滚动的基本条件
b.GirdView外包裹LinearLayout是java代码中参数设置的必要条件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<HorizontalScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_margin="10dp" >
<GridView
android:id="@+id/grid"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="spacingWidthUniform" >
</GridView>
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
在java文件中设置GridView一些参数:
/**设置GirdView参数,绑定数据*/
private void setGridView() {
int size = cityList.size();
int length = 100;
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
float density = dm.density;
int gridviewWidth = (int) (size * (length + 4) * density);
int itemWidth = (int) (length * density);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
gridviewWidth, LinearLayout.LayoutParams.FILL_PARENT);
gridView.setLayoutParams(params); // 设置GirdView布局参数,横向布局的关键
gridView.setColumnWidth(itemWidth); // 设置列表项宽
gridView.setHorizontalSpacing(5); // 设置列表项水平间距
gridView.setStretchMode(GridView.NO_STRETCH);
gridView.setNumColumns(size); // 设置列数量=列表集合数
GridViewAdapter adapter = new GridViewAdapter(getApplicationContext(),
cityList);
gridView.setAdapter(adapter);
}
适配器和普通的写法一致,就不再赘述.