Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get NavHostFragment

I'm integrating Android's Navigation Architecture Components into my app. I ran into some problems with passing data to the start of a fragment from an activity, so I was following this answer: Navigation Architecture Component- Passing argument data to the startDestination.

The logic seems sound to me, but I'm struggling to determine how to actually get the NavHostFragment. Elliot Shrock used this line -

val navHostFragment = navFragment as NavHostFragment

But I haven't found a Java equivalent that works. I tried getting the fragment of my navHost by using getSupportFragmentManager().findFragmentById(R.id.[mynavhostid])

but this command is returning null. Any ideas?

like image 228
Saba Imran Avatar asked Jun 16 '18 01:06

Saba Imran


3 Answers

I solved this by first inflating the view which contains the NavHost, then using the supportFragmentManager to get the navHost Fragment and pass in my default args.

Hoping that Google's Android team provides a cleaner solution to this in the future.

like image 182
Saba Imran Avatar answered Oct 07 '22 14:10

Saba Imran


This thing worked for me

 val navHostFragment = nav_host_fragment as NavHostFragment
like image 22
Abir Hossain Avatar answered Oct 07 '22 13:10

Abir Hossain


Note, for some reason the debugger will sometimes return null for a NavHostFragment where the code can actually find it without issue. I have no idea why but it's occupied probably 3 hours of my time, make sure it is in fact null by printing or using the fragment!

enter image description here

like image 1
Daniel Wilson Avatar answered Oct 07 '22 13:10

Daniel Wilson