9

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?

Saba Imran
  • 201
  • 2
  • 11
  • `val navHostFragment = navFragment as NavHostFragment` is the equivalent of `NavHostFragment navHostFragment = (NavHostFragment) findViewById(R.id.navFragment)` – Diego Malone Jun 16 '18 at 01:08

6 Answers6

5

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.

Saba Imran
  • 201
  • 2
  • 11
2

This thing worked for me

 val navHostFragment = nav_host_fragment as NavHostFragment
Abir Hossain
  • 111
  • 7
1

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

Daniel Wilson
  • 18,838
  • 12
  • 85
  • 135
0

Actually, verify that the NavHostFragement id in XML matches up with the one you are refering to in your code.

vanJoseph
  • 11
  • 3
0

If you want to inflate NavHost via Fragment then use this code in app.

btnClick.setOnClickListener(view -> {
          NavHostFragment.findNavController(getParentFragment())
                .navigate(R.id.activity_login_to_homeFragment); 
       }

on this code ID MUST BE SAME AS NAVIGATION.XML File attachment.

☻♥ Done.

0

So, attempting to retrieve the NavController in onCreate() of the Activity using Navigation.findNavController(Activity, @IdRes int) will fail. You will have to directly retrieve it from the support fragment manager. First, make sure your activity extends AppCompatActivity. Otherwise, you will not be able to use getSupportFragmentManager(). Then, this code should work:

NavHostFragment navHostFragment =
                    (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);
NavController navController = navHostFragment.getNavController();

Further reading: https://developer.android.com/guide/navigation/navigation-getting-started