I have a gridview
that contains some items. I want to get the screen related coordinates when touching any item in the grid.
I know I can do that using MotionEvent.getRawX
and MotionEvent.getRawY
. The problem is that I cannot set the touch listener on the item inside the grid, it doesn't fire, I don't know why. I've tried to set the listener for the gridview itself, this works, but once I touch any item the callback gets called more than once (2-4 times). Here is my code:
public class Calibration extends Activity {
List<String> list;
GridView grid;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calibration_activity);
list = new ArrayList<String>();
grid = (GridView) findViewById(R.id.gridView1);
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
list.add("6");
list.add("7");
list.add("8");
list.add("9");
ArrayAdapter<String> adp = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, list);
grid.setAdapter(adp);
/*Working but appears 2-4 times*/
grid.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
Toast.makeText(getBaseContext(), "( " + motionEvent.getRawX() + ", " + motionEvent.getRawY() + ")",
Toast.LENGTH_LONG).show();
return false;
}
});
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="auto_fit"
android:background="#7CFC00"
android:gravity="center"
android:columnWidth="100dp"
android:stretchMode="columnWidth" />
Notice that my aim is to have ImageView
inside the gridView
not string values. I tried having the ImageView filled in the adapter, then setting the listener on it, but that didn't work. So, I'm just using String values as an example for this question.
How can I solve this problem?
Update your onTouch method to show the toast only when user's finger left the the gridview (ACTION_UP)
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if(motionEvent.getAction() == KeyEvent.ACTION_UP) {
Toast.makeText(getBaseContext(), "( " + motionEvent.getRawX() + ", " + motionEvent.getRawY() + ")",
Toast.LENGTH_LONG).show();
return true;
}
else
return false;
}
You can try to check other KeyEvent conditions such as ACTION_DOWN. This is up to you
Doc is HERE
ACTION_DOWN
-> the key has been pressed down.
ACTION_MULTIPLE
-> you are pressing and sliding thru the screen (this event is sent until user release the screen)
ACTION_UP
-> the key has been released.