Develop Your Own Android Action Bar: A Step-by-Step Tutorial
Experience the freedom of design with our Android Custom Action Bar tutorial! Learn how to create your own action bar with a personalized layout and give your app a unique touch. Explained step by step – perfect for developers of all experience levels.
Configuring Android Custom Action Bar
To customize an ActionBar, we first need to configure the theme in the file res/values/styles.xml and set the theme for the respective activity class in the AndroidManifest.xml. Here’s the XML layout for it:
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme -->
</style>
<style name="CustomTheme" parent="Theme.AppCompat.Light">
<item name="contentInsetStart">0dp</item>
<item name="contentInsetEnd">0dp</item>
</style>
</resources>
When using the AppTheme style for our activity, a null pointer exception is triggered as it explicitly specifies the NoActionBar theme. Therefore, we’re using the CustomTheme style in this project. The contentInsetStart and contentInsetEnd values are the padding values. Note that we’re using AppCompatActivity for maximum compatibility with Android versions
before 3.0.
Custom Action Bar Layout
Below is the view layout assigned to the ActionBar of our MainActivity:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TableRow>
<!-- Your ImageButtons and TextView go here -->
</TableRow>
</TableLayout>
The view layout consists of two ImageButtons representing forward and backward, and a TextView in the middle.
Project Structure for Custom Action Bar
The activity_main.xml is an empty RelativeLayout since our focus here is on the ActionBar.
The MainActivity.java looks like this:
// Your Java code here
In this code, we’re using support libraries. Hence, we’ve used getSupportActionBar() instead of getActionBar(). To add a custom layout to the ActionBar, we’ve called the following two methods on getSupportActionBar():
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setDisplayShowCustomEnabled(true);
Using setCustomView()
inflates the ActionBar with a custom view. To set onClickListeners for the ActionBar buttons, we need to first retrieve the CustomView with getCustomView()
. In this tutorial, we’ve programmed the backward button to close the activity and the
forward button to display a toast.
Add the following line in the AndroidManifest.xml within the application tag:
android:theme="@style/CustomTheme"
That’s it for today! We hope this tutorial helped you create a custom action bar for your Android app. If you have any questions, please leave a comment. Until next time!