android - Controlling back button inside Fragment -
i have programming experience, not in android. think, on platform, can not allow user leave screen without data saved. have ensure data correct before saving.
in android, not find effective way implement scenario using fragments
let's consider app containing 1 activity called a1 controls 3 fragments f1, f2 , f3.
f1 , f2 accessed via navigationdrawer.
f3 called f2 when user wants enter data in database. f3 has several edittexts , other views, not idea leave f3 without alerting user may lose everything.
in toolbar there menu item lets user save data , return f2.
i control button in order prevent user forget save data or had way send message (toast) user, if have errors in information data.
do using activities possible, not solution, because i'm using navigationdrawer.
as far know, onbackpressed activity callback , not intercepted fragment.
in short:
i stay in fragment f3 until user correct errors , save data. in case of he/she tap button without save, alertdialog sent him/her.
anybody did that? best pratice data consistency in android?
thanks in advance help.
f3 called f2 when user wants enter data in database. f3 has several edittexts , other views, not idea leave f3 without alerting user may lose everything.
have considered backing data inside onpause()
(or ondestroy()
even) of fragment
? can store information inside edittext
(perhaps sharedpreferences
), , restore when fragment
restarts if destroyed.
that aside, create interface
(i.e. backpressobserver
) , have fragment
want react presses implement it.
public interface backpressobserver { boolean isreadytointerceptbackpress(); void onbackpress(); }
fragment one
public class fragmentone extends fragment implements backpressobserver { @override public boolean isreadytointerceptbackpress() { return this.isvisible() && //**another condition, i.e. !edittext.gettext().tostring().isempty();** } @override public void onbackpress() { //do whatever needs done on press. when finished, make sure isreadytointerceptbackpress() return false. } }
activity
public class mainactivity extends appcompatactivity { @override public void onbackpressed() { (fragment fragment : getsupportfragmentmanager().getfragments()) { if (fragment instanceof backpressobserver) { backpressobserver observer = (backpressobserver) fragment; if (observer.isreadytointerceptbackpress()) { observer.onbackpress(); return; } } } super.onbackpressed(); } }
Comments
Post a Comment