Kazuki Tanaka
Kazuki Tanaka

Reputation: 3

How to change fragment and selected item in bottom navigation menu in android studio

I wanted my app to change fragment view and the selected item in bottom navigation menu. I tried doing this:

private void replaceFragment(Fragment fragment){
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.frameLayout,fragment);
        fragmentTransaction.commit();
    }

It changes the fragment but the item selected in the bottom navigation menu doesn't. I tried doing startActivity(new Intent(activity.this, destination.class)); but it doesn't suit the app because it also refreshes the bottom nav menu which is not what I wanted. What I wanted is the fragment and the selected item in bottom navigation menu to both change.

this is the fragment where the button is

I want the app to go here when the book now button is clicked:

this is where i wanted it to go

As you can see in this picture, the fragment changed but the item selected does not. This is when I did the replaceFragment code when i use the replaceFragment code

Upvotes: 0

Views: 5117

Answers (2)

Arezou_ghorbani
Arezou_ghorbani

Reputation: 19

I think the easier and better way is :

Step 1: Add the navigation dependency to your app-level build.gradle file. This will allow you to use the Navigation component in your app.

dependencies {
def nav_version = "2.3.5"
implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
implementation "androidx.navigation:navigation-ui-ktx:$nav_version"
}

Step 2: Create a new menu resource file for the bottom navigation bar. This file will contain the menu items that will be displayed in the bar. To create a new menu resource file, right-click on the res folder in the Project panel, select New > Android resource file, and set the Resource type to Menu.

Step 3: In the menu resource file, add the menu items that will be displayed in the bottom navigation bar. Each menu item should have a unique ID and a title. For example:

<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:id="@+id/navigation_home"
    android:title="Home" />
<item
    android:id="@+id/navigation_dashboard"
    android:title="Dashboard" />
<item
    android:id="@+id/navigation_notifications"
    android:title="Notifications" />

Step 4: In the layout file where you want to display the bottom navigation bar, add a BottomNavigationView element. For example:

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

Note that the app:menu attribute is set to the name of the menu resource file created in step 2.

Step 5: In your activity or fragment that will host the bottom navigation bar, create an instance of NavController using the findNavController() method and pass in the BottomNavigationView as the argument. For example:

<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:startDestination="@id/navigation_home">

<fragment
    android:id="@+id/navigation_home"
    android:name="com.example.myapp.HomeFragment"
    android:label="@string/title_home" />

<fragment
    android:id="@+id/navigation_dashboard"
    android:name="com.example.myapp.DashboardFragment"
    android:label="@string/title_dashboard" />

<fragment
    android:id="@+id/navigation_notifications"
    android:name="com.example.myapp.NotificationsFragment"
    android:label="@string/title_notifications" />

Note that each fragment is identified by a unique ID, which corresponds to the ID of the menu item in the bottom navigation bar.

That's it! With these steps, you should now have a basic bottom navigation bar that can be used to replace different fragments in your app.

Upvotes: 0

AIroot
AIroot

Reputation: 81

You can use Bottom Navigation view implementation from Jet pack Navigation component for this work. it is easy and clear. Bottom navigation will handle all item selected use cases by default. Also you can customized it easily. Here I have added Kotlin example for bottom navigation setup. Step 01: add the following dependencies to your app's build.gradle file:

dependencies {
  val nav_version = "2.4.2"

  // Java language implementation
  implementation("androidx.navigation:navigation-fragment:$nav_version")
  implementation("androidx.navigation:navigation-ui:$nav_version")

  // Kotlin
  implementation("androidx.navigation:navigation-fragment-ktx:$nav_version")
  implementation("androidx.navigation:navigation-ui-ktx:$nav_version")

}

Step 02: Add a NavHostFragment via XML as part of an app's main activity:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

   <com.google.android.material.bottomnavigation.BottomNavigationView
    android:id="@+id/nav_view"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="0dp"
    android:layout_marginEnd="0dp"
    android:background="?android:attr/windowBackground"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:menu="@menu/bottom_navigation_menu" />

<fragment
    android:id="@+id/nav_host_fragment_activity_main"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    app:defaultNavHost="true"
    app:layout_constraintBottom_toTopOf="@id/nav_view"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:navGraph="@navigation/main_nav_graph" />
</androidx.constraintlayout.widget.ConstraintLayout>

Step 03: init Bottom navigation view and navigation controller from your main main activity OnCreate()

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(LayoutInflater.from(this))
        setContentView(binding.root)
        val navView : BottomNavigationView = binding.navView
        val navController = findNavController(R.id.nav_host_fragment_activity_main)
        navView.setupWithNavController(navController)
     
       // Get bottom nav listener
        navController.addOnDestinationChangedListener 
        { _, destination, _ ->
            when (destination.id) {
                R.id.A_Fragment -> {
                    // Add your requirement here base with destination
                }
                else -> {
                    // Add your requirement here
                }
            }

            // Manage bottom nav visibility and etc
            if (destination.id in arrayOf(
                    R.id.A_Fragment,
                    R.id.B_Fragment,
                    R.id.C_Fragment
            )) {
                navView.visibility = View.VISIBLE
                this.supportActionBar?.show()
                setupToolbar()
            }
            else {
                navView.visibility = View.GONE
                this.supportActionBar?.hide()
                // No Toolbar

            }
        }

}

Also you can define destination with navigation graph with this implementation. If you need to add or customized bottomNaivationView item badge, you can use following example fun:

private fun setupBadge(bottomNavigationView: BottomNavigationView) {
        val menu: Menu = bottomNavigationView.menu
        val your_A_MenuItem: MenuItem = menu.getItem(1)
        val your_B_MenuItem: MenuItem = menu.getItem(2)
        val your_A_Badge = bottomNavigationView.getOrCreateBadge(your_A_MenuItem.itemId)
      
        val your_B_Badge = bottomNavigationView.getOrCreateBadge(your_B_MenuItem.itemId)
// Add numbers
your_A_Badge.number = 10
your_A_Badge.isVisible = true
        
    }

Upvotes: 1

Related Questions