【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
}
相关推荐
hmywillstronger27 分钟前
【Excel】【VBA】根据内容调整打印区域
android·excel
coooliang1 小时前
【Android】ViewPager的使用
android
xvch3 小时前
Kotlin 2.1.0 入门教程(二十五)类型擦除
android·kotlin
kidding7238 小时前
前端VUE3的面试题
前端·typescript·compositionapi·fragment·teleport·suspense
simplepeng12 小时前
我的天,我真是和androidx的字体加载杠上了
android
小猫猫猫◍˃ᵕ˂◍13 小时前
备忘录模式:快速恢复原始数据
android·java·备忘录模式
CYRUS_STUDIO15 小时前
使用 AndroidNativeEmu 调用 JNI 函数
android·逆向·汇编语言
梦否15 小时前
【Android】类加载器&热修复-随记
android
徒步青云15 小时前
Java内存模型
android
今阳15 小时前
鸿蒙开发笔记-6-装饰器之@Require装饰器,@Reusable装饰器
android·app·harmonyos