Android visual effects: adding a custom toolbar

The options that you are given to customise your Android app are limitless. Every single thing from a button to a navigation drawer to the splash screen can be customised to whatever specification you may have in mind. In this post, I shall be talking about the toolbar, and how to customise it.

The toolbar in any Android app stays on top and is visible almost all the time to the user. Therefore, it is necessary to ensure that the toolbar is pretty. Ill be providing code to create your own custom toolbar in the easiest way possible.

First things first: you need to have a toolbar.xml. This file will go inside the layout folder.
(app\src\main\res\layout)
Copy and paste this code into the toolbar.xml file you just created

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

Now include the toolbar into the layout file of any activity you want the toolbar for, like this:

<LinearLayout  
          android:layout_width="fill_parent"  
          android:layout_height="wrap_content"  
          android:layout_alignParentTop="true"  
          android:orientation="vertical">  
          <include  
            android:id="@+id/toolbar"  
            layout="@layout/toolbar" />  
       </LinearLayout>  

 Great. You should now be presented with an empty toolbar. Filling this toolbar up with a back button and a title is easy. Go to the activity.java file and add this code to the onCreate() method:


 Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true); //if you want a title 
        getSupportActionBar().setTitle("Title goes here");

Don't forget to import the required libraries. Don't worry, Android Studio will automatically point them out for you. The colour of the toolbar is going to be whatever colour you have as "colorPrimary". You should be able to easily change this. If you can't though, I'll be back with a second post on dealing with styles.   

And that's it. I'll come back with more. 

Comments

Popular Posts