2

我正在尝试为网格视图制作水平滚动视图。我成功地使用了水平滚动视图。但现在我也需要为同一个网格视图实现 onItemClickListener 。我使用 GestureDetector.SimpleOnGestureListener 和 onTouchEvent 进行水平滚动。如果我使用这个 onItemClickListener 不起作用。骗子有人帮我让两者都工作。提前致谢。

4

1 回答 1

1

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

首先,我覆盖onListItemClickListFragment/ListActivity 中的默认侦听器。然后在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 秒)。

于 2014-08-03T02:54:01.553 回答