我的应用只有两个基本活动和几个片段,我想在用户通过单击后退到达特定基本片段时显示退出警报
override fun onBackPressed() {
if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
drawer_layout.closeDrawer(GravityCompat.START)
} else {
// super.onBackPressed()
AlertDialog.Builder(this)
.setTitle("Exit Alert")
.setMessage("Do You Want To Exit Petals App?")
.setPositiveButton(android.R.string.ok) { dialog, whichButton ->
super.onBackPressed()
}
.setNegativeButton(android.R.string.cancel) { dialog, whichButton ->
}
.show()
}
我在每个片段上使用了addtosatck
答案 0 :(得分:1)
首先检查可见片段
val currentFragment =this@ActivityName.supportFragmentManager.findFragmentById(R.id.Your_id)
if(currentFragment is FragmentName)
{
// AlertDialog()
}
最后
override fun onBackPressed()
{
if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
drawer_layout.closeDrawer(GravityCompat.START)
} else
{
val currentFragment =this@ActivityName.supportFragmentManager.findFragmentById(R.id.Your_id)
if(currentFragment is SpecificFragmentName)
{
AlertDialog.Builder(this@ActivityName)
.setTitle("Exit Alert")
.setMessage("Do You Want To Exit Petals App?")
.setPositiveButton(android.R.string.ok) { dialog, whichButton ->
super.onBackPressed()
}
.setNegativeButton(android.R.string.cancel) { dialog, whichButton ->
}
.show()
}
else{
super.onBackPressed()
}
}
}
答案 1 :(得分:0)
您可以:
val callback = requireActivity().onBackPressedDispatcher.addCallback(this) {
// Handle the back button event
}
有关更多信息,您可以检查this。