在尝试导航组件之前,我曾经手动执行片段事务,并使用fragment标签来获取当前片段.
Before trying the Navigation component I used to manually do fragment transactions and used the fragment tag in order to fetch the current fragment.
val fragment:MyFragment = supportFragmentManager.findFragmentByTag(tag):MyFragment
现在在我的主要活动布局中,我有类似的东西:
Now in my main activity layout I have something like:
<fragment android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/nav_host" app:navGraph= "@navigation/nav_item" android:name="androidx.navigation.fragment.NavHostFragment" app:defaultNavHost= "true" />如何通过导航"组件检索当前显示的片段?
How can I retrieve the current displayed fragment by the Navigation component? Doing
supportFragmentManager.findFragmentById(R.id.nav_host)
返回一个NavHostFragment,我想检索显示的'MyFragment`.
returns a NavHostFragment and I want to retrieve my shown 'MyFragment`.
谢谢.
推荐答案我设法找到了一种方法,如下所示:
I managed to discover a way for now and it is as follows:
NavHostFragment navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host); navHostFragment.getChildFragmentManager().getFragments().get(0);当然,您知道这是第一个片段.我仍在研究一种没有这种方法的方法.我同意这不是最好的方法,但目前应该是这样.
In case of course you know it is the first fragment. I am still investigating a way without this. I agree it is not the best way but that should be something for now.
更多推荐
Android导航体系结构组件
发布评论