首先写布局文件,这个很简单
<?xml version="1.0" encoding="utf-8"?>
<Gallery xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gallery"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</Gallery>
然后写Gallery的适配器,继承BaseAdapter
package wanxian.gallery;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery.LayoutParams;
import android.widget.ImageView;
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private Integer[] mImageIds={
R.drawable.camera,
R.drawable.computer,
R.drawable.excel,
R.drawable.outlook,
R.drawable.power_point,
R.drawable.radio,
R.drawable.tv,
R.drawable.word
};
public ImageAdapter(Context c){
this.mContext=c;
}
@Override
public int getCount() {
return mImageIds.length;
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView=new ImageView(mContext);
imageView.setImageResource(mImageIds[position]);
imageView.setLayoutParams(new LayoutParams(120, 120));//这个地方要注意
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
return imageView;
}
}
最后写Acitivity
package wanxian.gallery;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Gallery;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Gallery gallery=(Gallery) findViewById(R.id.gallery);
gallery.setAdapter(new ImageAdapter(MainActivity.this));
gallery.setBackgroundResource(R.drawable.bg);
gallery.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "你选择了"+(position+1)+"号图片", 0).show();
}
});
}
}