Android攻城狮GridView(主菜单)

【Android攻城狮GridView(主菜单)】得意犹堪夸世俗,诏黄新湿字如鸦。这篇文章主要讲述Android攻城狮GridView(主菜单)相关的知识,希望能为你提供帮助。

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 { 2private GridView gridView; 3private List< Map< String, Object> > dataList; 4 5private SimpleAdapter adapter; 6int[] icon = { R.drawable.g, R.drawable.h, R.drawable.k, 7R.drawable.th_qq, R.drawable.a, R.drawable.b, R.drawable.c, 8R.drawable.d, R.drawable.f, R.drawable.h, }; 9String[] iconName = { "小白菜", "土豆", "藕片", "南瓜", "番茄", "土豆", "小白菜", 10"西瓜", "木耳", "黄瓜", }; 11@Override 12protected void onCreate(Bundle savedInstanceState) { 13super.onCreate(savedInstanceState); 14setContentView(R.layout.fragment_main); 15gridView=(GridView)findViewById(R.id.gridview1); 16// 准备数据源 17// 新建适配器 18// GridView加载适配器 19// GridView配置事件监听器(OnItemClinckListener) 20dataList = new ArrayList< Map< String, Object> > (); 21 22adapter = new SimpleAdapter(this, getDate(), R.layout.item, 23new String[] {"image", "text" }, new int[] { R.id.imageView1, 24R.id.text }); 25gridView.setAdapter(adapter); 26gridView.setOnItemClickListener(this); 27} 28 29private List< Map< String, Object> > getDate() { 30 31 32for(int i=0; i< icon.length; i++){ 33Map< String, Object> map=new HashMap< String, Object> (); 34map.put("image", icon[i]); 35map.put("text", iconName[i]); 36dataList.add(map); 37 38} 39return dataList; 40} 41@Override 42public void onItemClick(AdapterView< ?> parent, View view, int position, 43long id) { 44// TODO Auto-generated method stub 45 46Toast.makeText(this, "我是"+iconName[position], 0).show(); 47}

 























    推荐阅读