Add (not replace) fragment with navigation architecture component

后端 未结 6 1882
失恋的感觉
失恋的感觉 2021-01-31 02:14

I have an activity with a product list fragment and many other fragments and I am trying to use architecture component navigation controller.

The problem is: it replaces

6条回答
  •  迷失自我
    2021-01-31 02:37

    I faced the same problem, while waiting on add and other options for fragment transactions I implemented this work around to preserve the state when hitting back.

    I just added a check if the binding is present then I just restore the previous state, the same with the networking call, I added a check if the data is present in view model then don't do the network refetching. After testing it works as expected.

    EDIT: For the recycler view I believe it will automatically return to the same sate the list was before you navigated from the fragment but storing the position in the onSavedInstanceSate is also possible

      private lateinit var binding: FragmentSearchResultsBinding
    
      override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {
            viewModel =
                ViewModelProviders.of(this, mViewModelFactory).get(SearchResultsViewModel::class.java)
            return if (::binding.isInitialized) {
                binding.root
            } else {
                binding = DataBindingUtil.inflate(inflater, R.layout.fragment_search_results, container, false)
    
                with(binding) {
                   //some stuff
                    root
                }
            }
    }
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
            //reload only if search results are empty
            if (viewModel.searchResults.isEmpty()) {
               args.searchKey.let {
                    binding.toolbarHome.title = it
                    viewModel.onSearchResultRequest(it)
                }
            }
        }
    

提交回复
热议问题