1. 程式人生 > >Android中GridView水平滾動和垂直滾動的實現(動態)

Android中GridView水平滾動和垂直滾動的實現(動態)

經過本人實驗,完美實現水平滾動和垂直滾動。話不多說,先看佈局檔案:

<?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="match_parent"
        android:layout_height="fill_parent" >

        <FrameLayout
            android:layout_width="fill_parent"
            android:layout_height="match_parent" >

            <LinearLayout
                android:id="@+id/linearLayout_gridtableLayout"
                android:layout_width="300dp"
                android:layout_height="match_parent"
                android:orientation="horizontal" >


                <GridView
                    android:id="@+id/tablegrid"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:layout_gravity="center"
                    android:background="#ffffff"
                    android:columnWidth="100dp"
                    android:gravity="center"
                    android:horizontalSpacing="1dp"
                    android:scrollbarAlwaysDrawHorizontalTrack="true"
                    android:scrollbarAlwaysDrawVerticalTrack="true"
                    android:scrollbars="horizontal|vertical"
                    android:verticalSpacing="1dp" />

            </LinearLayout>
        </FrameLayout>
    </HorizontalScrollView>

</LinearLayout>

指定其中LinearLayout的寬度就能夠實現你GridView的長寬變化,如果它的長超過螢幕,則自動新增水平滾動條。

但是如果你還想在程式當中動態指定你的GridView的寬度,則示例程式碼如下:

LinearLayout ll_gridetableLayout=
				(LinearLayout)tableView.findViewById(R.id.linearLayout_gridtableLayout);
		ll_gridetableLayout.setLayoutParams(new FrameLayout.LayoutParams(//動態設定寬度
				100*coloumnNum,
				LinearLayout.LayoutParams.MATCH_PARENT));

這裡要注意了,雖然我們要修改LinearLayout的寬度,但是我們卻不能使用LinearLayout.LyoutParam來作為它setLayoutParms的引數,而必須使用它的parent,也就是FrameLayout的LayoutParam,否則你的程式是要報異常的。