簡體   English   中英

如何在片段中而不是在活動中使用 NavController(在片段中使用 NavHost)?

[英]How to use NavController (with a NavHost in a fragment) in a fragment rather than in an activity?

我有一個 MainActivity,其中有一個帶有 mainFragment 的 navController,用作 4 個片段(Feed、通知、配置文件和幫助)的 NavHost。 我的問題是這些片段中的第三個,我需要它也有自己的 navController 和 3 個選項(活動、成就和編輯配置文件)。 我嘗試創建與我在 MainActivity 中創建的相同的方式,在 Profile 片段中添加一個 NavHost 片段,但是 android 沒有以這種方式接受它,我在 Google 上找不到任何搜索示例。 有誰知道如何解決它?

https://developer.android.com/reference/kotlin/androidx/navigation/NavController

它遵循我在 MainActivity 中實現的方式,這個“bottomNavigationView”是在片段之間轉換的菜單:

        navController = Navigation.findNavController(this, R.id.main_fragment);

        navController.addOnDestinationChangedListener((controller, destination, arguments) -> {
        navDestination = destination;

        switch (destination.getId()) {

            case R.id.feed:
                bottomNavigationView.setCurrentActiveItem(0);
                break;
            case R.id.alerts:
                bottomNavigationView.setCurrentActiveItem(1);
                break;
            case R.id.profile:
                bottomNavigationView.setCurrentActiveItem(2);
                break;
            case R.id.help:
                bottomNavigationView.setCurrentActiveItem(3);
                break;

        }

    });
    bottomNavigationView.setNavigationChangeListener((view, position) -> {

        switch (position) {
            case 0:
                if (navDestination.getId() != R.id.feed) {
                    titleHeaderMain.setText(R.string.publicacao);
                    titleHeaderMain.setGravity(View.TEXT_ALIGNMENT_CENTER);
                    navController.navigate(R.id.feed);
                }
                break;
            case 1:
                if (navDestination.getId() != R.id.alerts) {
                    titleHeaderMain.setText(R.string.notificacoes);
                    navController.navigate(R.id.alerts);
                }
                break;
            case 2:
                if (navDestination.getId() != R.id.profile) {
                    titleHeaderMain.setText(R.string.perfil);
                    navController.navigate(R.id.profile);
                }
                break;
            case 3:
                if (navDestination.getId() != R.id.help) {
                    titleHeaderMain.setText(R.string.ajudar);
                    navController.navigate(R.id.help);
                }
                break;
        }

    });

你必須重新考慮你的導航路徑。 我遇到了同樣的問題,但沒有用。 我不得不重新處理它。

我只將底部導航放在活動中,並根據目的地隱藏或顯示它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM