How can I add a different button on Toolbar in Different Activity?

90 Views Asked by At

Here's my activity_main.xml, which have a basic Toolbar and two Buttons on the right (and as well a NavigationView):

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.drawerlayout.widget.DrawerLayout 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"
        android:background="@drawable/mxhbg"
        android:id="@+id/drawer_layout"
        android:fitsSystemWindows="true"
        tools:context="com.myapp.MainActivity"
        tools:openDrawer="start">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/mxhbg"
            android:orientation="vertical"
            android:keepScreenOn="true"
            android:weightSum="10">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="54dp"
                android:orientation="horizontal">

                <androidx.appcompat.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    android:background="@color/colorPrimary"
                    android:elevation="4dp"
                    android:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

                    <Button
                        android:id="@+id/btnRandom"
                        android:layout_width="30dp"
                        android:layout_height="30dp"
                        android:layout_alignParentEnd="true"
                        android:layout_centerVertical="true"
                        android:layout_gravity="end"
                        android:layout_marginEnd="16dp"
                        android:background="@drawable/ic_shuffle">

                    </Button>

                    <Button
                        android:id="@+id/btnRescanSongs"
                        android:layout_width="30dp"
                        android:layout_height="30dp"
                        android:layout_alignParentEnd="true"
                        android:layout_centerVertical="true"
                        android:layout_gravity="end"
                        android:layout_marginEnd="16dp"
                        android:background="@android:drawable/stat_notify_sync">

                    </Button>
                </androidx.appcompat.widget.Toolbar>

            </LinearLayout>

            // other stuff
            
        </LinearLayout>

        <com.google.android.material.navigation.NavigationView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:id="@+id/nav_view"
            app:headerLayout="@layout/nav_header"
            app:menu="@menu/drawer_menu">

        </com.google.android.material.navigation.NavigationView>

    </androidx.drawerlayout.widget.DrawerLayout>

I set it on MainActivity this way:

setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

Now, on another Activity (SyncActivity), I'd like to display the same Toolbar but with different icons on the right.

What's the correct way to do this?

Doing this on activity_sync.xml:

    <?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"
        android:background="@drawable/mxhbg"
        tools:context=".SyncActivity">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/mxhbg"
            android:orientation="vertical"
            android:keepScreenOn="true"
            android:weightSum="10">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="54dp"
                android:orientation="horizontal">

                <androidx.appcompat.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    android:background="@color/colorPrimary"
                    android:elevation="4dp"
                    android:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

                    <Button
                        android:id="@+id/btnRescanSongs"
                        android:layout_width="30dp"
                        android:layout_height="30dp"
                        android:layout_alignParentEnd="true"
                        android:layout_centerVertical="true"
                        android:layout_gravity="end"
                        android:layout_marginEnd="16dp"
                        android:background="@android:drawable/stat_notify_sync">

                    </Button>
                </androidx.appcompat.widget.Toolbar>

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="9">

                <ListView
                    android:id="@+id/log"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:divider="@android:color/transparent"
                    android:dividerHeight="10.0sp"
                    android:padding="8dp">

                </ListView>

            </LinearLayout>
        </LinearLayout>

    </androidx.constraintlayout.widget.ConstraintLayout>

and on SyncActivity:

    setContentView(R.layout.activity_sync);
    Objects.requireNonNull(getSupportActionBar()).setTitle("Sync");
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);

it adds a new Toolbar, below the main one.

Also: why the icons on main Toolbar are not showed on other Activity? Seems it hides them? Why?

2

There are 2 best solutions below

2
madlymad On BEST ANSWER

You can remove all the toolbar buttons from the layout xml and move them to menu xml like that.

File: res/menu/yourmenuname.xml

<menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/menu_random"
        android:icon="@android:drawable/stat_notify_sync"
        android:title="@string/menu_rescan_songs"
        app:showAsAction="always"/>
    <item
        android:id="@+id/menu_rescan_songs"
        android:icon="@android:drawable/stat_notify_sync"
        android:title="@string/menu_rescan_songs"
        app:showAsAction="always"/>

</menu>

Note that you also have to provide a title and not only the icon you can use the showAsAction with always to display always the icon or ifRoom or ifRoom|withText just experiment what likes you most.

Then in each of your activities you override this function to load your menu. Pay attention to yourmenuname that will be different in each one of the activities.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
   getMenuInflater().inflate(R.menu.yourmenuname,menu);
   return super.onCreateOptionsMenu(menu);
}

And to handle the menu actions use:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
        case R.id.menu_random:
            doSomethingElse();
            return true;
        case R.id.menu_rescan_songs:
            doSomething();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

In the second activity use the different menu with the different options and do the handling and creation in a similar way.

There are a lot of stuff you can do with the menus, adding here some links that may help you keep reading on them:

0
G.Shraddha On

If you want to use same Toolbar in multiple screens, include it in BaseActivity. This activity should include all common UIs of your application.

Then you have to extend MainActivity/SyncActivity from BaseActivity

open class BaseActivity : AppCompatActivity {

    var  baseLayoutBinding : ActivityBaseBinding? = null

    override fun setContentView(layoutResID: Int) {
       baseLayoutBinding = ActivityBaseBinding.inflate(LayoutInflater.from(this))
    layoutInflater.inflate(layoutResID, baseLayoutBinding?.mainContainer, true)
    
       super.setContentView(baseLayoutBinding?.root)
   }

   protected fun setUpToolbar(var title : String?, var rightDrawable : Int ) {  }

}


class MainActivity : BaseActivity() {

 override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

       setContentView(R.layout.main_activity)
       setUpToolbar(“Title1” , R.drawable.main_activity_drawable) 
}

class SyncActivity : BaseActivity() {   
    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    setContentView(R.layout.sync_activity)
    setUpToolbar(“Title2” , R.drawable.sync_activity_drawable) 
}