[英]How to implement an endless gallery in Android?
我在我的應用程序中使用了庫布局。 當用戶從左到右移動圖庫中的圖片時它正在工作(它是無限的,意味着元素再次重復)。 但是當用戶從右向左移動並到達第一個元素時,它不會。 之后就沒有元素了。 但是我也要重復這一方面的要素。 你能給我一些建議嗎?
Gallery g = (Gallery) findViewById(R.id.gallery);
g.setAdapter(new ImageAdapter(this));
g.setFocusable(true);
g.setSelection((int)(Integer.MAX_VALUE / 2) - (Integer.MAX_VALUE / 2)% mImageIds.length);
g.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
try {
imageid=position;
((ImageView)findViewById(R.id.ImageViewlarge)).setImageResource(mImageIds[position]);
((TextView)findViewById(R.id.TextViewImageName)).setText(imgNames[position]);
mp = MediaPlayer.create(SeaSpell.this,audioTrack[position]);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
如何讓我的畫廊視圖循環? 我能夠無限地從左到右進行,但是當我從右向左拖動時,它顯示了終點。
在getView中:
if(position>21){
position=0;
}
這應該被刪除,因為它應該由checkPosition函數處理。
在checkPosition中:
對於模數運算符( %
),給定a % b
如果0 <= a < b
則結果為a
。 對於b <= a < 2*b
則結果將為ab
,因此如果b == a
,則結果為0
。 對於任何正整數,這都會繼續,因此檢查應該是:
if (position > 0)
position = position % mImageIds.length;
現在,你在這里缺少的是處理position < 0
的情況。
a a%3 a a%3 f(a)
0 0 0 0 0
1 1 -1 -1 2
2 2 -2 -2 1
3 0 -3 0 0
4 1 -4 -1 2
5 2 -5 -2 1
6 0 -6 0 0
在這種情況下我們想要的是它回繞到列表的末尾 - 上表中的f(a)
。
從上表中可以看出,如果a
為負,則-b < a <= 0
。 此外,如果我們使f(a) = (a % b) + b
我們得到我們想要的結果。
這意味着checkPosition中的邏輯變為:
position = position % mImageIds.length;
if (position < 0)
position = position + mImageIds.length;
這應該適用於所有position
值,而不管mImageIds.length
的值。
如果有人想讓它也倒退,你可以實現這一點。 所有這一切真的是在中間開始畫廊。
GalleryName.setSelection((int)( Integer.MAX_VALUE / 2 ) - ( Integer.MAX_VALUE / 2 ) % mImageIds.length);
reece解釋的適配器代碼可以在這里找到: android圓形圖庫?
只需確保使用gogothee的建議將初始選擇移動到范圍的中點。 (這樣你幾乎可以永遠向左和向右滾動)。 例如,我這樣做:
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mylayout);
//get references to UI components
mGallery = (Gallery) findViewById(R.id.filter_gallery);
//connect Galleries with adapters
mGallery.setAdapter(new GalleryAdapter(this));
//auto-select first image (position 1073741820)
mGallery.setSelection((int)(Integer.MAX_VALUE/2) - ( (Integer.MAX_VALUE/2) % mImageBuffer.getCount() ) );
}
要將第一個元素作為可用數組的中心:
your_gallery_obj.setSelection((int)(Integer.MAX_VALUE / 2) - (Integer.MAX_VALUE / 2)%your_array_size);
要將中間元素作為可用數組的中心:
your_gallery_obj.setSelection((int)(Integer.MAX_VALUE / 2)+(Integer.MAX_VALUE / 2)%your_array_size);
一個無恥的自我插件,只寫了一個無限滾動畫廊教程:
http://blog.blundell-apps.com/infinite-scrolling-gallery/
我使用與@reece相同的modulas數學,也可以下載源代碼。
您可以使用SD卡上的圖像或/ resources / drawable目錄中的圖像
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.