2010-07-30 112 views
1

嗨我想重复显示画廊元素。这意味着当我向前或向后移动时,不需要画廊图像结束。如果我采用23个元素数组将图像分配到画廊然后再次显示图像重复当我向前或向后gallary.For此人请给我一些建议。预先感谢重复画廊元素

回答

6

这是非常相似的this question。您需要在getView()方法中创建一个条件,在该条件中检查您是否位于最后一个元素,然后在第一次在getCount中使用模数重新启动。

编辑 这可能是你可以重用一个例子:

public class TestGallery extends Activity { 
private Integer[] mImageIds = { R.drawable.sample_1, R.drawable.sample_2, R.drawable.sample_3, R.drawable.sample_4 }; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.gallery); 

    Gallery g = (Gallery) findViewById(R.id.gallery); 
    g.setAdapter(new ImageAdapter(this)); 

    g.setOnItemClickListener(new OnItemClickListener() { 
     public void onItemClick(AdapterView parent, View v, int position, long id) { 
      if (position >= mImageIds.length) { 
       position = position % mImageIds.length; 
      } 
      Toast.makeText(TestGallery.this, "" + position, Toast.LENGTH_SHORT).show(); 
     } 
    }); 
} 

public class ImageAdapter extends BaseAdapter { 
    int mGalleryItemBackground; 
    private Context mContext; 

    public ImageAdapter(Context c) { 
     mContext = c; 
     TypedArray a = obtainStyledAttributes(R.styleable.default_gallery); 
     mGalleryItemBackground = a.getResourceId(R.styleable.default_gallery_android_galleryItemBackground, 0); 

     a.recycle(); 
    } 

    public int getCount() { 
     return Integer.MAX_VALUE; 
    } 

    public Object getItem(int position) { 
     if (position >= mImageIds.length) { 
      position = position % mImageIds.length; 
     } 
     return position; 
    } 

    public long getItemId(int position) { 
     if (position >= mImageIds.length) { 
      position = position % mImageIds.length; 
     } 
     return position; 
    } 

    public View getView(int position, View convertView, ViewGroup parent) { 
     ImageView i = new ImageView(mContext); 
     if (position >= mImageIds.length) { 
      position = position % mImageIds.length; 
     } 
     i.setImageResource(mImageIds[position]); 
     i.setLayoutParams(new Gallery.LayoutParams(80, 80)); 
     i.setScaleType(ImageView.ScaleType.FIT_XY); 
     i.setBackgroundResource(mGalleryItemBackground); 
     return i; 
    } 

    public int checkPosition(int position) { 
     if (position >= mImageIds.length) { 
      position = position % mImageIds.length; 
     } 
     return position; 
    } 
} 

}

+0

对不起,我忘记了一件事,然后再复制给你。在“checkPosition(position);”之前添加“position =”在getView – Sephy 2010-07-30 12:23:58

+0

我纠正了上面的示例,使其中的一切工作。 – Sephy 2010-07-30 12:27:24

+0

看起来你的getItem方法有错误。 – Zammbi 2012-06-12 23:51:34