How to find a child Fragment with Navigation Architecture components

柔情痞子 提交于 2020-08-10 19:35:33

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/52987205/how-to-find-a-child-fragment-with-navigation-architecture-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!