Android - OnTouchListener不起作用

4

您好,我制作了一个应用程序,其中包含一个根RelativeLayout视图。我尝试设置一个on touch监听器来返回用户何时触摸屏幕,但似乎没有触发,我无法弄清楚哪里出错了。我已经搜索并在网上查找过,但从我所看到的来看,每个人都似乎使用与我相同的方法 - 只是我的不起作用。
有人能看出原因吗?

  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" />

是的,这个名字已经很形象地描述了 :) 但它在哪里被定义呢?我在参考资料中没有找到它,所以这应该是你自己的方法。 - Psytho
你能添加完整的 XML 吗?你在相对布局中还有其他元素吗? - Zahan Safallwa
是的,我有几个视图和一个地图片段,都在我的RelativeLayout中。 - Paul Alexander
android:focusableInTouchMode="true" - IntelliJ Amiya
1
也许问题在于另一个视图在相对布局之前消耗了触摸或点击事件,因此您的onTouchListener没有被调用。 - Palejandro
显示剩余3条评论
1个回答

6

在xml文件的RelativeLayout的每个子元素中添加此代码:

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

如果这些元素也需要可点击怎么办? - Zahan Safallwa
你可以放置两个RelativeLayout,然后在第二个RelativeLayout中放置需要被点击的View,并将其放置在正确的位置。 - saleh sereshki

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接