问题描述
我有一个表单,希望在用户离开之前得到用户的确认消息.
I have a form and want to get a confirmation message from the user before the user leaves it.
我想在用户触摸此按钮时提供自定义后退按钮:
i want provide custom back button when user touch this button:
我试试这个:
val onBackPressedCallback = object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
}
}
requireActivity().onBackPressedDispatcher.addCallback(this,onBackPressedCallback)
但似乎只能为内置的软件/硬件后退按钮提供自定义后退行为,而不是后退箭头按钮
but only seems to work for providing custom back behavior to the built-in software/hardware back button and not the back arrow button
我该怎么做?
推荐答案
使用 onSupportNavigateUp
,并将 yourCurrentFragmentID
替换为当前的片段ID.所有这些都应在MainActivity中完成.
Use onSupportNavigateUp
, and replace yourCurrentFragmentID
to your current fragment id. All these should be done in MainActivity.
navController = findNavController(R.id.nav_host_fragment)
setupActionBarWithNavController(navController!!)
override fun onSupportNavigateUp(): Boolean {
return when(navController?.currentDestination?.id) {
R.id.yourCurrentFragmentID -> {
showDialog()
true
}
else -> navController?.navigateUp()!!
}
}
修改
如果您的片段已使用 onOptionsItemSelected
,则可以通过检查 itemId
来处理逻辑.
If your fragment already use onOptionsItemSelected
, you can handle the logic by checking itemId
.
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
if (id == R.id.save) {
// your save button code logic
}else if(id ==android.R.id.home){
// display confirmation message
}
return super.onOptionsItemSelected(item)
}
这篇关于自定义后退按钮-Android导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!