Search code examples
androidkotlinandroid-fragmentsandroid-architecture-navigation

How to navigate to previous fragment without reloading in navigation component architecture


I have Fragment A which loads some data when it opens. It has one button when we click. It navigate to Fragment B. That's not the issue, the problem is when I press back Button in Fragment B it comes to Fragment A and reload that data in Fragment A. My problem is I don't want to reload that data in Fragment A When back press From Fragment B.

Thanks in advance


Solution

  • I would suggest Dharmender's approach but if you are not using viewmodel then you can try this:

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
            val tv1 = requireActivity().findViewById<TextView>(R.id.tv1)
            tv1.setOnClickListener {
                if(!isUpdated) {
                    isUpdated = true
                    requireActivity().supportFragmentManager.beginTransaction()
                        .replace((requireView().parent as ViewGroup).id, F2.newInstance())
                        .addToBackStack("f2").commit()
                }else{
                    Toast.makeText(requireActivity(),"Already updated!", Toast.LENGTH_LONG).show()
                }
            }
        }
    
        override fun onCreateView(
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {
            // Inflate the layout for this fragment
            Log.e(TAG,"On create view")
            return inflater.inflate(R.layout.fragment_f1, container, false)
        }
    
        companion object {
            @JvmStatic
            fun newInstance() =
                F1()
            val TAG = F1::class.java.simpleName
            var isUpdated = false
        }
    

    Here I am using one flag isUpdated.