重复画廊元素

时间:2010-07-30 08:53:03

标签: android

嗨我想重复显示gallary元素。这意味着当我向前或向后移动时,不需要结束gallary图像。如果我采用23个elemets数组将图像分配给gallary,那么当我移动时,这些图像会再次重复为了这个,请给我一些建议。谢谢。

2 个答案:

答案 0 :(得分: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;
    }
}

}

答案 1 :(得分:1)

下面的代码是圆形GalleryView的非常好的例子。

https://stackoverflow.com/a/3370421/741588