New User
New User

Reputation: 13

How to find a child Fragment with Navigation Architecture components

After learning basics about new architecture components, I decided to apply this knowledge and work a demo project. In this project I have been working with google map.

In my navHost fragment, one of the fragment shows google map this way

<fragment android:layout_width="match_parent" android:layout_height="match_parent"
          android:id="@+id/map"
          android:name="com.google.android.gms.maps.SupportMapFragment"></fragment>

from the code I have been trying to get this fragment class, the related code looks like this

private val host: NavHostFragment? by lazyFast {
    activity?.supportFragmentManager
        ?.findFragmentById(R.id.my_nav_host_fragment) as NavHostFragment?
}

and in onCreateView I tried this

val mapFragment = host?.childFragmentManager?.findFragmentById(R.id.map) as SupportMapFragment
    mapFragment.getMapAsync(this)

it gave me this error

Runtime Exception: non-null can not be casted to null

Anyone has any idea what I am doing wrong?

Upvotes: 1

Views: 2795

Answers (1)

Wubbalubbadubdub
Wubbalubbadubdub

Reputation: 2475

this error has nothing to do with Navigation Components. for example, host?.childFragmentManager?.findFragmentById(R.id.map) as SupportMapFragment actually find a nested navigation graph.

If you just want to get access to your child fragment, it can be done just refactoring your code this way

val mapFragment = this.childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment

hope it helps

Upvotes: 4

Related Questions