【问题标题】:How to find a child Fragment with Navigation Architecture components如何使用导航架构组件查找子片段
【发布时间】:2019-03-29 22:39:13
【问题描述】:

在学习了有关新架构组件的基础知识后,我决定应用这些知识并开展一个演示项目。在这个项目中,我一直在使用谷歌地图。

在我的 navHost 片段中,其中一个片段以这种方式显示谷歌地图

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

从我一直试图获取这个片段类的代码来看,相关的代码是这样的

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

在 onCreateView 我试过这个

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

它给了我这个错误

运行时异常:非 null 不能转换为 null

有人知道我做错了什么吗?

【问题讨论】:

标签: android kotlin navigation android-architecture-components


【解决方案1】:

此错误与导航组件无关。例如,host?.childFragmentManager?.findFragmentById(R.id.map) as SupportMapFragment 实际上找到了一个嵌套导航图。

如果您只想访问您的子片段,可以通过这种方式重构您的代码

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

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-23
    • 2020-10-20
    • 2018-11-18
    • 1970-01-01
    • 1970-01-01
    • 2018-12-07
    • 2021-03-20
    • 1970-01-01
    相关资源
    最近更新 更多