从片段堆栈还原Fragment时更改EditText值 [英] Change EditText value when Fragment is restored from backstack

查看:246
本文介绍了从片段堆栈还原Fragment时更改EditText值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个片段:F1和F2

I have two Fragments: F1 and F2

F1包含:

  • 用户可以填充的EditText
  • 一个下一步"按钮转到F2

当用户按下"next"时,将显示F2并将F1添加到后堆栈.因此,当用户在F2上按回时,它将返回F1.

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.

当用户返回F1时,我想重置EditText中的值.因为我只想在重新创建视图时才重新初始化该值,所以我在onViewCreated中而不是在onResume中重置该值.

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.

我遇到的问题是,当用户按下时,EditText由系统自动填充,因为它试图将Fragment还原为以前的状态. 该值会自动从saveInstanceState捆绑包的onViewStateRestored中重新填充.

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.

所以我的问题是:覆盖onViewStateRestored方法以将空束发送到super(请参见下文)是一个好主意,因为它解决了我的问题?

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);
}

推荐答案

所以我的问题是:覆盖onViewStateRestored方法以将空束发送到super(请参见下文)是一个好主意,因为它解决了我的问题?

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?

答案很可能不是.这种小"黑客通常会在将来导致巨大的WTF和冗长的调试会话.

The answer is most probably no. This kind of "small" hacks usually lead to huge WTFs and long debug sessions in the future.

例如,如果我没记错的话,这种黑客攻击将立即导致配置更改和保存并恢复流程方面的错误.由于在这两个流程中都会重新创建片段的View,因此您将失去用户的输入.

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.

我阅读了您在评论中的讨论,但仍然不明白为什么您坚持要在重新创建片段View时要求清除EditText.

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.

如果用户回到此片段,您希望此EditText为空,对吗?然后,恕我直言,最好的解决方案是在转换到F2之前单击下一步"按钮将其清除.

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.

这篇关于从片段堆栈还原Fragment时更改EditText值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆