Android导航体系结构组件-获取当前可见的片段 [英] Android Navigation Architecture Component - Get current visible fragment

查看:52
本文介绍了Android导航体系结构组件-获取当前可见的片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试导航组件之前,我曾经手动执行片段事务,并使用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导航体系结构组件-获取当前可见的片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆