Gallery组件实现循环显示图像

/*让Galllery循环播放的方法
* 1. 使getCount方法返回一个很大的值。建议返回Integer.MAX_VALUE,这个值可以到达20亿多。
* 2. 在getView方法中通过取余来循环取得resIds数组中的图像资源ID。
* 3.循环Gallery参考http://blog.csdn.net/herryz/article/details/6141957
*/

并修正其中的一个bug。

直接贴代码:
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;

public class App extends Activity {
	private Integer[] imgs = {
					R.drawable.photo1,
					R.drawable.photo2,
					R.drawable.photo3,
					R.drawable.photo4,
					R.drawable.photo5,
					R.drawable.photo6,
					R.drawable.photo7,
					R.drawable.photo8
					};
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Gallery g = (Gallery) findViewById(R.id.gallery);
        g.setAdapter(new ImageAdapter(this));
        g.setOnItemClickListener(new Gallery.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Log.i("tag", "position==="+position);
			}
		});
    }
    class ImageAdapter extends BaseAdapter{
    	private Context context;
    	ImageAdapter(Context context){
    		this.context=context;
    	}
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return Integer.MAX_VALUE;//返回无限多个
		}
		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return imgs[position%imgs.length];//修正!
		}
		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position%imgs.length;//修正!
		}
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
//			Log.i("tag", "position=="+getItemId(position));
			ImageView iv = new ImageView(context);
			iv.setImageResource(imgs[position%imgs.length]);//取余
			iv.setScaleType(ImageView.ScaleType.CENTER);
			iv.setLayoutParams(new Gallery.LayoutParams(150, 100));
			return iv;
		}
    }
}


viewpager实现循环滑动(向右)
http://www.eoeandroid.com/thread-164918-1-1.html

让Android自带的Gallery实现多点缩放,拖动和边界回弹效果,效果流畅
http://www.havenliu.com/android/668.html

你可能感兴趣的:(android,galllery)