[Tutorial] Android ActionBar with Material Design and search field

Welcome!

In this post, I’ll show you how to create a custom and simple ActionBar/Toolbar to your Android application with Material Design.

And then we’ll add a custom search field to the ActionBar.

I - About Android Tutorials

I’ll be creating a big number of Android tutorials, showing you how to use nice libraries, UI, tips, and more.

I’ll be using Android Studio and Gradle in all tutorials.

If you need some help with any Android lib or feature, feel free to comment here and if possible, I can write a new tutorial about it :)

Source Codes:

Get updates Follow @aron-bordin
Star it: Star
Contribute: Fork
Download: Download

II - First, why??

Ok, you probably know that Android already provides a default ActionBar and search field, so why recode them?

Sometimes it’s necessary to do some deep modifications, create your own UI or even work with you own features.

So, in these cases, reusing something ready may not be the best choice. In this post I’ll show you how to create a Material Design ActionBar/Toobar with a search EditText.

III - Creating a new project

Ok, this first step is easy. Just open you Android Studio and create a new a blank activity. First, remove some auto-generated code from you activity_main.xml:

<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=".MainActivity">
</RelativeLayout>

And as we are going to create our own ActionBar, go to styles.xml and edit to

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/ColorPrimary</item>
        <item name="colorPrimaryDark">@color/ColorPrimaryDark</item>
        <item name="colorAccent">@color/ColorPrimaryDark</item>
    </style>

</resources>

Now the application has no ActionBar. So, let’s create a new one!

IV - Creating a custom Android Material Design ActionBar

Create it in a separated file.

Create a toolbar.xml inside your layouts folder, extending a LinearLayout.

New layout

This is a simple layout to represents our new ActionBar.

This ActionBar will have some features, so we’ll call it as a Toolbar from now. You can check my toolbar.xml here:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:elevation="4dp"
    android:background="#00FF00">

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

To display this new Toolbar on you Android application, add the following code to your activity_main.xml:

<include
        android:id="@+id/toolbar"
        layout="@layout/toolbar">
        </include>

Now, if you run your app, you will see a simple green(horrible green :P ) bar in the top of the app.

We need to say to the Activity that this “green bar” is an ActionBar.

Open you MainActivity.java and create the following variable:

private Toolbar mToolbar;

And inside your onCreate method, add these lines:

mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);

Now you can run your app and see the that toolbar is working fine!

V - Styling you App

It’s possible to change the notification bar color and others options with Android >= 5.0. Unfortunately it won’t work with pre-Lollipop devices.

In this image you can see some useful places to style. In this app we’ll be changing the  colorPrimary and colorPrimaryDark.

Create the file colors.xml inside your values folder to add the default colors:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="ColorPrimary">#00FF22</color>
    <color name="ColorPrimaryDark">#0000FF</color>
</resources>

And now just update your toolbar.xml and set the line:

  android:background="@color/ColorPrimary">

Now, let’s add a search bar.

Download the desired icons, one called ic_open_search and a ic_close_search.

I’m using these ones:

To add the search icon to the Toolbar, edit the menu_main.xml inside menu folder.

<menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">

    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never" />

    <item
        android:id="@+id/action_search"
        android:title="@string/search"
        android:orderInCategory="200"
        android:icon="@drawable/ic_open_search"
        app:showAsAction="ifRoom"
        />
</menu>

To search we need to add a EditText inside the ActionBar. So, create the file search_bar.xml inside you layouts folder.

[code language="xml"]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <EditText
        android:id="@+id/edtSearch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:imeOptions="actionSearch" />

</LinearLayout>

We use the meOptions=”actionSearch” so the keyboard will show a search icon on Enter button.

VIII - Coding the search button

Let’s code it.

Add the following private variables inside your MainActivity.java:

private MenuItem mSearchAction;
private boolean isSearchOpened = false;
private EditText edtSeach;

The first thing is to get the action_search edit. Override this method:

  @Override
  public boolean onPrepareOptionsMenu(Menu menu) {
    mSearchAction = menu.findItem(R.id.action_search);
    return super.onPrepareOptionsMenu(menu);
  }

To handle the click in the search button, edit the onOptionsItemSelected method.

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    switch (id) {
      case R.id.action_settings:
        return true;
      case R.id.action_search:
        handleMenuSearch();
        return true;
    }

    return super.onOptionsItemSelected(item);
  }

The handleMenuSearch() will open and close the search EditText.

Take a look in my handleMenuSearch, it’s commented to help you to understand.

protected void handleMenuSearch(){
    ActionBar action = getSupportActionBar(); //get the actionbar

    if(isSearchOpened){ //test if the search is open

        action.setDisplayShowCustomEnabled(false); //disable a custom view inside the actionbar
        action.setDisplayShowTitleEnabled(true); //show the title in the action bar

        //hides the keyboard
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(edtSeach.getWindowToken(), 0);

        //add the search icon in the action bar
        mSearchAction.setIcon(getResources().getDrawable(R.drawable.ic_open_search));

        isSearchOpened = false;
    } else { //open the search entry

        action.setDisplayShowCustomEnabled(true); //enable it to display a
        // custom view in the action bar.
        action.setCustomView(R.layout.search_bar);//add the custom view
        action.setDisplayShowTitleEnabled(false); //hide the title

        edtSeach = (EditText)action.getCustomView().findViewById(R.id.edtSearch); //the text editor

        //this is a listener to do a search when the user clicks on search button
        edtSeach.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    doSearch();
                    return true;
                }
                return false;
            }
        });


        edtSeach.requestFocus();

        //open the keyboard focused in the edtSearch
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(edtSeach, InputMethodManager.SHOW_IMPLICIT);


        //add the close icon
        mSearchAction.setIcon(getResources().getDrawable(R.drawable.ic_close_search));

        isSearchOpened = true;
    }
}

You’d add this method too, to close the search entry with the backbutton:

@Override
public void onBackPressed() {
  if(isSearchOpened) {
    handleMenuSearch();
    return;
  }
  super.onBackPressed();
}

To this tutorial, I created an empty doSearch method.

You can anything here and do your custom search:

private void doSearch() {
//
}  

Now, it’s you can test and check it running!

Here you can see the app runinng on Android 4.1:

You can get the source code and APK in the github repository. That’s it, thx for reading.

If you have any problem/suggestion/or anything, feel free to comment here :)

Aron Bordin

Aron Bordin

Aron Bordin
Computer Science Student and AI researcher. Always coding something fun :)

[Tutorial] Developing Android Background Services

### Welcome!In this post, I'll show you how to develop background services on Android Studio. We'll see two type of services: `Service` a...… Continue reading