安卓高级组件------网格视图

来源:互联网 发布:科学怪人 知乎 编辑:程序博客网 时间:2024/05/16 05:40
网格视图<GridView>安卓常用的规划容器,视图自身分为行列的矩阵,单元格放置自己的组件和内容,通常是放图片和文字。网格视图和列表视图有着共同的父类:AbsListView,区别在于:ListView显示的是一个列,而GridView可以通过控制列的数目。数据配置方面,GridView和ListView类似,都要通过适配器进行数据配置。

GridView常用的xml属性:

                  android:columnWidth       列宽度

                  android:numColumns       列数目

                  android:gravity                设置对其方式

                  android:horizentalSpacing      元素水平间距

                  android:strechMode          单元格的拉伸模式

                  android:verticleSpacing     元素的垂直间距

下面用一个显示图片的实例简单使用一下GridView:

1.布局文件中加入一个GridView,设置列数目为3

复制代码
    <GridView        android:id="@+id/gridView1"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:numColumns="3" >    </GridView>
复制代码

2.对于单元格内部,我们再使用一个xml文件设置布局(单元格内布局),这个文件为content.xml,具体细节如下:

复制代码
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:gravity="center"    android:orientation="vertical" >    <ImageView        android:id="@+id/imageView1"        android:layout_width="wrap_content"        android:layout_height="wrap_content" />    <TextView        android:id="@+id/textView1"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:gravity="center" /></LinearLayout>
复制代码

3.获取网格列表,之后定义图片数组和名字数组,并将这两个数组塞入List<Map<String,Object>>链表

复制代码
        gv = (GridView)findViewById(R.id.gridView1);                img = new int[]{R.drawable.img1,R.drawable.img2,R.drawable.img3,                R.drawable.img4,R.drawable.img5,R.drawable.img6,                R.drawable.img7,R.drawable.img8,R.drawable.img9};                String[] name = new String[]{"大娃","二娃","三娃","四娃","五娃","六娃","七娃","小金刚","爷爷"};                List<Map<String,Object>> listItems = new ArrayList<Map<String,Object>>();                for(int i = 0; i < img.length - 1;i ++){            Map<String, Object> map = new HashMap<String,Object>();            map.put("image", img[i]);            map.put("name", name[i]);            listItems.add(map);        }
复制代码

4.创建一个适配器,指定布局,数据,数据来源,数据指向,并绑定给网格布局

        SimpleAdapter s = new SimpleAdapter(this, listItems, R.layout.content,                new String[]{"image","name"}, new int[]{R.id.imageView1,R.id.textView1});                gv.setAdapter(s);

水平有限,请留言!

0 0
原创粉丝点击