这个控件在android 4.1以后不建议使用,替代UI为ViewPager,下面给出一个网友的事例:
另外为gallery添加一个资源文件:
实现代码:
package com.example.androidgallerydemotest;import android.os.Bundle;import android.app.Activity;import android.content.Context;import android.content.res.TypedArray;import android.view.Menu;import android.view.View;import android.view.ViewGroup;import android.widget.AdapterView;import android.widget.AdapterView.OnItemClickListener;import android.widget.BaseAdapter;import android.widget.Gallery;import android.widget.ImageView;public class MainActivity extends Activity { private int[] imagesIDs = new int[] { R.drawable.bmp1, R.drawable.bmp2, R.drawable.bmp3, R.drawable.bmp4, R.drawable.bmp5, R.drawable.bmp6, R.drawable.bmp7, R.drawable.bmp8, R.drawable.bmp9, R.drawable.bmp10 }; @SuppressWarnings("deprecation") private Gallery gallery; private ImageView image; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); gallery = (Gallery) findViewById(R.id.gallery1); image = (ImageView) findViewById(R.id.image1); gallery.setAdapter(new ImageAdapter(MainActivity.this)); gallery.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { image.setImageResource(imagesIDs[position]); } }); } // 声明一个BaseAdapter public class ImageAdapter extends BaseAdapter { // 使用Adapter的上下文变量 Context context; // 背景样式的Id int itemBackground; public ImageAdapter(Context c) { // 在构造函数中传递需要使用这个Adapter的上下文变量 context = c; // 通过XML资源中定义的样式,设定背景 TypedArray a = obtainStyledAttributes(R.styleable.Gallery1); itemBackground = a.getResourceId( R.styleable.Gallery1_android_galleryItemBackground, 0); a.recycle(); } @Override public int getCount() { // 返回当前数据集中数据的个数 return imagesIDs.length; } @Override public Object getItem(int position) { // 返回数据集中,当前position位置的数据 return imagesIDs[position]; } @Override public long getItemId(int position) { // 返回数据集中,当前position位置的数据的Id return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // 返回当前position位置的视图 ImageView imageview; if (convertView == null) { // 通过数据上下文对象声明一个ImageView,并设置相关属性 imageview = new ImageView(context); imageview.setImageResource(imagesIDs[position]); imageview.setScaleType(ImageView.ScaleType.FIT_XY); imageview.setLayoutParams(new Gallery.LayoutParams(150, 120)); } else { imageview = (ImageView) convertView; } // 使用XML 中定义的样式为待显示的View设定背景样式 imageview.setBackgroundResource(itemBackground); return imageview; } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; }}
运行效果: