Android 为多个 ImageView 触发 onTouch 事件

Android firing onTouch event for multiple ImageViews(Android 为多个 ImageView 触发 onTouch 事件)
本文介绍了Android 为多个 ImageView 触发 onTouch 事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个 ImageView,当我在多个图像上拖动手指时,我希望为每个 ImageView 触发 onTouch 事件.目前 onTouch 事件仅在第一个 ImageView 上触发(或实际上在多个 ImageView 上但仅在多点触摸屏幕时触发).伪代码:

I have several ImageViews, and I want the onTouch event to fire for each of them when I drag my finger across multiple images. At present the onTouch event is only firing on the first ImageView (or actually on multiple ImageViews but only when multitouching the screen). Pseudo code:

            for(int i=0;i<5;i++){
              ImageView img=new ImageView(this);
              LinearLayout.LayoutParams layoutParams=new LinearLayout.LayoutParams(width,height);
              img.setImageResource(R.drawable.cell);
              img.setOnTouchListener(this);
              mainLayout.addView(img,layoutParams);
            }
            ...

            public boolean onTouch (View v, MotionEvent event){
              Log.d("MY_APP","View: " + v.getId());
              return false;
            }

我是不是完全找错树了?

Am I barking up completely the wrong tree?

感谢您的帮助.

推荐答案

我认为您需要使用移动事件而不是触摸事件并将getX和getY与您的视图位置进行比较.

I think you need to use move event rather than touch event and compare getX and getY with the location of your views.

     @Override
    public boolean onTouchEvent(MotionEvent ev) {

        final int action = ev.getAction();

        switch (action) {

            // MotionEvent class constant signifying a finger-down event

            case MotionEvent.ACTION_DOWN: {
                break;
            }

            // MotionEvent class constant signifying a finger-drag event  

            case MotionEvent.ACTION_MOVE: {

                    X = ev.getX();
                    Y = ev.getY();
                    //compare here using a loop of your views
                    break;

            }

            // MotionEvent class constant signifying a finger-up event

            case MotionEvent.ACTION_UP:

                break;

        }
        return true;
    }

这篇关于Android 为多个 ImageView 触发 onTouch 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How to target newer versions in .gitlab-ci.yml using auto devops (java 11 instead of 8 and Android 31 instead of 29)(如何在.gitlab-ci.yml中使用自动开发工具(Java 11而不是8,Android 31而不是29)瞄准较新的版本)
Android + coreLibraryDesugaring: which Java 11 APIs can I expect to work?(Android+core LibraryDesugering:我可以期待哪些Java 11API能够工作?)
How to render something in an if statement React Native(如何在If语句中呈现某些内容Reaction Native)
How can I sync two flatList scroll position in react native(如何在本机Reaction中同步两个平面列表滚动位置)
Using Firebase Firestore in offline only mode(在仅脱机模式下使用Firebase FiRestore)
Crash on Google Play Pre-Launch Report: java.lang.NoSuchMethodError(Google Play发布前崩溃报告:java.lang.NoSuchMethodError)