SimpleAdapter 简单说就是一个适配器,可以将静态数据映射到XML文件中定义好的视图。通常来讲(也可以不适用xml文件,全部用java代码来实现),实现一个GridView需要两个xml布局文件和一个Activity。现贴出代码:
主xml布局文件:gridview.xml
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF" >
<GridView
android:id="@+id/gridView1"
android:layout_width="fill_parent"
android:layout_height="337dp"
android:layout_x="1dp"
android:layout_y="102dp"
android:background="#00000000"
android:columnWidth="90dp"
android:gravity="center"
android:horizontalSpacing="2dp"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="14dp" />
</AbsoluteLayout>
PS:我这里用的是绝对布局。
gridview_list.xml (这个文件主要是实现 main.xml 文件中的 GridView 的布局)。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:paddingBottom="4dip">
<ImageView
android:id="@+id/imageView1"
android:layout_height="70dp"
android:layout_width="70dp"
android:layout_centerHorizontal="true">
</ImageView>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_below="@+id/imageView1"
android:layout_height="wrap_content"
android:textSize="14sp"
android:textColor="#4682B4"
android:layout_centerHorizontal="true">
</TextView>
</RelativeLayout>
java代码部分,GridViewActivity.java
public class GridViewActivity extends Activity{
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.gridview);
GridView gridview = (GridView)findViewById(R.id.gridView1);
//生成动态数组,并且转入数据
ArrayList<HashMap<String, Object>> lstImageItem = new ArrayList<HashMap<String, Object>>();
makeImageButton(R.drawable.ic_launcher, "登录", lstImageItem);
makeImageButton(R.drawable.ic_launcher, "列表", lstImageItem);
makeImageButton(R.drawable.ic_launcher, "树形菜单", lstImageItem);
makeImageButton(R.drawable.ic_launcher, "导航", lstImageItem);
makeImageButton(R.drawable.ic_launcher, "下拉刷新", lstImageItem);
makeImageButton(R.drawable.ic_launcher, "手势切换", lstImageItem);
makeImageButton(R.drawable.ic_launcher, "SQLite", lstImageItem);
makeImageButton(R.drawable.ic_launcher, "选择文件", lstImageItem);
//生成适配器的ImageItem <====> 动态数组的元素,两者一一对应
SimpleAdapter saImageItems = new SimpleAdapter(this, lstImageItem,//数据来源
R.layout.gridview_list,//gridview_list的XML实现
new String[] {"ItemImage","ItemText"},//动态数组与ImageItem对应的子项
new int[] {R.id.imageView1,R.id.textView1});//ImageItem的XML文件里面的一个ImageView,两个TextView ID
//添加并且显示
gridview.setAdapter(saImageItems);
}
//
public void makeImageButton(int picture, String itemText, ArrayList<HashMap<String, Object>> list){
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("ItemImage", picture);//添加图像资源的ID
map.put("ItemText", itemText);//按序号做ItemText
list.add(map);
}
}
同样,实现ListView 也是同样的道理。效果图如下: