I am using a gallery layout in my application. It is working when the user moves the pictures in the gallery from left to right (it is infinite that means elements are repeated again). But when the user moves from right to left and reaches the first element, it doesn't. After then no elements are coming. But I want to repeat elements from this side also. Can you give me some suggestions?
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();
}
}
});
}
How can I make my gallery view circular? I am able to do it from left to right infinitely, but when I drag from right to left it is showing the end point.
In getView:
if(position>21){
position=0;
}
this should be removed as it should be handled by the checkPosition function.
In checkPosition:
For the modulus operator (%
), given a % b
if 0 <= a < b
then the result will be a
. For b <= a < 2*b
then the result will be a-b
, so if b == a
, then the result is 0
. This continues for any positive integer, so the check should be:
if (position > 0)
position = position % mImageIds.length;
Now, what you are missing from this is handling the case where 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
What we want in this case is for it to wrap back around to the end of the list -- the f(a)
in the table above.
As can be seen in the table above, if a
is negative then -b < a <= 0
. Also, if we make f(a) = (a % b) + b
we get our desired result.
This means that the logic in checkPosition becomes:
position = position % mImageIds.length;
if (position < 0)
position = position + mImageIds.length;
which should work for all values of position
irrespective of the value of mImageIds.length
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With