网格视图,一行四列,每列显示四个图片,每个图形下有一个对应的标题
1.gridview.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/llayout"
>
<GridView android:id="@+id/gridView1"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:stretchMode="columnWidth"
android:numColumns="4"></GridView>
</LinearLayout>
2.item.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/image"
android:paddingLeft="10px"
android:scaleType="fitCenter"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5px"
android:layout_gravity="center"
android:id="@+id/title"
/>
</LinearLayout>
3.MainActivity
private int[] imageId = new int[] { R.drawable.img01, R.drawable.img02,
R.drawable.img03, R.drawable.img04, R.drawable.img05,
R.drawable.img06, R.drawable.img07, R.drawable.img08,
R.drawable.img09, R.drawable.img10, R.drawable.img11,
R.drawable.img12, }; // 定义并初始化保存图片id的数组
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gridview);
GridView gridview = (GridView) findViewById(R.id.gridView1); // 获取GridView组件
/***********************使用SimpleAdapter指定要显示的内容*********************************/
String[] title = new String[] { "花开富贵", "海天一色", "日出", "天路", "一枝独秀",
"云", "独占鳌头", "蒲公英花", "花团锦簇", "争奇斗艳", "和谐", "林间小路" }; // 定义并初始化保存说明文字的数组
List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();// 创建一个list集合
// 通过for循环将图片id和列表项文字放到Map中,并添加到list集合中
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); // 将map对象添加到List集合中
}
SimpleAdapter adapter = new SimpleAdapter(this,//SimpleAdapter关联的view的运行环境
listItems,//由map构成的list列表[{,}, {,}, ...]
R.layout.items,//布局文件,包括map中对应的value的id
new String[] { "title", "image" },//添加到map映射上的键名(key值而非value)
new int[] {R.id.title, R.id.image }//map中对应的value的id
); // 创建SimpleAdapter
gridview.setAdapter(adapter); // 将适配器与GridView关联
}