简体   繁体   中英

How to create fragments with newInstance() when using NavController?

I'm creating a single-activity app that uses NavController and fragments to display each screen.

The app has a home screen and contains three other menu items in the nav drawer so the user can visit different websites in an external browser.

In the onCreate() method of my MainActivity , I have:

mDrawerLayout = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
        R.id.nav_home,
        R.id.nav_visit_website_1,
        R.id.nav_visit_website_2,
        R.id.nav_visit_website_3)
        .setDrawerLayout(mDrawerLayout)
        .build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);

I've created a VisitWebsiteFragment class which has a static newInstance(String websiteUrl) method - with the intention of using it for the three website menu items.

I've read through the navigation documentation , but I'm not sure how to intercept/control the NavController in order to create the three fragment instances with VisitWebsiteFragment.newInstance(...) .

There may be some aspect of navigation that I'm totally missing. Could someone point me in the right direction?

The IDs of the menu items are nav_visit_website_1 , nav_visit_website_2 and nav_visit_website_3 .

Adding this code to my nav_graph.xml gives me what I need:

<fragment
    android:id="@+id/visit_website"
    android:name="org.example.VisitWebsiteFragment"
    android:label="@string/visit_website" />

<action
    android:id="@+id/nav_visit_website_1"
    app:destination="@id/visit_website">
    <argument
        android:name="url"
        app:argType="string"
        android:defaultValue="https://example.com/website1" />
</action>

<action
    android:id="@+id/nav_visit_website_2"
    app:destination="@id/visit_website">
    <argument
        android:name="url"
        app:argType="string"
        android:defaultValue="https://example.com/website2" />
</action>

<action
    android:id="@+id/nav_visit_website_3"
    app:destination="@id/visit_website">
    <argument
        android:name="url"
        app:argType="string"
        android:defaultValue="https://example.com/website3" />
</action>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM