How to save fragment state while navigating with navigation component

后端 未结 6 1019
既然无缘
既然无缘 2021-01-02 14:24

I\'m trying to create a single activity app using android architecture components. I have a fragment A which has some textfields, when user pushes a button I navigate to fra

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-02 14:51

    You can use base fragment, but it's just workaround. Actually, navigation component is still buggy. Here is an issue on GitHub. Example:

    class SearchFragment : BaseBottomTabFragment() {
    
        private var _binding: FragmentSearchBinding? = null
        private val binding get() = _binding!!
    
        override fun onCreateView(
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {
            // Inflate the layout for this fragment
            _binding = FragmentSearchBinding.inflate(inflater, container, false)
            return binding.root
        }
    
        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
            binding.buttonDynamicTitleNavigate.setOnClickListener {
                navigateWithAction(
                    SearchFragmentDirections.actionSearchFragmentToDynamicTitleFragment(
                        binding.editTextTitle.text.toString()
                    )
                )
            }
        }
    
        override fun onDestroyView() {
            super.onDestroyView()
            _binding = null
        }
    }
    

    Code snipped from: This project

提交回复
热议问题