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

android布局之GridView布局学习小结

2014-06-08 14:54 686 查看
     GridView视图是android开发过程中,很常用的一种视图,该视图将其他控件以二维格式显示在表格中,而被显示的控件全部来自于ListAdapter适配器。     

     一个GridView布局的使用与显示,我们可以按照以下方法进行:

    1. 创建带GridView控件的全局布局文件:

<?xmlversion="1.0"encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="@drawable/bg"
>
<GridView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="4"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:id="@+id/gridView"
/>
</LinearLayout>

      2.创建用来存放网格布局中具体子项item的显示方式的布局,简单的说就是每个网格需要显示哪些内容,现在我们创建一个线性垂直布局,上面为ImageView,下面是TextView.

<?xmlversion="1.0"encoding="UTF-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:contentDescription="image"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:id="@+id/textView"
android:textSize="16sp"
android:textColor="#000099"
/>
</LinearLayout>

       3.存储网格中显示的内容到适配器Adapter中去。上面我们说到了GridView中的数据全部来自于ListAdapter适配器,所有我们需要首先将需要显示的数据填充到Adapter中期股,下面我们就以ListAdapter的子类SimpleAdapter为案例来填充内容。

          首先我们需要定义int数组和字符串数组,分别用来存放资源文件中的图片id和对应的字符串资源

          int[]images={R.drawable.i1,R.drawable.i2,R.drawable.i3,R.drawable.i4,R.drawable.i5,R.drawable.i6,R.drawable.i7,R.drawable.i8};

          String[]testDescs={"搜索","文件管理","下载管理","全屏","网址","书签","加入书签","分享页面"};

publicListAdaptergetAdapter(){
List<Map<String,Object>>griList=newArrayList<Map<String,Object>>();
for(inti=0;i<images.length;i++){
HashMap<String,Object>imgMap=newHashMap<String,Object>();
imgMap.put("image",images[i]);
imgMap.put("names",testDescs[i]);

griList.add(imgMap);
}

SimpleAdaptersimpleAdepter=newSimpleAdapter(this,griList,R.layout.grid_item,newString[]{"image","names"},newint[]{R.id.imageView,R.id.textView});
returnsimpleAdepter;
}

        注:首先将资源ID和其对应的描述存放在Map中,再将Map添加到list中;SimpleAdapter中最后2个参数分别表示Map中的key组成的数组,和GrideView的子项item中对应的控件ID构成的int数组,表示将grilist中存放的数据,从Map中映射到布局中去

        4.获取布局中的GridView控件,并为其设置Adapater适配器

	//找到gridView对象
GridViewgridView=(GridView)findViewById(R.id.gridView);
gridView.setAdapter(getAdapter());


 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  gridview android