【问题标题】:Android on touch listener inside an item click listener项目点击侦听器内的 Android on touch 侦听器
【发布时间】:2021-01-21 11:36:28
【问题描述】:

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

 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 元素,我认为这是因为我第一次单击列表项元素时,它会注册 OnTouchListener,然后,如果我再次点击它就会启动。

如何解决这种奇怪的行为,以便一键触发 on touch 监听器?

【问题讨论】:

    标签: android android-listview touch-event ontouchlistener onitemclicklistener


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-16
      • 1970-01-01
      相关资源
      最近更新 更多