安卓--网格视图(GridView)实例

本文展示了一个使用Android中GridView和SimpleAdapter实现图片网格布局的例子。通过反射机制动态获取资源并填充到网格视图中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

main.xml代码如下:

<?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" >

    <GridView
        android:id="@+id/myGridView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:numColumns="3"
        android:stretchMode="columnWidth" >
    </GridView>

</LinearLayout>

grid_layout.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:orientation="vertical" >
    <ImageView
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scaleType="center"
        android:padding="3px"/>

</LinearLayout>

.java代码 如下:

package org.lxh.demo;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;

import android.os.Bundle;

import android.widget.GridView;
import android.widget.SimpleAdapter;

public class Hello extends Activity {
	private List<Map<String, Integer>> list = new ArrayList<Map<String, Integer>>();
	private SimpleAdapter simpleAdapter = null;
	private GridView gridView = null;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState); // 生命周期方法
		super.setContentView(R.layout.main); // 设置要使用的布局管理器
		this.initAdapter();
		this.gridView = (GridView) super.findViewById(R.id.myGridView);
		this.gridView.setAdapter(this.simpleAdapter);

	}

	private void initAdapter() {
		Field[] fields = R.drawable.class.getDeclaredFields();//反射机制
		for (int x = 0; x < fields.length; x++) {
			if (fields[x].getName().startsWith("png_")) {
				Map<String, Integer> map = new HashMap<String, Integer>();
				try {
					map.put("img", fields[x].getInt(R.drawable.class));
				} catch (IllegalArgumentException e) {

					e.printStackTrace();
				} catch (IllegalAccessException e) {

					e.printStackTrace();
				}
				this.list.add(map);
			}
			this.simpleAdapter = new SimpleAdapter(this, this.list,
					R.layout.grid_layout, new String[] { "img" },
					new int[] { R.id.img });
		}
	}
}

效果如下:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值