ActionBarCompat (Part 2): Action Views

In the first part of this tutorial series I talked about how to use ActionBarCompat in our projects. Once you have set the theme, extended ActionBarActivity and added some menu items, it’s time to add an Action View to your bar.

< Part 1: How to use ActionBarCompat

Adding an Action View to ActionBarCompat

Action Views are those helpful views that can be added over the Action Bar when the user presses a menu item. The most typical is the Search View, and that’s the one I’m explaining here. Every Action View has been added to the support library, so you will need to add the reference to it instead of the one in the SDK:

[xml]

<item

android:id="@+id/action_search"

android:title="@string/action_search"

android:icon="@drawable/ic_action_search"

app:actionViewClass="android.support.v7.widget.SearchView"

app:showAsAction="ifRoom" />

[/xml]

Recovering this Action View from code is a little bit different. MenuItemCompat will do the hard work this time:

[java]

private SearchView mSearchView;

@Override

public boolean onCreateOptionsMenu(Menu menu) {

getMenuInflater().inflate(R.menu.main, menu);

MenuItem searchItem = menu.findItem(R.id.action_search);

mSearchView = (SearchView) MenuItemCompat.getActionView(searchItem);

Want to learn Kotlin? Check my free guide to create your first project in 15 minutes! GET THE FREE GUIDE

return true;

}

[/java]

Now it’s time to show the search view when the user presses the magnifying glass icon. No difference with native Action Bar:

[java]

@Override

public boolean onOptionsItemSelected(MenuItem item) {

switch(item.getItemId()){

…

case R.id.action_search:

mSearchView.setIconified(false);

return true;

…

}

return false;

}

[/java]

You can add an OnQueryTextListener to detect user input on SearchView

[java]

public class MainActivity extends ActionBarActivity implements SearchView.OnQueryTextListener {

…

@Override

public boolean onCreateOptionsMenu(Menu menu) {

…

mSearchView = (SearchView) MenuItemCompat.getActionView(searchItem);

mSearchView.setOnQueryTextListener(this);

return true;

}

…

@Override

public boolean onQueryTextSubmit(String s) {

Toast.makeText(this, s, Toast.LENGTH_LONG).show();

return true;

}

@Override

public boolean onQueryTextChange(String s) {

return false;

}

}

[/java]

Conclusion

Apart from using some new classes and very little coding changes, the process of adding a new action view is similar and straightforward. If you have done this before, it will be easy.

For the next tutorial, I will explain how to replace ActionBarSherlock with ActionBarCompat. I will take my App Bandhook as basis to explain the full process.

Like this: Like Loading...