首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Android on touch listener在项目内单击listener

Android on touch listener在项目内单击listener
EN

Stack Overflow用户
提问于 2020-10-06 22:53:12
回答 1查看 45关注 0票数 0

我有一个带有项目的列表视图,每次我点击一个列表项目时,我都需要知道我触摸到的是屏幕的左侧还是右侧。为了实现这一点,我编写了以下代码:

代码语言:javascript
复制
 testListView.setOnItemClickListener(((parent, view, position, id) -> {

        view.setOnTouchListener(new View.OnTouchListener() {
            private long startClickTime = 0;
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {

                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {

                    startClickTime = System.currentTimeMillis();

                } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {

                    if (System.currentTimeMillis() - startClickTime < ViewConfiguration.getTapTimeout()) {

                        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
                        float dpWidth = displayMetrics.widthPixels / displayMetrics.density;
                        float leftPersentage = (dpWidth) * 100 / 100;
                        int x = (int) motionEvent.getX();
                        if (x < leftPersentage) {
                            Toast.makeText(context,"I have touched the left side of screen",Toast.LENGTH_SHORT);
                        } else {
                            Toast.makeText(context,"I have touched the right side of screen",Toast.LENGTH_SHORT);
                        }
                    }
                }
                return true;
            }
        });
    }));

这是可行的,但是为了让Toast出现,我需要按两次List元素,我认为这是因为我第一次单击list item元素时,它会注册OnTouchListener,然后,如果我再次单击,它就会触发。

我如何修复这种奇怪的行为,以便只需单击一次即可触发on touch侦听器?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-06 23:21:31

您需要在getView函数上的ListView适配器上设置setOnTouchListener,而不是在setOnItemClickListener上。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64228349

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档