A Toolbar
is a generalization of ActionBar
for use within application layouts. While an ActionBar
is traditionally part of an Activity's
opaque window decor controlled by the framework, a Toolbar
may be placed at any arbitrary level of nesting within a view hierarchy. It can be added by performing the following steps:
Make sure the following dependency is added to your module's (e.g. app's) build.gradle file under dependencies:
compile 'com.android.support:appcompat-v7:25.3.1'
Set the theme for your app to one that does not have an ActionBar
. To do that, edit your styles.xml file under res/values
, and set a Theme.AppCompat
theme.
In this example we are using Theme.AppCompat.NoActionBar
as parent of your AppTheme
:
<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
<item name="colorPrimary">@color/primary</item>
<item name="colorPrimaryDark">@color/primaryDark</item>
<item name="colorAccent">@color/accent</item>
</style>
You can also use Theme.AppCompat.Light.NoActionBar
or Theme.AppCompat.DayNight.NoActionBar
, or any other theme that does not inherently have an ActionBar
Add the Toolbar
to your activity layout:
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"/>
Below the Toolbar
you can add the rest of your layout.
In your Activity
, set the Toolbar
as the ActionBar
for this Activity
. Provided that you're using the appcompat library and an AppCompatActivity
, you would use the setSupportActionBar()
method:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//...
}
After performing the above steps, you can use the getSupportActionBar()
method to manipulate the Toolbar
that is set as the ActionBar
.
For example, you can set the title as shown below:
getSupportActionBar().setTitle("Activity Title");
For example, you can also set title and background color as shown below:
CharSequence title = "Your App Name";
SpannableString s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(Color.RED), 0, title.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
getSupportActionBar().setTitle(s);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.argb(128, 0, 0, 0)));