android - 片段 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
}
}
解决方案
发生的事情是您将点击侦听器设置在 上,FrameLayout
但实际上将点击发送到了,因为它覆盖了根视图 ( )GridView
的整个维度。FrameLayout
你可以
- 减小
GridView
要分派到根布局的事件的维度。 - 将您的点击侦听器设置
GridView
在事件实际发生的位置。
推荐阅读
- java - 记录来自 apache httpClient 的响应
- ios - 如何在导航栏的后退按钮中隐藏后退箭头?
- elasticsearch - 如何定期更新 ElasticSearch 索引?更新还是重建?
- python - python中“If”/“else”语句的问题
- java - 如何从一台设备触发多台设备的相同事件
- c# - eShopOnWeb 项目中的聚合是什么意思?
- javascript - 如何修复搜索框错误 ini 谷歌地图
- python - 将 PySpark DataFrame 中的每一行转换为 s3 中的文件
- ns-3 - 如何获取 NS-3 中每个数据包的接收时间?(802.11n+MIMO 示例)
- html - 如何在单独的div部分中设置复选框和标签的样式