Tuesday, 5 May 2015

Android Material Design - Toolbar Example


Android's new Operating System Lollipop uses a new User Experience which is called as Material Design. Many new stuffs have been introduced in Material Design, and one of them is Toolbar which is the replacement of ActionBar.


Toolbar was introduced in Android Lollipop, API 21 which is available for applications targeting API 21 and above. But to support lower android versions , you have to use AppCompat Library i.e android.support.v7.widget.Toolbar class. 

You can customize the Toolbar i.e change its color, showing menu icons or logo etc.


Using Toolbar

First step you need to implement is to disable the default action bar in your app. To do this go to styles.xml file and make sure the parent of the style theme is Theme.AppCompat.NoActionBar.

Make sure your code matches to this snippet.





Now, Make sure that appcompat library has been added. In Android Studio , add the support library to the application's build.gradle file under dependencies section.


That's great. Now its time to add toolbar to your layout file.


<android.support.v7.widget.Toolbar
    android:id="@+id/my_awesome_toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#ff9b1cff"
    android:minHeight="?attr/actionBarSize">

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


You are almost done. Now go to your MainActivity file and instantiate the Toolbar. 



public class MainActivity extends ActionBarActivity {

    @Override    
    public void onCreate(Bundle saved) {

        super.onCreate(saved);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
        setSupportActionBar(toolbar);
   }
}

So here you go. You have successfully integrated toolbar in your app. For any problems, please mention in the comment box.


No comments:

Post a Comment