开发者

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 d开发者_如何学Cetail (without proudly reinventing the wheel by implementing my own ListView)?


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜