天天看點

Android 橫向清單GridView 實作橫向滾動

<a target=_blank href="http://www.cnblogs.com/_ymw/p/4147163.html" target="_blank" rel="external nofollow"  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);
    }
           

擴充卡和普通的寫法一緻,就不再贅述.

Demo位址