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() {@Overridepublic void onItemClick(AdapterView<?> parent, View view,int position, long id) {// TODO Auto-generated method stubLog.i("tag", "position==="+position);}}); } class ImageAdapter extends BaseAdapter{ private Context context; ImageAdapter(Context context){ this.context=context; }@Overridepublic int getCount() {// TODO Auto-generated method stubreturn Integer.MAX_VALUE;//返回无限多个}@Overridepublic Object getItem(int position) {// TODO Auto-generated method stubreturn imgs[position%imgs.length];//修正!}@Overridepublic long getItemId(int position) {// TODO Auto-generated method stubreturn position%imgs.length;//修正!}@Overridepublic 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;} }}