这次有上次有一点是不同的:
每个图片下面都有一个文本信息。
这次范例就是实现这个功能。再有一点就是前面的方法就是自己实现一个ImageAdapter继承BaseAdapter,再供GridView使用
这次本文介绍的GridView用法跟前文ListView的极其类似,利用适配器SimpleAdapter来完成,我柑橘这样挺简单的。
package xiaosi.gridview;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.SimpleAdapter;
public class GridViewActivity extends Activity {
/** Called when the activity is first created. */
private GridView gridview = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gridview = (GridView) findViewById(R.id.gridview);
//生成数据源 一个List
ArrayList<HashMap<String, Object>> DateList = new ArrayList<HashMap<String, Object>>();
for(int i=0;i<15;i++)
{
//医用HashMap来存储
HashMap<String, Object> hashMap = new HashMap<String, Object>();
//添加图像资源的ID
hashMap.put("Image", R.drawable.a);
//按序号做ItemText
hashMap.put("Text", "NO."+String.valueOf(i));
//添加到List去
DateList.add(hashMap);
}
//生成适配器的simpleAdapter
//DateList 数据源
//R.layout.item 来自于item。xml 控制GridView中每一项的布局(一个ImageView 一个TextView)
//第三个参数是hashoMap的键值
//第四个参数是item。xml中ImageView,TextView的ID
SimpleAdapter simpleAdapter = new SimpleAdapter(this,DateList,R.layout.item,
new String[] {"Image","Text"}, new int[] {R.id.ItemImage,R.id.ItemText});
//添加并且显示
gridview.setAdapter(simpleAdapter);
//添加消息处理
gridview.setOnItemClickListener(new ItemClickListener());
}
private class ItemClickListener implements OnItemClickListener
{
public void onItemClick(AdapterView<?> arg0,View arg1, int arg2,long arg3) {
//arg0就是那个DateList
HashMap<String, Object> item=(HashMap<String, Object>) arg0.getItemAtPosition(arg2);
//显示应用标题的那个TextView
setTitle((String)item.get("Text"));
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:verticalSpacing="5dip"
android:horizontalSpacing="5dip"
android:columnWidth="80dip"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:gravity="center"
/>
创建item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:paddingBottom="4dip" android:layout_width="fill_parent">
<ImageView
android:layout_height="wrap_content"
android:id="@+id/ItemImage"
android:layout_width="wrap_content"
android:layout_centerHorizontal="true">
</ImageView>
<TextView
android:layout_width="wrap_content"
android:layout_below="@+id/ItemImage"
android:layout_height="wrap_content"
android:text="TextView01"
android:layout_centerHorizontal="true"
android:id="@+id/ItemText">
</TextView>
</RelativeLayout>