您的位置:首页 > 移动开发 > Android开发

Android中GridView水平滚动和垂直滚动的实现(动态)

2012-07-19 22:00 661 查看
经过本人实验,完美实现水平滚动和垂直滚动。话不多说,先看布局文件:

<?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,否则你的程序是要报异常的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: