簡體   English   中英

當我使用底部導航視圖時如何從主頁片段中的操作欄中刪除后退箭頭

[英]How to remove back arrow from action bar in the home fragment when I'm using bottom navigation view

我用 label 為每個片段創建了三個片段和工具欄。我使用向上導航在主頁片段和其他片段之間切換。 我的問題是,在主要片段中,我想從工具欄中刪除后退箭頭。 我已經在主要活動上嘗試過這個actionBar?.setDisplayHomeAsUpEnabled(false)但它沒有用。請幫助我

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val bottomNavView = bottom_nav
    val navController = findNavController(R.id.fragment_nav_host)

    setSupportActionBar(toolbar)
    val actionBar = supportActionBar

    val appbarConfig = AppBarConfiguration(setOf(R.layout.fragment_home,R.layout.fragment_favorite,R.layout.fragment_profile))

    setupActionBarWithNavController(navController,appbarConfig)

    bottomNavView.setupWithNavController(navController)
}

override fun onSupportNavigateUp(): Boolean {
    val navController = this.findNavController(R.id.fragment_nav_host)
    return navController.navigateUp()
}

}

這是 activity_main 布局上的工具欄代碼

<androidx.appcompat.widget.Toolbar
     android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:theme="@style/toolbarTheme"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/colorPrimary" />

截圖

您需要禁用操作欄的主頁按鈕,如下所示

   setSupportActionBar(toolbar)
   val actionBar = supportActionBar
        if (actionBar != null) {
            actionBar?.setDisplayShowHomeEnabled(false);
            actionBar?.setHomeButtonEnabled(false);
        }

在 View Created 上,添加這個

(作為 AppCompatActivity 的活動).supportActionBar?.setDisplayHomeAsUpEnabled(false)

終於找到了答案。 如果您查看 setupActionBarWithNavController 的文檔,您會注意到此處設置的操作欄是通過方法 getSupportActionBar() 而不是 getActionBar() 返回的,建議在每個線程中使用該方法。

現在,如果您想按照我的意願在片段級別上使用它,那么您還需要將片段保存的活動轉換為 AppCompatActivity,以便您可以訪問 supportActionBar。

像這樣:

(requireActivity() as AppCompatActivity).supportActionBar?.setDisplayHomeAsUpEnabled(false)

Java 代碼將以下內容放入 onviewcreated(.....)

  try {
        ((AppCompatActivity) getActivity()).getSupportActionBar().hide();
    } catch (Exception ex) {
        ex.printStackTrace();
    }

暫無
暫無

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

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