【问题标题】:Android - OnTouchListener not workingAndroid - OnTouchListener 不工作
【发布时间】:2016-01-02 05:07:49
【问题描述】:

您好,我已经构建了一个具有根 relativelayout 视图的应用程序。我试图设置一个触摸监听器,以便在用户触摸屏幕时返回,但它似乎没有触发,我不知道我哪里出错了。我已经在网上搜索并查看了,但从我所看到的情况来看,每个人似乎都使用与我相同的方法 - 我的方法不起作用。
谁能明白为什么?

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

【问题讨论】:

  • 什么是toastShort()
  • 只是一种在屏幕上显示敬酒消息的方法
  • 是的,这个名字是自描述的 :) 但它是在哪里定义的?我没有在参考中找到它,所以这是你自己的方法。
  • 是的,这是我自己的方法,我知道我的 toast 方法有效,因为我之前在其余代码中使用过很多次:/
  • 也许问题是另一个视图在你的onTouchListener的relativeLayout之前消耗了触摸或点击事件,所以onTouch根本没有被调用。

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


【解决方案1】:

把这个为relativelayout的每个孩子放在xml文件中:

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

【讨论】:

  • 如果元素也需要可点击怎么办?
  • 你可以放两个相对布局,然后你把你想点击的视图放在第二个相对布局中,放在正确的位置
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-06
  • 1970-01-01
相关资源
最近更新 更多