首页 > 解决方案 > 片段 setOnTouchListener 未触发

问题描述

我有以下 kotlin 代码,但无法调用 onTouch\click 侦听器。我正在使用模拟器,我在很多地方多次单击该片段,但似乎没有任何东西让听众打电话。我放了断点并打印\日志,却一无所获......

gridview 有一个 onItemClick。如果我删除了gridview - 触摸监听器工作,但我确实需要gridview 和onItemClick。那么如何将两者结合起来呢?

片段 xml:

    <?xml version="1.0" encoding="utf-8"?>
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clickable="true"
    android:focusable="true"
    tools:context=".fragments.MainAppFragment">

        <GridView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:columnWidth="150dp"
        android:id="@+id/my_grid_view"
        android:horizontalSpacing="15dp"
        android:numColumns="auto_fit"
        android:verticalSpacing="15dp"
        />
</FrameLayout>

片段类:

    class MainAppFragment : Fragment(){

        override fun onCreateView(
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {
          val view = inflater.inflate(R.layout.fragment_main_app, container, false)

          view.setOnClickListener {
            Log.d("TAG", "onTouch entered");
          }
          view.setOnTouchListener { v, event ->
            print(event.action)
            true
          }

          return view
    }
}

标签: androidkotlintouch-eventontouchlistener

解决方案


发生的事情是您将点击侦听器设置在 上,FrameLayout但实际上将点击发送到了,因为它覆盖了根视图 ( )GridView的整个维度。FrameLayout

你可以

  1. 减小GridView要分派到根布局的事件的维度。
  2. 将您的点击侦听器设置GridView在事件实际发生的位置。

推荐阅读