【问题标题】:How to know if user tap on the screen如何知道用户是否点击屏幕
【发布时间】:2019-11-22 08:00:56
【问题描述】:

当我点击按钮应用程序启动smaller view 时,如果用户点击屏幕上除打开视图之外的任何位置,我需要关闭它。

我尝试将TouchListener 添加到我的父布局中,但它没有检测到父布局上的点击或触摸事件。

    <androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/home_bg"
            android:animateLayoutChanges="true"
            android:id="@+id/activity_profile"
            android:clickable="true"
            android:focusable="true"
            >

            <!-- VIEWS -->

 </androidx.coordinatorlayout.widget.CoordinatorLayout>

在我的活动中,我编写了以下代码,但这不起作用。

activity_profile.setOnTouchListener(object : View.OnTouchListener {
            override fun onTouch(v: View?, event: MotionEvent?): Boolean {
                when (event?.action) {
                    MotionEvent.ACTION_DOWN -> {
                        layoutContextual.visibility = View.GONE
                    }
                }

                return v?.onTouchEvent(event) ?: true
            }
        })

【问题讨论】:

    标签: android android-layout android-fragments android-view


    【解决方案1】:

    在父布局的 CoordinatorLayout id 上调用 setOnClickListener

    activity_profile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // put your code here
    
    
            }
        });
    

    或者

    你可以使用 onTouchEvent()

    @Override
     public boolean onTouchEvent(MotionEvent event) {
        // put your code here
     }
    

    【讨论】:

      【解决方案2】:

      对话框是你试图实现的东西。

      https://developer.android.com/guide/topics/ui/dialogs https://developer.android.com/reference/android/app/DialogFragment

      您可以使用带或不带标题的自定义视图,使其符合您的期望。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-29
        • 1970-01-01
        相关资源
        最近更新 更多