循环显示图像的原理java
循环显示有些相似于循环链表,最后一个结点的下一个结点又是第1个结点。循环显示图像也能够模拟这一点。android
也许细心的读者从上一节实现的ImageAdapter类中会发现些什么。对!就是getView方法中的position参数和getCount方法的关系。position参数的值是不可能超过getCount方法返回的值的,也就是说,position参数值的范围是0至getCount() - 1。数组
若是这时Gallery组件正好显示到最后一个图像,position参数值正好为getCount() - 1。那么咱们如何再让Gallery显示下一个图像呢?也就是说让position参数值再增1,对!将getCount()方法的返回值也增1。app
那么这里还有一个问题,若是position参数值无限地增长,就意味着myImageIds数组要不断地增大,这样会大大消耗系统的资源。想到这,就须要解决两个问题:既要position不断地增长,又让resIds数组中保存的图像资源ID是有限的,该怎么作呢?对于getCount()方法很是好解决,能够让getCount方法返回一个很大的数,例如,*Integer.MAX_VALUE。这时position参数值就能够随着Gallery组件的图像不断向前移动而增大。如今myImageIds数组只有6个元素,若是position的值超过数组边界,要想继续循环取得数组中的元素(也就是说,当position的值是6时,取myImageIds数组的第0个元素,是6时取第1个元素)*,最简单的方法就是取余,代码以下:ide
package irdc.EX04_10; import android.app.Activity; import android.os.Bundle; import android.content.Context; import android.content.res.TypedArray; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Gallery; import android.widget.ImageView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; public class EX04_10 extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Gallery g = (Gallery) findViewById(R.id.mygallery); g.setAdapter(new ImageAdapter(this)); setTitle("Gallery 实现循环浏览图片"); g.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView parent, View v, int position, long id) { Toast.makeText(EX04_10.this, getString(R.string.my_gallery_text_pre) + position + getString(R.string.my_gallery_text_post), Toast.LENGTH_SHORT).show(); } }); } public class ImageAdapter extends BaseAdapter { int mGalleryItemBackground; private Context mContext; private int[] myImageIds = {R.drawable.photo1, R.drawable.photo2, R.drawable.photo3, R.drawable.photo4, R.drawable.photo5, R.drawable.photo6,}; public ImageAdapter(Context c) { mContext = c; TypedArray a = obtainStyledAttributes(R.styleable.Gallery); mGalleryItemBackground = a.getResourceId(R.styleable.Gallery_android_galleryItemBackground, 0); a.recycle(); } public int getCount() { //return myImageIds.length; return Integer.MAX_VALUE; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { // if (position == getCount()) // { // position = 0; // } ImageView i = new ImageView(mContext); i.setImageResource(myImageIds[position%myImageIds.length]); i.setScaleType(ImageView.ScaleType.FIT_XY); i.setLayoutParams(new Gallery.LayoutParams(136, 88)); i.setBackgroundResource(mGalleryItemBackground); return i; } } }