4

I'm trying to get the item selected when i touch a gridview, i cant use the onClick as that starts another activity. What I'm trying to achieve is to be able to move items in a gridview around and since i cant find a way of doing it I'm trying to make a way..

So yeah.. Is there a way to get which item has been 'touched', I've tried using a Rect and it hasn't worked properly..

(Can i just elaborate.. i Cant use the onItemClick for this..)

Any help would be great, Thank you! :)

Tom O
  • 1,780
  • 2
  • 20
  • 43
  • 1
    I'm a bit confused. You want to determine which item has been clicked so you can move it, but you can't use the method that's called when an item is clicked because a new Activity is launched? If you want a feature such as is used on Android homescreens, you could look into the onLongClickListener(). – Glendon Trullinger Jun 20 '11 at 23:01
  • Hello Thomas, Can you please share some code snippet as I have to solve similar kind of problem where I want to arrange the images of a grid from one cell to another. – Chandra Sekhar Feb 16 '12 at 14:00

2 Answers2

19

To get the item that was 'touched'

gridView.setOnTouchListener(new OnTouchListener() {
        public boolean onTouch(View v, MotionEvent me) {

            int action = me.getActionMasked();  // MotionEvent types such as ACTION_UP, ACTION_DOWN
            float currentXPosition = me.getX();
            float currentYPosition = me.getY();
            int position = gridView.pointToPosition((int) currentXPosition, (int) currentYPosition);

            // Access text in the cell, or the object itself
            String s = (String) gridView.getItemAtPosition(position);
            TextView tv = (TextView) gridView.getChildAt(position);
    }
}
PS376
  • 539
  • 8
  • 13
  • 3
    It's not simple nor elegant. gridView.getChildAt(position) will return null because the GridView reuses it's elements, like ListView does with the rows. – bogdan Sep 30 '14 at 10:14
6

If Glendon Trullinger's suggestion of using onLongClickListener isn't sufficient for you, try GridView#pointToPosition(int x, int y), which you can call from a View.OnTouchListener, using the MotionEvent's x and y coordinates. With that position, you can get the child view at that position using this answer, and/or you can get the adapter item itself using AdapterView#getItemAtPosition(int)

Community
  • 1
  • 1
Joe
  • 42,036
  • 13
  • 45
  • 61