【问题标题】:Show/Hide Back Button in Toolbar在工具栏中显示/隐藏返回按钮
【发布时间】:2018-06-20 18:48:17
【问题描述】:

我想在某些情况下在工具栏中显示返回按钮,并在另一种情况下隐藏它。我写了下面的代码:

public void setupToolbar() {
    if (mStacks.get(mCurrentTab).size() > 1) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        toolbar.setNavigationOnClickListener(v -> onBackPressed());
    } else {
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        getSupportActionBar().setHomeButtonEnabled(false);
    }
} 

但我的问题是当我将主页按钮设置为假时,即使第一个条件变为真,它也不再可见。有人可以帮帮我吗?

【问题讨论】:

  • 尝试拨打getSupportActionBar().setDisplayShowHomeEnabled(true);
  • @AtefHares 没有任何改变。
  • 您是否将工具栏设置为支持操作栏?您需要在 onCreate() 方法中执行此操作: // 工具栏 Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar);
  • @NicolaGallazzi 是的,我将它设置为支持操作栏。

标签: android android-actionbar toolbar


【解决方案1】:

在工具栏中显示/隐藏返回按钮。请尝试一下

显示代码

 if (getSupportActionBar() != null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
    }

隐藏代码

 if (getSupportActionBar() != null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        getSupportActionBar().setHomeButtonEnabled(false);
    }

【讨论】:

    【解决方案2】:

    如果我正确理解了您的观点,您应该使用以下代码:

     private void hideSystemUI() {
        // Enables regular immersive mode.
        // For "lean back" mode, remove SYSTEM_UI_FLAG_IMMERSIVE.
        // Or for "sticky immersive," replace it with SYSTEM_UI_FLAG_IMMERSIVE
        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_IMMERSIVE
                        // Set the content to appear under the system bars so that the
                        // content doesn't resize when the system bars hide and show.
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        // Hide the nav bar and status bar
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_FULLSCREEN);
    }
    

    此函数隐藏 BackButton 和 HomeButton

    为了展示你应该使用以下代码:

    private void showSystemUI() {
        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 2012-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多