Android的GridView控件用于把一系列的空间组织成一个二维的网格显示出来应用的比较多的就是组合图片显示下面我就详细讲一个例子
首先写一个类继承BaseAdapter
[Java]代码
package com.yarin.android.Examples_04_19; |
03 |
import android.content.Context; |
04 |
import android.view.View; |
05 |
import android.view.ViewGroup; |
06 |
import android.widget.BaseAdapter; |
07 |
import android.widget.GridView; |
08 |
import android.widget.ImageView; |
10 |
public class ImageAdapter extends BaseAdapter |
13 |
private Context mContext; |
15 |
private Integer[] mImageIds = |
28 |
public ImageAdapter(Context c) |
36 |
return mImageIds.length; |
40 |
public Object getItem( int position) |
47 |
public long getItemId( int position) |
53 |
public View getView( int position, View convertView, ViewGroup parent) |
56 |
if (convertView == null ) |
59 |
imageView = new ImageView(mContext); |
61 |
imageView.setLayoutParams( new GridView.LayoutParams( 85 , 85 )); |
63 |
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER); |
67 |
imageView = (ImageView) convertView; |
70 |
imageView.setImageResource(mImageIds[position]); |
[代码] [Java]代码
01 |
package com.yarin.android.Examples_04_19; |
03 |
import android.app.Activity; |
04 |
import android.os.Bundle; |
05 |
import android.view.View; |
06 |
import android.widget.AdapterView; |
07 |
import android.widget.GridView; |
08 |
import android.widget.Toast; |
09 |
import android.widget.AdapterView.OnItemClickListener; |
11 |
public class Activity01 extends Activity |
13 |
/** Called when the activity is first created. */ |
15 |
public void onCreate(Bundle savedInstanceState) |
17 |
super .onCreate(savedInstanceState); |
18 |
setContentView(R.layout.main); |
21 |
GridView gridview = (GridView) findViewById(R.id.gridview); |
23 |
gridview.setAdapter( new ImageAdapter( this )); |
26 |
gridview.setBackgroundResource(R.drawable.bg0); |
29 |
gridview.setOnItemClickListener( new OnItemClickListener() { |
30 |
public void onItemClick(AdapterView<?> parent, View v, int position, long id) |
32 |
Toast.makeText(Activity01. this , "你选择了" + (position + 1 ) + " 号图片" , Toast.LENGTH_SHORT).show(); |
[代码] [XML]代码
01 |
<? xml version = "1.0" encoding = "utf-8" ?> |
02 |
< GridView xmlns:android = "http://schemas.android.com/apk/res/android" |
03 |
android:id = "@+id/gridview" |
04 |
android:layout_width = "fill_parent" |
05 |
android:layout_height = "fill_parent" |
06 |
android:numColumns = "auto_fit" |
07 |
android:verticalSpacing = "10dp" |
08 |
android:horizontalSpacing = "10dp" |
09 |
android:columnWidth = "90dp" |
10 |
android:stretchMode = "columnWidth" |
11 |
android:gravity = "center" |