android gallery no scroll on click
By default it seems, when a gallery 开发者_高级运维item is clicked, the gallery automatically scrolls to center the item that was clicked. How can I override this behavior? I do not want the gallery to scroll to center when clicked, I want it to stay where it is.
I think this is a correct solution:
@Override
public boolean onSingleTapUp(final MotionEvent e) {
boolean handled = super.onSingleTapUp(e);
onDown(e);
return handled;
}
I think this is what you are looking for.
First create a class that extends from Gallery and then override the onSingleTapUp method:
@Override
public boolean onSingleTapUp(final MotionEvent e) {
final OnItemClickListener listener = getOnItemClickListener();
final View selectedView = getSelectedView();
final float tapX = e.getRawX();
final float tapY = e.getRawY();
if ((selectedView != null) && (listener != null)
&& (tapX >= selectedView.getLeft()) && (tapX <= selectedView.getRight())
&& (tapY >= selectedView.getTop()) && (tapY <= selectedView.getBottom())) {
final int selectedPosition = getSelectedItemPosition();
listener.onItemClick(this, selectedView, selectedPosition, selectedPosition);
}
return true;
}
I never used a gallery before (actually i had to watch a youtube view to see it's visual effect first ;-)
So i digged in the source code of gallery and it seems to me that they have tied the selection quite heavy to the positioning, so you would have to override the class and do some heavy code hacking, maybe even reflection, to reach your goal. I can't even tell whether you would succeed.
This is not a solution, but a hint what you should expect if you want to realize that ;-)
Gallery has a method to override this.
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
Toast.makeText(HelloGallery.this, "" + position, Toast.LENGTH_SHORT).show();
}
});
}
I haven't tried this... but you can try the following:
In the onItemClickListener.onItemClick()
, determine the currently selected position using Gallery.getSelectedItemPosition()
and then set the position using Gallery.setSelection(int position)
. I don't know if this will work or not but you can give it a shot.
There is also the OnItemSelectedListener
which you could try leveraging.
Unfortunately I don't seem to have the ability to comment on others' posts yet, but for any who found this question but was having issues, note that if you are creating a custom gallery that overrides the onSingleTap
method (as suggested by Ohgema), you need to override the constructor that takes a Context
and an AttributeSet
.
精彩评论