本文实现如下效果
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();
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, ).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(,));
image.setScaleType(ImageView.ScaleType.CENTER_CROP);
image.setPadding(, , , );
}
else
image=(ImageView)convertView; image.setImageResource(ids[position]);
return image;
} } }
grid.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" > <GridView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/girdview" /> </LinearLayout>