底部导航视图不显示片段,除非双击

bottom navigation view doesnt shows fargment unless double click

我修复了之前的错误,但现在在这里。如果我不单击底部导航两次,则片段不可见。我的代码:

activity_main.xml

<androidx.fragment.app.FragmentContainerView
    android:id="@+id/FragmentContainerView"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    app:layout_constraintBottom_toTopOf="@+id/bottom_navigation"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<com.google.android.material.bottomnavigation.BottomNavigationView
    android:id="@+id/bottom_navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:menu="@menu/bottom_navigation_menu" />

MainActivity.kt

binding.bottomNavigation.setOnItemReselectedListener { item ->
        when(item.itemId) {
            R.id.home -> {
                replaceFragment(HomeFragment())
            }
            R.id.favs -> {
                replaceFragment(FavsFragment())
            }
        }
    }
}

private fun replaceFragment(fragment: Fragment) {
    val fragmentManager = supportFragmentManager
    val fragmentTransaction = fragmentManager.beginTransaction()

    fragmentTransaction.replace(R.id.FragmentContainerView, fragment)
    fragmentTransaction.commit()
}

首先我们创建navigation.xml(点击左边的ResourceManager按钮,点击上方的select导航,点击+号就可以创建navigation.xml),然后我们将其命名为 my_nav 并单击顶部的新目标按钮和 select 您将使用的所有片段。我建议你先select你的主要片段

<fragment
        android:id="@+id/fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@+id/bottom_navigation"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/my_nav" />

或者试试这个

binding.bottomNavigation.setItemSelected(R.id.home, true) 

顺便给你一些建议

binding.apply{
//If I do it this way, you don't need to write bindings for your objects every time.
//eg:
  bottomNavigation.setOnItemReselectedListener { item ->        
    }
}

您应该使用 setOnItemSelectedListener 而不是 setOnItemReselectedListener 来避免“double-clicking”。

但是您仍然需要将初始片段添加到 FragmentContainerView。例如,在 onCreate() 中,您可以使用需要首先显示的片段来调用您的 replaceFragment()