Android - OnTouchListener 不工作

标签 android android-view ontouchlistener touch-event android-relativelayout

您好,我构建了一个具有根相对布局 View 的应用程序。我试图设置一个触摸监听器以在用户触摸屏幕时返回,但它似乎没有触发,我不知道我哪里出错了。我在网上搜索和查看,但据我所见,似乎每个人都使用与我相同的方法 - 我的就是行不通。
有人知道为什么吗?

  RelativeLayout relativeLayout;

  relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);

 //relative layout on touch listener
    relativeLayout.setOnTouchListener(new View.OnTouchListener(){

        @Override
        public boolean onTouch(View v, MotionEvent event) {

            //down - finger on screen
            if (event.getAction()== MotionEvent.ACTION_DOWN) {

                //store center of screen lat lon
                centerOfScreenLatLng = getScreenCenterLatLon();

                toastMsg = "down";
                toastShort();

                return true;
            }

            //up - finger off screen
            else if (event.getAction() == MotionEvent.ACTION_UP) {

                toastMsg = "up";
                toastShort();

                //get center of screen lat lon
                LatLng centerPoint = getScreenCenterLatLon();

                //if not equal then screen has been moved
                if (centerPoint != centerOfScreenLatLng){

                    //check which markers are currently in view
                    checkMarkersInView();
                }

                return true;
            }

            return false;
        }

    });


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/grey_1"
    tools:context=".MainActivity"
    android:clickable="true"
    android:focusable="true" />

最佳答案

在 xml 文件中为 relativelayout 的每个子元素放置这个:

android:clickable="false"
android:focusable="false"

关于Android - OnTouchListener 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32950365/

相关文章:

java - 向已发布的 Android 应用发送通知

android - 如何将前景属性设置为其他非 FrameLayout View

android - 无法设置 OnTouchListener

javascript - 如何在 android 7 中加载 html 之前在 webview 中注入(inject) javascript 脚本

android - Sherlock ActionBar onActivityResult 未在 Fragment 中调用

android - 如何设置cordova webview 背景,或者缓存?

Android - 用于捕获 View 属性更改的监听器(例如 android :layout_marginTop)

安卓多点触控?

android - 动态位置布局

java - 在 Android Studio 中出现错误, "Fatal signal 6 (SIGABRT), code -6 in tid 3796",我无法解决