GridView
布局文件声明GridViewjava里创建GridView 配置 1、准备数据源 2、新建适配器(SimpleAdapter) 3、GridView加载适配器 4、GridView配置监听器(OnItemClickListener) gridView实现过程: 1.准备数据源 dataList=new ArrayList<Map<String,Object>>(); 2.新建适配器(SimpleAdapter) adapter=new SimpleAdapter(this,getData(),自定义布局,new String[]{"image","text"},new int[]{R.id.image,R.id.text}); (getData方法内容见笔记附录1) 3.gridView加载适配器 gridView.setAdapter(adapter); 4.gridView配置时间监听器(OnItemClickListener) 插入接口OnItemClickListener gridView.setOnItemClickListener(this); (onItemClick见笔记附录2) 1.getData方法内部 private List<Map<String,Object>> getData(){ for(int i=0;i<icon.length;i++){ Map<String,Object>map=new HashMap<String,Object>(); map.put("image",icon[i]); map.put("text",iconName[i]); dataList.add(map); } return dataList; } 2.public void onItemClick(...){ Toast.makeText(this,"我是"+iconName[position],Toast.LENGTH_SHORT).show(); }
GridView的三种属性:
android:numColumns="" 每一行显示多少列
android:horizontalSpacing="" 两列之间的距离
android:verticalSpacing="" 两行之间的距离
其中,android:numColumns="auto_fit" 将实现自动适配的效果,但实际上可能不好看,还是应该人为规定有多少列数,同时修改ImageButton的大小,本节的示例是将原来的warp_content改成60dp。
清单文件中:android:theme="@android:style/Theme.Black.NoTitleBar"
1 public class MainActivity extends Activity implements OnItemClickListener { 2 private GridView gridView; 3 private List<Map<String, Object>> dataList; 4 5 private SimpleAdapter adapter; 6 int[] icon = { R.drawable.g, R.drawable.h, R.drawable.k, 7 R.drawable.th_qq, R.drawable.a, R.drawable.b, R.drawable.c, 8 R.drawable.d, R.drawable.f, R.drawable.h, }; 9 String[] iconName = { "小白菜", "土豆", "藕片", "南瓜", "番茄", "土豆", "小白菜", 10 "西瓜", "木耳", "黄瓜", }; 11 @Override 12 protected void onCreate(Bundle savedInstanceState) { 13 super.onCreate(savedInstanceState); 14 setContentView(R.layout.fragment_main); 15 gridView=(GridView)findViewById(R.id.gridview1); 16 // 准备数据源 17 // 新建适配器 18 // GridView加载适配器 19 // GridView配置事件监听器(OnItemClinckListener) 20 dataList = new ArrayList<Map<String, Object>>(); 21 22 adapter = new SimpleAdapter(this, getDate(), R.layout.item, 23 new String[] {"image", "text" }, new int[] { R.id.imageView1, 24 R.id.text }); 25 gridView.setAdapter(adapter); 26 gridView.setOnItemClickListener(this); 27 } 28 29 private List<Map<String, Object>> getDate() { 30 31 32 for(int i=0;i<icon.length;i++){ 33 Map<String, Object> map=new HashMap<String, Object>(); 34 map.put("image", icon[i]); 35 map.put("text", iconName[i]); 36 dataList.add(map); 37 38 } 39 return dataList; 40 } 41 @Override 42 public void onItemClick(AdapterView<?> parent, View view, int position, 43 long id) { 44 // TODO Auto-generated method stub 45 46 Toast.makeText(this, "我是"+iconName[position], 0).show(); 47 }