Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
631 views
in Technique[技术] by (71.8m points)

Android Navigation Architecture Component - Get current visible 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)

returns a NavHostFragment and I want to retrieve my shown 'MyFragment`.

Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...