gpt4 book ai didi

java - 从 fragment 更改工具栏

转载 作者:行者123 更新时间:2023-12-02 06:12:22 25 4
gpt4 key购买 nike

我正在使用 jetpack recommended architecture 编写一个应用程序, NavigationUI, and the navigation graph 。因此,我有一个主要 Activity ,其中包含 ToolbarBottomNavigationViewNavHostFragment

到目前为止,一切都运行良好:我需要更改 Toolbar 以使用 CollapsingToolbarLayout 并将 BottomNavigationView 隐藏在我的 fragment 之一中。

我尝试添加一个导航监听器(如所述 here )来隐藏我的 ToolbarBottomNavigationView,并在我的 fragment 中,我膨胀了新的 工具栏并在主 Activity 上调用setSupportActionBar()

// in MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
navController.addOnDestinationChangedListener((controller, destination, arguments) -> {
if(destination.getId() == R.id.detailFragment){
bottomBar.setVisibility(View.GONE);
topBar.setVisibility(View.GONE);
}else{
bottomBar.setVisibility(View.VISIBLE);
topBar.setVisibility(View.VISIBLE);
}
});
// ...
}

public void changeToolbar(Toolbar toolbar){
getSupportActionBar().hide();
setSupportActionBar(toolbar);
}

// in DetailFragment.java
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// ...
navController = NavHostFragment.findNavController(this);

AppBarConfiguration.Builder builder = new Builder(
R.id.accuracyFragment,
R.id.dataFragment,
R.id.magnetFragment,
R.id.settingsFragment);
AppBarConfiguration config = builder.build();
NavigationUI.setupWithNavController(toolbarLayout, toolbar, navController);
((MainActivity)getActivity()).changeToolbar(toolbar);
// ...
}

它几乎可以正常工作,但是:

  1. 当我向上导航或转​​到另一个 fragment 时,BottomNavigationView 未正确显示。它似乎是被工具栏按下的。
  2. 过渡很丑陋:工具栏明显发生变化,我可以看到它在更改之前就消失了

所以问题是:是否有另一种方法可以更改/隐藏 fragment 中的导航元素?如果没有,我应该创建一个新 Activity 吗?

最佳答案

这是一次疯狂的旅程,但我终于找到了解决方案。对于问题 1,这是由于 Android 管理 fitsSystemWindows 属性传播的方式造成的。为了使其正常工作,我对布局做了一些更改。我创建了一个自定义 FitSystemWindowLinearLayout,它只是一个扩展标准 LinearLayout 并重写 onApplyWindowInsets 的类,如下所示:

  @Override
public WindowInsets onApplyWindowInsets(WindowInsets insets) {
int childCount = getChildCount();
for (int index = 0; index < childCount; ++index) {
getChildAt(index).dispatchApplyWindowInsets(insets);
}

return insets;
}

我的主要 Activity 现在如下所示:

+-- CoordinatorLayout, fitsSystemWindows=false
+-- FitSystemWindowLinearLayout, fitsSystemWindows="false"
+-- Toolbar
+-- NavHostFragment, fitsSystemWindows="false"
+-- BottomNavigationView, fitsSystemWindows="false"

对于第二个问题,即过渡很难看,我通过向过渡添加共享元素来缓解这个问题。

总而言之,我认为使用新的 Activity 来完成此类事情会更容易,NavigationUI 目前还有些不足。

以下是一些对我有帮助的资源:

关于java - 从 fragment 更改工具栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55898362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com