问题
I have two Fragments: F1 and F2
F1 contains:
- an EditText that the user can fill
- a 'next' button to go to F2
When the user presses 'next', F2 is displayed and F1 is added to the backstack. So when the user presses back on F2 it returns to F1.
When the user goes back to F1 I want to reset the value in the EditText. As I want to reinitialised the value only when the view is recreated, I reset the value in the onViewCreated
and not in onResume
.
The problem I have is that the EditText is automatically filled by the system when the user presses back as it tries to restore the Fragment in its previous state.
The value is automatically repopulated in onViewStateRestored
from the saveInstanceState
bundle.
So my question is: is it a good idea to override the onViewStateRestored
method to send a null bundle to super (see below), as it solves my issue?
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
super.onViewStateRestored(null);
}
回答1:
So my question is: is it a good idea to override the onViewStateRestored method to send a null bundle to super (see below), as it solves my issue?
The answer is most probably no. This kind of "small" hacks usually lead to huge WTFs and long debug sessions in the future.
For instance, if I'm not mistaken, this hack will immediately lead to a bug in context of config change and save&restore flows. Since in both these flows fragment's View
will be re-created, you will loose user's input.
Most probably, that's not the behavior you want.
I read your discussion in the comments, and still can't understand why you insist to condition clearing of EditText
on re-creation of fragment's View
.
You want this EditText
to be empty if the user gets back to this fragment, right? Then, IMHO, the best solution will be to clear it when "next" button is clicked before transitioning to F2.
来源:https://stackoverflow.com/questions/49757603/change-edittext-value-when-fragment-is-restored-from-backstack