BottomNavigationView与navgraph再次加载片段

时间:2019-03-15 08:39:02

标签: android kotlin bottomnavigationview androidx

我将 Picasso.with(context).load(uri).placeholder(R.drawable.profile_display).fit().centerCrop().into(yourImageView); BottomNavigationView一起使用 下面是我的代码

nav-graph

MainActivity.class

activity_main.xml

navController = Navigation.findNavController(this, R.id.mainFragment);

    bottomNavigation.setOnNavigationItemSelectedListener(menuItem -> {
        switch (menuItem.getItemId()){
            case R.id.home:
                navController.navigate(R.id.exploreFragment);
                return true;
            case R.id.events:
                navController.navigate(R.id.eventsFragment);
                return true;
            case R.id.stories:
                navController.navigate(R.id.storiesFragment);
                return true;
        }
        return false;
    });

nav_home.xml

<fragment
    android:id="@+id/mainFragment"
    app:defaultNavHost="true"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toTopOf="@+id/bottomNavigation"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:navGraph="@navigation/nav_home"/>

<com.google.android.material.bottomnavigation.BottomNavigationView
    android:layout_width="match_parent"
    app:itemIconTint="@drawable/bottom_navigation_color"
    app:itemTextColor="@drawable/bottom_navigation_color"
    android:background="@color/grey_50"
    android:id="@+id/bottomNavigation"
    app:menu="@menu/bottom_navigation"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    android:layout_height="wrap_content"/>

<include
    layout="@layout/toolbar"
    android:id="@+id/toolbar"/>

所以问题是当我在BottomNavigationView中点击Home时,它会一次又一次地重新加载片段。我尝试了很多方法,但没有成功。

2 个答案:

答案 0 :(得分:1)

由于您使用的是navigation controller,因此可以删除setOnNavigationItemSelectedListener功能。

bottom_navigation菜单中,确保定义的项目ID与在nav graph中定义的ID相同。

您需要这些代码才能使底部导航栏起作用

setupActionBarWithNavController(navController!!)
bottomNavigation.setupWithNavController(navController!!)

修改

对于androidx

NavigationUI.setupWithNavController(bottomNavigation, 
Navigation.findNavController(this, R.id.mainFragment))

答案 1 :(得分:0)

val navController = Navigation.findNavController(this, R.id.mainFragment) 
bottomNavigation.setOnNavigationItemSelectedListener {
                if (it.itemId != bottomNavigation.selectedItemId)
                    NavigationUI.onNavDestinationSelected(it, navController)
                 true

}