简体   繁体   English

Android导航架构组件避免了Fragment娱乐

[英]Android Navigation Architecture component avoid Fragment recreation

I have the following flow where within Fragment's content is a Form with various input fields. 我有以下流程,其中Fragment的内容是具有各种输入字段的表单。

Fragment A -> Fragment B -> Fragment C -> Fragment D ... 片段A - >片段B - >片段C - >片段D ......

when the user has filled, for example, the Frag C completely, and move back to Frag B, all the Frag B data is stored and kept as intact, but when moving forward back to C, all the input data is gone. 例如,当用户完全填充了Frag C并返回到Frag B时,所有Frag B数据都被存储并保持完整,但是当向前移回C时,所有输入数据都消失了。 Imagine the same scenario, the user Filled Frag A, B and he had filled half of the Frag C fields, and he chooses to go back to Frag A, when he's navigating back all the input data is intact on the previous Frags (B and A), but once he decides to move forward back to C where he was, the data from B and C are lost and replaced with new fragment every new step. 想象一下同样的场景,用户填充片段A,B并且他已经填充了一半的Frag C字段,并且他选择回到Frag A,当他导航回来时,所有输入数据在之前的Frags上完好无损(B和A),但是一旦他决定向前移回C所在的位置,B和C的数据就会丢失,并在每一个新步骤中都被新的片段替换。 So the input data is only kept when going back (android back button), when he opens the Fragment where he's already have been there before, a new Fragment with all input as blank is created. 因此输入数据仅在返回时保留(android后退按钮),当他打开之前已经存在的Fragment时,会创建一个所有输入为空的新片段。 Is it possible to keep fragment as unique whenever the user moves back or moves forward to it on Navigation architecture component? 每当用户向后移动或在导航架构组件上向前移动时,是否可以将片段保持为唯一?

This isn't a way to stop fragment recreation but it addresses your problem. 这不是一种停止片段娱乐的方法,但它可以解决您的问题。 Create an activity scoped ViewModel to hold the form data, and then have your fragments observe this ViewModel. 创建一个活动范围的ViewModel来保存表单数据,然后让您的片段观察此ViewModel。 The ViewModel will outlive the fragments, so when they are recreated they will use the value that you previously stored in the ViewModel. ViewModel将比片段更长,因此当它们被重新创建时,它们将使用您先前存储在ViewModel中的值。

How to implement ViewModel 如何实现ViewModel

Save view in variable and check if view != null then inflate 将视图保存在变量中并检查是否为view!= null然后膨胀

  private var mView: View? = null

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                            savedInstanceState: Bundle?): View? {
    return if(mView == null) {
      val v = inflater.inflate(R.layout.chat_fragment, container, false)
      initializeView(v)
      mView = v
      v
    }else{
      mView
    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM