Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtaining click coordinates in Android ListView OnItemClickListener

Let's say, I have an Android ListView that I attached an OnItemClickListener to:

ListView listView = (ListView) findViewById(...);
listView.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        [...]

When a certain item in the view is clicked, I can figure out the corresponding rectangle by getting the view's dimensions. However, I would like to get the corresponding coordinates even more precisely to identify the point on the screen that the user actually clicked.

Unfortunately, the OnItemClickListener API does not seem to expose this information. Are there any alternative ways of getting hold of this detail (without proudly reinventing the wheel by implementing my own ListView)?

like image 733
Thilo-Alexander Ginkel Avatar asked Jul 04 '11 23:07

Thilo-Alexander Ginkel


1 Answers

I needed to do this also. I set an OnTouchListener and an OnItemClickListener on the ListView. The touch listener is fired first, so you can use it to set a variable which you can then access from your onItemClick(). It's important that your onTouch() returns false, otherwise it will consume the tap. In my case, I only needed the X coordinate:

private int touchPositionX;

...

getListView().setOnTouchListener(new OnTouchListener() {
  public boolean onTouch(View view, MotionEvent event) {
    touchPositionX = (int)event.getX();
    return false;
  }
});

getListView().setOnItemClickListener(new OnItemClickListener() {
  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    if (touchPositionX < 100) {
    ...
like image 188
Chris Seatory Avatar answered Nov 02 '22 11:11

Chris Seatory