2010-07-30 70 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