本人参照CSDN上一位技术专家博客的文章(原文地址:http://blog.csdn.net/hellogv/archive/2009/09/19/4567095.aspx,标题“Android入门第八篇之GridView(九宫图)),做了下测试。
主界面图如下:
共涉及三段代码:main.xml、item.xml以及java源代码。(说明:代码引自上面所列博客里的内容,仅做小量改动)。
1、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:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:columnWidth="90dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/hellogv/archive/2009/09/19/4567095.aspx
2、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>
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/hellogv/archive/2009/09/19/4567095.aspx
3、java源代码
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gridview = (GridView) findViewById(R.id.gridview);
//生成动态数组,并且转入数据
ArrayList<HashMap<String, Object>> lstImageItem = new ArrayList<HashMap<String, Object>>();
for(int i=0;i<10;i++)
{
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("ItemImage", R.drawable.icon);//添加图像资源的ID
map.put("ItemText", "测试");
lstImageItem.add(map);
}
//生成适配器的ImageItem <====> 动态数组的元素,两者一一对应
SimpleAdapter saImageItems = new SimpleAdapter(this, //没什么解释
lstImageItem,//数据来源
R.layout.night_item,//night_item的XML实现
//动态数组与ImageItem对应的子项
new String[] {"ItemImage","ItemText"},
//ImageItem的XML文件里面的一个ImageView,两个TextView ID
new int[] {R.id.ItemImage,R.id.ItemText});
//添加并且显示
gridview.setAdapter(saImageItems);
//添加消息处理
gridview.setOnItemClickListener(new ItemClickListener());
}
//当AdapterView被单击(触摸屏或者键盘),则返回的Item单击事件
class ItemClickListener implements OnItemClickListener
{
public void onItemClick(AdapterView<?> arg0,//The AdapterView where the click happened
View arg1,//The view within the AdapterView that was clicked
int arg2,//The position of the view in the adapter
long arg3//The row id of the item that was clicked
) {
//在本例中arg2=arg3
HashMap<String, Object> item=(HashMap<String, Object>) arg0.getItemAtPosition(arg2);
//显示所选Item的ItemText
setTitle((String)item.get("ItemText"));
}
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/hellogv/archive/2009/09/19/4567095.aspx
问题来了,我把上面item.xml中的imageview换成imagebutton之后,再点击图标,就不会触发ItemClickListener事件了,非常奇怪,麻烦各位帮忙分析下原因。