【问题标题】:Change toolbar from fragment从片段更改工具栏
【发布时间】:2019-04-29 06:56:57
【问题描述】:

我正在使用jetpack recommended architecture、NavigationUI, and the navigation graph 编写应用程序。所以我有一个主要活动是Toolbar、BottomNavigationView 和NavHostFragment。

到目前为止一切正常:我需要将Toolbar 更改为使用CollapsingToolbarLayout 并将BottomNavigationView 隐藏在我的一个片段中。

我尝试添加一个导航监听器(如here 所述)来隐藏我的Toolbar 和BottomNavigationView,在我的片段中,我膨胀了新的Toolbar 并在主要活动上调用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. 当我向上导航或转​​到另一个片段时,BottomNavigationView 未正确显示。好像被Toolbar推倒了。
  2. 过渡很丑:工具栏明显改变,我可以看到它在改变之前就消失了

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

【问题讨论】:

    标签: java android android-fragments android-jetpack


    【解决方案1】:

    这是一段疯狂的旅程,但我终于找到了解决方案。对于问题 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;
      }
    

    我的主要活动现在看起来像这样:

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

    对于第二个问题,即过渡效果不好,我通过在过渡效果中添加共享元素来缓解这种情况。

    总而言之,我认为为这类事情使用新活动更容易,NavigationUI 现在有点短。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多