简体   繁体   中英

In Android Navigation Architecture, how can I get the previous fragment name?

This is my fragment:

class InvoicesSettingsFragment : Fragment() {

    private lateinit var _navigationHost: NavController

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_invoices_settings, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        _navigationHost = requireView().findNavController()
    }
    
}

I'd like to write the previous fragment name in the current fragment. How can I get the previous fragment name? I tried every property definied in NavController ( _navigationHost ) with no luck. The only other possibility I have in mind is to pass its name as an argument while navigating.

What you mean by fragment name ?

If you want the label of the fragmnet in nav_graph , you can get the backStack property of NavController

val backStack = findNavController().backStack.toList()
if (bacStack.size > 1) {
   val prevDest = backStack[backStack.size - 2]
   prevDest.destination.label // the label of the previous fragment
}

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