Search code examples
androidbottomnavigationview

How to change top bar when working with bottom navigation


I'm making my application based on the standard Bottom Navigation Activity from Android Studio.The code was generated automatically, I didn't change it.

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    BottomNavigationView navView = findViewById(R.id.nav_view);
    AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
            R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
            .build();
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
    NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
    NavigationUI.setupWithNavController(navView, navController);
}

And I have this: screen

I want to add to the top screen an icon, by which I will go to other fragments of the MainActivity (which are not in the bottom menu). I want to have this on top of screen top bar

  1. How can I place them exactly on top?
  2. How can I change the color of this top bar?

So far, I could only programmatically set the Title in onCreate MainActivity like this (after deleting labels in mobile_navigations):

this.getSupportActionBar().setTitle("TEST"); 

Solution

    1. override onCreateOptionsMenu() in MainActivity.

       override fun onCreateOptionsMenu(menu: Menu?): Boolean {
           super.onCreateOptionsMenu(menu)
           menuInflater.inflate(R.menu.menu_second, menu)
           return true
       }
      
    2. create menus in res folder

      <menu xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/apk/res-auto">
          <item android:id="@+id/menu_next"
              android:title="toNext"
              android:titleCondensed="next"
              android:orderInCategory="1"
              android:icon="your icon"
              app:showAsAction="always" />
      </menu> 
      

    menu api