2012-05-29 50 views
2

我正在尝试为网格视图制作水平滚动视图。我成功进入了水平滚动视图。但是现在我需要为相同的网格视图实现onItemClickListener。我使用GestureDetector.SimpleOnGestureListener和onTouchEvent进行水平滚动。如果我使用onItemClickListener不起作用。有人帮助我同时工作。提前致谢。如何在onitemclick监听器上使用ontouchevent()?

回答

1

我最近不得不面对同样的问题,这就是我解决它的方法。

首先,我重写ListFragment/ListActivity中的默认onListItemClick侦听器。然后在onTouchEvent方法中,我设置了一个条件,如果为true,则调用ListView的onListItemClick。当动作等于MotionEvent.ACTION_UP并且条件满足时执行此呼叫。您必须先决定哪些事件构成您的视图的点击。我宣布我为ACTION_DOWN,紧接着是ACTION_UP。当您准备好执行onListItemClick时,您必须将实际项目的视图,位置和ID传递给方法。

看到我下面的例子。

Class....{ 
    private boolean clickDetected = true; 

    public boolean onTouchEvent(MotionEvent ev) { 
     final int action = ev.getAction(); 
     final int x = (int) ev.getX(); 
     final int y = (int) ev.getY(); 

     //if an action other than ACTION_UP and ACTION_DOWN was performed 
     //then we are no longer in a simple item click event group 
     //(i.e DOWN followed immediately by UP) 
     if (action != MotionEvent.ACTION_UP 
       && action != MotionEvent.ACTION_DOWN) 
      clickDetected = false; 

     if (action == MotionEvent.ACTION_UP){ 
      //check if the onItemClick requirement was met 
      if (clickDetected){ 
       //get the item and necessary data to perform onItemClick 
       //subtract the first visible item's position from the current item's position 
       //to compensate for the list been scrolled since pointToPosition does not consider it 
       int position = pointToPosition(x,y) - getFirstVisiblePosition(); 
       View view = getChildAt(position); 
       if (view != null){//only continue if a valid view exists 
        long id = view.getId(); 
        performItemClick(view, position, id);//pass control back to fragment/activity 
       }//end if 
      }//end if 

      clickDetected= true;//set this to true to refresh for next event 
     }//end if 
     return super.onTouchEvent(ev); 
     .... 
    }//end onTouchEvent 
}//end class 

这种设置允许更大的灵活性,例如,如果你想建立一个长期点击你可以做同样的上方,简单的检查了ACTION_DOWN和ACTION_UP之间的时间差。

另一种方法是获取启动该操作的项目的位置,并针对该操作检查该操作的位置,甚至针对向下和向上操作(例如小于1秒)输入时间差异标准, 。

+0

好的意见,这是我登录的东西。无论如何,我想提一下,这对于一些低成本设备无效。我注意到不久前,在测试我的新应用程序时,在三星,asus,千兆以太网(以及其他常见设备)上查看注册的ACTION_DOWN,随后立即通过ACTION_UP操作,在低成本设备上按ACTION_DOWN - > ACTION_MOVE - > ACTION_UP进行查看。 – vanomart