获取Android ListView OnItemClickListener中的点击坐标

时间:2023-01-05 21:19:17

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

比如,我有一个Android ListView我附加了一个OnItemClickListener到:

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)?

不幸的是,OnItemClickListener API似乎没有公开这些信息。是否有其他的方法来获得这个细节(不用通过实现我自己的ListView来自豪地重新发明*)?

1 个解决方案

#1


19  

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:

我也需要这么做。我在ListView上设置了OnTouchListener和OnItemClickListener。首先触发触摸侦听器,因此可以使用它设置一个变量,然后可以从onItemClick()中访问该变量。onTouch()返回false是很重要的,否则它将消耗tap。在我的例子中,我只需要X坐标:

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) {
    ...

#1


19  

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:

我也需要这么做。我在ListView上设置了OnTouchListener和OnItemClickListener。首先触发触摸侦听器,因此可以使用它设置一个变量,然后可以从onItemClick()中访问该变量。onTouch()返回false是很重要的,否则它将消耗tap。在我的例子中,我只需要X坐标:

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) {
    ...