1.xml布局文件
main.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:orientation="vertical" > 6 7 <GridView 8 android:id="@+id/girdView1" 9 android:numColumns="2" 10 android:verticalSpacing="10dp" 11 android:horizontalSpacing="10dp" 12 android:layout_width="wrap_content" 13 android:layout_height="wrap_content"> 14 </GridView> 15 16 <!-- 17 android:numColumns //列数 18 android:verticalSpacing //两行之间的距离 19 android:horizontalSpacing //两列之间的距离 20 --> 21 22 </LinearLayout>
item.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:orientation="vertical" 6 android:gravity="center" > 7 8 <ImageView 9 android:id="@+id/imageView1" 10 android:layout_width="60dp" 11 android:layout_height="60dp" 12 android:src="@drawable/a"/> 13 14 <TextView 15 android:id="@+id/textView1" 16 android:layout_marginTop="5dp" 17 android:layout_width="wrap_content" 18 android:layout_height="wrap_content" 19 android:textSize="15sp" 20 android:text="阿森纳"/> 21 22 23 </LinearLayout>
2.java代码
1 public class MainActivity extends ActionBarActivity implements OnItemClickListener { 2 3 private GridView gv1; 4 private List<Map<String,Object>> dataList; 5 private int[] pic = {R.drawable.a,R.drawable.l,R.drawable.m,R.drawable.q}; 6 private String[] name = {"阿森纳","利物浦","曼联","切尔西"}; 7 private SimpleAdapter sa; 8 9 @Override 10 protected void onCreate(Bundle savedInstanceState) { 11 super.onCreate(savedInstanceState); 12 setContentView(R.layout.main); 13 14 gv1 = (GridView) findViewById(R.id.girdView1); 15 //初始化 16 dataList = new ArrayList<Map<String,Object>>(); 17 18 //1.准备数据源 19 //2.新建适配器(SimpleAdapter) 20 //3.GridView加载适配器 21 //4.GridView配置时间监听器(onItemClickListener) 22 23 sa = new SimpleAdapter(this, getData(),R.layout.item ,new String[]{"pic","name"}, new int[]{R.id.imageView1,R.id.textView1}); 24 gv1.setAdapter(sa); 25 gv1.setOnItemClickListener(this); 26 27 28 29 } 30 private List<Map<String,Object>> getData() { 31 for(int i =0;i<pic.length;i++){ 32 Map<String,Object> map = new HashMap<String, Object>(); 33 map.put("pic", pic[i]); 34 map.put("name", name[i]); 35 dataList.add(map); 36 } 37 return dataList; 38 } 39 @Override 40 public void onItemClick(AdapterView<?> parent, View view, int position, 41 long id) { 42 // TODO Auto-generated method stub 43 Toast.makeText(this, "我是"+name[position], Toast.LENGTH_SHORT).show(); 44 } 45 }
时间: 2024-10-07 03:37:05