问题
In an Android project, I have 3 fragments, and I navigate through them during an operation the user does.
FragmentA -> FragmentB -> FragmentC
When the user finishes the operation, I do a popBackStack
to return to FragmentA
if(getFragmentManager()!=null)
if(getFragmentManager().getBackStackEntryCount()>0) {
getFragmentManager().popBackStack(getFragmentManager()
.getBackStackEntryAt(0)
.getName(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
My question is:
I have an EditText
, where the user writes some text, and after the call to popBackStack()
, the fragment shows with the text still there.
Is there a way to know that the fragment has been popped and reset that EditText
?
EDIT
This is what I use to go to next screen:
try {
String backStateName = ((Object) fragment).getClass().getName();
String fragmentTag = backStateName;
ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.container, fragment, fragmentTag);
ft.setTransition(FragmentTransaction.TRANSIT_NONE);
if (addToBackStack)
ft.addToBackStack(backStateName);
ft.commit();
} catch (Exception e) {
Logging.logException(e);
}
回答1:
This can be easily done using flags.
The idea is that when the popBackStack()
is called, the Activity sets a flag which will be checked by FragmentA in its onResume()
.
Simplified steps:
When popping off FragmentC, do this:
clearEditTextOfA = true;
in
onResume()
of FragmentA, do this:if (activityCallback.shouldClearEditText()) { editText.setText(""); }
The
activityCallback
is an interface which lets a Fragment communicate with the Activity it is placed in. See Android Docs.Instead of doing
ft.add()
, doft.replace()
.This will make the
onResume()
of your Fragments get called whenever they change.
来源:https://stackoverflow.com/questions/45192417/how-do-i-clear-edittext-after-all-fragments-above-it-have-been-popped