Android How to get position of selected item from gridview without using onclicklistner, using ontouchlistner instead
- by zonemikel
I have a gridview, I need to do stuff on motioneven.action_down and do something for motioneven.action_up ... using onclicklistener is great but does not give me this needed functionality.
Is there anyway to easily call the gridview and get its selected item in a ontouchlistener ? I've been having limited success with making my own implementation. Its hard to get the right x,y because if i call the child it gives me the x and y relative to the child so a button would be 0,0 to 48,48 but it does not tell you the actual location on the screen relative to the gridview or the screen itself.
this is what i've been doing, its partially working so far.
Grid.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
int x = (int)event.getX();
int y = (int)event.getY();
int position = 0;
int childCount = Grid.getChildCount();
Message msg = new Message();
Rect ButtonRect = new Rect();
Grid.getChildAt(0).getDrawingRect(ButtonRect);
int InitialLeft = ButtonRect.left + 10;
ButtonRect.offsetTo(InitialLeft, ButtonRect.top);
//
while(position < childCount){
if(ButtonRect.contains(x,y)){break;}
if(ButtonRect.right + ButtonRect.width() > Grid.getWidth())
{ ButtonRect.offsetTo(InitialLeft, ButtonRect.bottom);}
position++;
ButtonRect.offsetTo(ButtonRect.right, ButtonRect.top);
}
msg.what = position;
msg.arg1 = ButtonRect.bottom;
msg.arg2 = y;
cHandler.sendMessage(msg);
}// end if action up
if (event.getAction() == MotionEvent.ACTION_UP) {
}
return false;
}
});