如何使用导航架构组件查找子片段 [英] How to find a child Fragment with Navigation Architecture components
问题描述
在学习了有关新架构组件的基础知识之后,我决定应用这些知识并进行一个演示项目.在这个项目中,我一直在使用Google Map.
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.
在我的navHost片段中,其中一个片段以这种方式显示了Google地图
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?
}
在onCreateView中,我尝试了
and in onCreateView I tried this
val mapFragment = host?.childFragmentManager?.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
它给了我这个错误
运行时异常:非null不能强制转换为null
Runtime Exception: non-null can not be casted to null
有人知道我在做什么错吗?
Anyone has any idea what I am doing wrong?
推荐答案
此错误与导航组件无关.例如,host?.childFragmentManager?.findFragmentById(R.id.map) as SupportMapFragment
实际上找到了嵌套的导航图.
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
希望有帮助
这篇关于如何使用导航架构组件查找子片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!