简体   繁体   中英

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 A -> Fragment B -> Fragment C -> Fragment 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. 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. 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. 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. The ViewModel will outlive the fragments, so when they are recreated they will use the value that you previously stored in the ViewModel.

How to implement ViewModel

Save view in variable and check if view != null then inflate

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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