如何在片段中动态更改标签?

How to change label dynamically in Fragment?

我想更改 Fragment

中的 "android:label"

我尝试运行下面的代码来更改标签,但是失败了。

val graph = findNavController().graph
graph.label = "测试"
findNavController().graph = graph

根据 Navigation UI documentation, the NavigationUI methods, such as the setupActionBarWithNavController() method rely on an OnDestinationChangedListener,每次您 navigate() 到新目的地时都会调用它。这就是标签不会立即更改的原因 - 它只会在您导航到新目的地时更新。

文档确实解释了 the top app bar:

the label you attach to destinations can be automatically populated from the arguments provided to the destination by using the format of {argName} in your label.

这允许您将用于标签的字符串(比如 R.string.destination_label)更新为

的形式
<string name="destination_label">You are on {destination}</string>

通过在您的目的地使用相同的 argument,您的标题将自动填充正确的信息。

当然,如果您没有可以提前确定的参数,那么您最好避免在目的地设置 android:label,而是手动更新操作栏的来自该目的地的标题等。

navController.addOnDestinationChangedListener((controller, destination, arguments) -> {
        destination.setLabel("Bruno is here");

    });

只需在托管 activity onCreate() 函数中添加以下代码行。

  1. 获取NavController的引用,这里我使用NavHostFragment获取NavController的引用,你也可以使用其他方式。
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.nav_host_container);

NavController navController= navHostFragment.getNavController();
  1. 将 addOnDestinationChangedListener 添加到 NavController 并根据参数中收到的数据项更改标签。
navController.addOnDestinationChangedListener( new NavController.OnDestinationChangedListener() {
                @Override
                public void onDestinationChanged(@NonNull NavController controller, @NonNull NavDestination destination, @Nullable Bundle arguments) {
                    if (destination.getId() == R.id.fragmentID) {
                        if (arguments != null) {
                            DataItem item = FragmentArgs.fromBundle(arguments).getItem();
                            if (item != null)
                                destination.setLabel(getString(R.string.your_label));
                            else
                                destination.setLabel(getString(R.string.other_label));
                        }
                    }

                }
            });