Reputation: 11
In user enter data, UI/UX screen there are 'Save', 'Cancel' buttons. If user enters some data, BUT taps Back key, I need to display (AlertDialog) whether he wants to save the data or not. How can be done ?
I think this should be done on something like: @override onDestroy() ? but unable to (kind of) hold/pause onDestroy() and display the AlertDialog !
This would be something similar to what 'Microsoft Word' does, but in Android.
Upvotes: 1
Views: 80
Reputation: 582
If you have Fragment you can Pass Listener and then you can listen whenever user presses back button you will be notified.
create interface.
interface IOnBackPressed {
fun onBackPressed(): Boolean
}
in your Activity.
class MyActivity : AppCompatActivity() {
override fun onBackPressed() {
val fragment =
this.supportFragmentManager.findFragmentById(R.id.main_container)
(fragment as? IOnBackPressed)?.onBackPressed()?.not()?.let {
super.onBackPressed()
}
}
}
in your Fragment.
class YourFragmentName : Fragment(), IOnBackPressed {
override fun onBackPressed(): Boolean {
//Create Your Dialog.
//Dialog.Positive.clicked return true
//Dialog.Negate.clicked return false
}
}
Upvotes: 0
Reputation: 27
There is a method specifically for this purpose, it's called when the user presses the back button on their device.
@Override
public void onBackPressed() {
//super.onBackPressed();
..call the dialog builder here..
}
you can use super.onBackPressed() method when the user presses either the positive or negative buttons.
Upvotes: 0
Reputation: 7347
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if(needsSave){
.
.
.
return true;
}
}
return super.onKeyDown(keyCode, event);
}
Upvotes: 1