高级组件之网格视图

1.使用gridview组件创建网格视图
android:columnwidth 设置列的宽度
android:gravity 设置对齐方式
android:horizontal 设置元素之间的水平间距
android:verticalspacing 设置元素之间的垂直间距
android:numcolumns 设置列数
android:stretchmode 设置拉伸模式
布局代码:<GridView
        android:id="@+id/gridView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:numColumns="3"
        android:horizontalSpacing="10px"
        android:verticalSpacing="10px">
    </GridView>
2.新建编写用于布局网格内容的XML文件
<ImageView
        android:id="@+id/imageView1"
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="10px"
        android:scaleType="fitCenter" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="5px"
        android:layout_gravity="center"/>
3.创建两个保存图片ID和说明文字的数组,并将这些图片ID和说明文字添加到List集合中,在创建一个simpleadapter适配器,最后将该适配器与gridview相关联
GridView gridView = (GridView)findViewById(R.id.gridView1);
int[] imageid = new int[]{R.drawable.img19,R.drawable.img20,
R.drawable.img21,R.drawable.img22,R.drawable.img5,
R.drawable.img6,R.drawable.img7,R.drawable.img8,
R.drawable.img9,R.drawable.img10,R.drawable.img11,
R.drawable.img12,R.drawable.img13,R.drawable.img14,
R.drawable.img15,R.drawable.img16,R.drawable.img17,
R.drawable.img18};
String[] title = new String[]{"1","2","3","4","5","6","7","8",
"9","10","11","12","13","14","15","16","17","18"};
List<Map<String, Object>> listItems = new ArrayList<Map<String,Object>>();
for (int i = 0; i < imageid.length; i++) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("image", imageid[i]);
map.put("title", title[i]);
listItems.add(map);
}
SimpleAdapter adapter = new SimpleAdapter(this, listItems,
R.layout.activity_items, new String[]{"title","image"},
new int[]{R.id.textView1,R.id.imageView1} );
gridView.setAdapter(adapter);

高级组件之网格视图_第1张图片

你可能感兴趣的:(android)