【Android】Fragment中监听Backpress返回键

需求

在Fragment中监听返回键,并结束Activity

问题

Fragment未提供监听返回键的方法

思路

可以给Fragment中的RootView添加KeyListener

但是RootView默认是无法获取按键焦点的,所以即使添加了KeyListener也无效

我们只要允许Fragment的RootView获得焦点,并获得焦点,再添加KeyListener即可

代码
kotlin 复制代码
binding.root.isFocusableInTouchMode = true
binding.root.requestFocus()
binding.root.setOnKeyListener { v, keyCode, event ->
	if (keyCode == KeyEvent.KEYCODE_BACK) {
			requireActivity().finish()
			return@setOnKeyListener true
	}
	return@setOnKeyListener false
}
相关推荐
符哥200810 小时前
新能源智能充电桩与 Android/iOS App 蓝牙通信协议
android·ios
JMchen12310 小时前
自定义View性能优化:从60fps到120fps的进阶之路
android·经验分享·性能优化·kotlin·自定义view
vistaup11 小时前
DevEco Studio 鸿蒙 HAR本地引入相互依赖问题解决
android·华为·harmonyos
常利兵11 小时前
Android 开发秘籍:用Tint为Icon动态变色
android
奔跑吧 android12 小时前
【车载audio】【CarAudioService 05】【车载 Android 系统调试深度指南:解析 dumpsys car_service】
android·audio·audioflinger·aosp15·车载音频·车载audio·car_service
shuangrenlong12 小时前
androidstudio gradle文件报红
android
Digitally12 小时前
如何通过蓝牙将 iPhone 上的照片传输到 Android
android·ios·iphone
常利兵12 小时前
Android Intent.setAction失效报错排查与修复全方案
android
低调小一12 小时前
RecyclerView 缓存与复用机制:从一次滑动讲明白(2026 版)
android·recyclerview
耶叶12 小时前
kotlin的修饰符
android·开发语言·kotlin