I have to create one Toolbar for each activity in my Android app?

13,182

Solution 1

Toolbar is just a view and you have to add it to your each Activity in which you want to show it.

One way is to just put it in a separate layout file and include in your Activity layout.

toolbar.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    >

</android.support.v7.widget.Toolbar>

Now in your Activity layout where you want to add it just include like this:

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

Solution 2

You can also extend Your activity class with AppCompatActivity instead of Activity

Share:
13,182
Daniel Filho
Author by

Daniel Filho

Updated on July 21, 2022

Comments

  • Daniel Filho
    Daniel Filho almost 2 years

    I have this doubt about new Toolbar in Android.

    I have to create one Toolbar for each activity in my app or there are a best practice to create one Toolbar for all activities?

    I try create a Singleton inflating a layout and search a view ID to create a toolbar and return the same instance for all activities, but this don't work.

    Can anybody help me? :S

  • Sharjeel
    Sharjeel over 8 years
    @DanielFilho you can accept it as Answer if it works for your.
  • Latrova
    Latrova about 8 years
    @Sharj I need to set the Id for every include?
  • Zvonimir Peran
    Zvonimir Peran about 7 years
    Yes, you do, if you want to access it in Java code.
  • blueware
    blueware almost 7 years
    Actually, you don't have to use the Id for every include. You only need to set it up in its layout and then include it in other activities
  • Stephen M -on strike-
    Stephen M -on strike- almost 6 years
    Just some code with no explanation isn't very helpful. Where does this code go? How do you access this code from your Activities? etc.