今天是我在深圳的第三天上班,做安卓研发,用到了个以后将常要用到的东西,记录下来(里面巧妙运用了循环语句,我觉得不错)。
java代码:
package com.example.xsgj.activity.menu;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.SimpleAdapter;
public class JXCActivity extends Activity {
private GridView _gridView1;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
_gridView1 = (GridView) findViewById(R.id.menu);
// 生成动态数组,并且转入数据
ArrayList<HashMap<String, Object>> lstImageItem = new ArrayList<HashMap<String, Object>>();
for (int i = 0; i < 2; i++) {
HashMap<String, Object> map = new HashMap<String, Object>();
if (i == 0) {
map.put("ItemImage", R.drawable.dianmian);
map.put("ItemText", "店面");
} else if (i == 1) {
map.put("ItemImage", R.drawable.dingdan);
map.put("ItemText", "订单");
}
lstImageItem.add(map);
}
// 生成适配器的ImageItem <====> 动态数组的元素,两者一一对应
SimpleAdapter saImageItems = new SimpleAdapter(this,
lstImageItem,// 数据来源
R.layout.layout_gridview_item,// night_item的XML实现
// 动态数组与ImageItem对应的子项
new String[] { "ItemImage", "ItemText" },
// ImageItem的XML文件里面的一个ImageView,一个TextView ID
new int[] { R.id.imageView_ItemImage, R.id.textView_ItemText });
// 添加并且显示
_gridView1.setAdapter(saImageItems);
}
}
acitivity_menu.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" >
<include layout="@layout/header" >
</include>
<GridView
android:id="@+id/menu"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:numColumns="2" >
</GridView>
</LinearLayout>