对于那些仍在寻找解决方案的人,我尝试了许多方法,但这个(Kotlin)对我来说是最好的:
Image
片段A
1- 在FRAGMENT A的onStop()中阻止片段a后代的焦点性,以避免活动在BACK时将焦点给予随机按钮。
override fun onStop() {
println("**onStop")
(view as ViewGroup?)?.descendantFocusability = ViewGroup.FOCUS_BLOCK_DESCENDANTS
super.onStop()
}
2- 制作一个lambda函数来处理简历上的一些事情
private var doOnResume: (() -> Unit?)? = null
3- 设置片段转换
private fun gotoFragment(onResume: () -> Unit) {
doOnResume = onResume
(requireActivity() as MainActivity).apply {
supportFragmentManager.commit {
replace(R.id.app_container, DetailsFragment())
addToBackStack(null)
}
}
}
4- 我正在使用Leanback RowSupportFragment,当您请求将焦点设置到其VerticalGridView时,它会自动将焦点设置为最后一个项目。
listFragment.setOnContentClickedListener {
gotoFragment {
listFragment.verticalGridView.requestFocus()
}
}
注意,你可以将焦点放在任何你想要的视图上
private fun onPlayButtonClicked() {
binding.playBTN.setOnClickListener {button->
gotoFragment {
button.requestFocus()
}
}
}
5- 在onResume中调用您的Lambda函数
override fun onResume() {
(view as ViewGroup?)?.descendantFocusability = ViewGroup.FOCUS_AFTER_DESCENDANTS
try {
doOnResume?.invoke()
} catch (_:Exception) {
}
super.onResume()
}