本文实现如下效果
Test_Grid.java
public class Test_Grid extends Activity { private GridView gridview; private int[] ids={R.drawable.s1,R.drawable.s2,R.drawable.s3,R.drawable.s4,R.drawable.s5}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.grid); gridview =(GridView)findViewById(R.id.girdview); //设置一行显示几个 gridview.setNumColumns(3); gridview.setAdapter(new MyGirdAdapter()); gridview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(Test_Grid.this, ""+position, 1).show(); } }); } private class MyGirdAdapter extends BaseAdapter { @Override public int getCount() { // TODO Auto-generated method stub return ids.length; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return ids[position]; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ImageView image; if(convertView==null) { image=new ImageView(Test_Grid.this); image.setLayoutParams(new GridView.LayoutParams(180,180)); image.setScaleType(ImageView.ScaleType.CENTER_CROP); image.setPadding(6, 6, 6, 6); } else image=(ImageView)convertView; image.setImageResource(ids[position]); return image; } } }
grid.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:layout_width="match_parent" 9 android:layout_height="wrap_content" 10 android:id="@+id/girdview" /> 11 12 13 </LinearLayout>