如何在 NavHostFragment 中检索当前片段? [英] How I can retrieve current fragment in NavHostFragment?
本文介绍了如何在 NavHostFragment 中检索当前片段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在新的导航组件中找到一个方法,但我没有找到任何关于它的方法.
I tried to find a method in the new Navigation components but I didn't find anything about that.
我有当前目的地:
mainHostFragment.findNavController().currentDestination
但我无法获得对显示片段的任何引用.
But I can't get any reference to the displayed fragment.
推荐答案
引用显示的片段(AndroidX):
Reference to the displayed fragment (AndroidX):
Java
public Fragment getForegroundFragment(){
Fragment navHostFragment = getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);
return navHostFragment == null ? null : navHostFragment.getChildFragmentManager().getFragments().get(0);
}
科特林
val navHostFragment: Fragment? =
supportFragmentManager.findFragmentById(R.id.nav_host_fragment)
navHostFragment?.childFragmentManager?.fragments?.get(0)
这里 nav_host_fragment
是一个 ID使用 android:name="androidx.navigation.fragment.NavHostFragment"
Here nav_host_fragment
is an ID
of the fragment
tag in your activity_main.xml
with android:name="androidx.navigation.fragment.NavHostFragment"
这篇关于如何在 NavHostFragment 中检索当前片段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文