How to replace ActionBar with Toolbar in android studio step by step example tutorial android support v7 widget Toolbar.
Android lollipop comes with lots of new features and one of them is Toolbar widget. Toolbar widget is the alternative option for ActionBar with multiple features included like icon adding management, text title management etc. With the toolbar widget android developers can easily create android apps with material design look which is most popular in now days. So here is the complete step by step tutorial for Android custom ToolBar layout with Material Design example tutorial.
Follow all the below steps very carefully to add Toolbar Widget in your project.
1. Open your Project’s build.gradle ( Module : app ) and add com.android.support:appcompat-v7:23.4.0 library file.
2. Here is the code to add appcompat library inside build.gradle file.
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.4.0' }
Screenshot after add this code into build.gradle file.
3. Open your project’s styles.xml file and change the theme with below theme.
<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
4. Open colors.xml file and set primary color and secondary color for toolbar.
<?xml version="1.0" encoding="utf-8"?> <resources> <!-- Edit primary color code to change your Toolbar color --> <color name="colorPrimary">#FF9800</color> <color name="colorPrimaryDark">#E65100</color> <color name="colorAccent">#FF4081</color> </resources>
Android custom ToolBar layout with Material Design example tutorial.
Code for MainActivity.java file.
package com.android_examples.toolbar_android_examplescom; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; public class MainActivity extends AppCompatActivity { Toolbar toolbar ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.toolbar1); toolbar.setTitle("Custom Toolbar"); setSupportActionBar(toolbar); } }
Code for activity_main.xml layout file.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.android_examples.toolbar_android_examplescom.MainActivity" android:background="#ffff"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar1" android:layout_width="fill_parent" android:layout_height="58dp" android:background="?attr/colorPrimary" android:minHeight="?attr/actionBarSize" android:titleTextColor="#ffffff"> </android.support.v7.widget.Toolbar> </RelativeLayout>
Screenshots: