繁体   English   中英

如何与onitemclick侦听器一起使用ontouchevent()?

[英]How to use ontouchevent() with onitemclick Listener?

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

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

首先,我重写了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秒)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM