How to Create a Custom ActionBar, 40/100 Days of…
The ActionBar is essential to the UI of an Android App. It can be used to display key information about the Activity.
In this tutorial, I show you how to create a basic, customizable ActionBar for your apps. I’ve also included a video at the bottom of the page and a link to the source code here.
NOTE: This tutorial assumes you have basic understanding of Android Studio and file management.
Step 1: Add a new custom layout for the ActionBar. This will be used to style the ActionBar
- Right-click the app/res/layout folder and select New > XML > Layout
- In this example, I saved mine as custom_action_bar.xml (click below)
Step 2: Configure your Activity to use the layout to style the ActionBar using methods from the ActionBar class
- Open your MainActivity.java file and include the code below
package com.example.actionbar; import android.os.Bundle; import android.support.v7.app.ActionBar; //Import the ActionBar class to use the getSupportActionBar() method import android.support.v7.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //These methods allow for setting a custom ActionBar and setting the view using a custom layout getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); getSupportActionBar().setCustomView(R.layout.custom_action_bar); } }
Step 3: Configure the custom layout. For this example, we are centering the ActionBar and changing the default textColor to Yellow.
- Open your custom layout (mine is named custom_action_bar.xml)
- Style your new ActionBar text using the code below and you’re all set (click the image below the code)
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:gravity="center" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Our Main Activity :)" android:textColor="#FFFF00" style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"/> </LinearLayout>
Have fun designing ActionBars for your apps! For more details, watch the video below! For the source code, click here.
-CF