· 2 min read
ActionBarCompat (Part 1): How to use
Google has released a new version of its Support Library and it finally includes ActionBarCompat. We don’t know if ActionBarSherlock days of glory are over, but it’s true that the Android team has been working on ActionBarCompat so hard that it deserves at least one chance.
Coding ActionBarCompat
So let’s create a new project using API 18 and add the project under sdk\extras\android\support\v7\appcompat folder. I will set light theme with dark Action Bar. It is as easy as usual:
<application
android:label="@string/app_name"
android:icon="@drawable/ic_launcher"
android:theme="@style/Theme.AppCompat.Light.DarkActionBar">
</application>
Now your activity needs to extend ActionBarActivity instead. This activity is based on FragmentActivity, so you will be able to use fragments without any extra effort. It’s easy:
public class MainActivity extends ActionBarActivity {
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
And here it is!
But what if we want to add some menu items? It’s pretty much the same, but some attributes require our custom namespace:
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_refresh"
android:title="@string/action_refresh"
android:icon="@drawable/ic_action_refresh"
app:showAsAction="ifRoom" />
<item
android:id="@+id/action_search"
android:title="@string/action_search"
android:icon="@drawable/ic_action_search"
app:showAsAction="ifRoom" />
<item
android:id="@+id/action_settings"
android:title="@string/action_settings"
app:showAsAction="never" />
</menu>
That’s the case of showAsAction, or actionViewClass, which will be explained in next episode. Not too difficult, right?
Now you can inflate the menu:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
If you need to access Action Bar programatically, you will call getSupportActionBar()
Conclusion
Using ActionBarCompat is almost as easy as native bar, and even similar to ActionBarSherlock, but there are a few differences that must be know. This first tutorial covered the most simple integration. You can find full code on Github.
In next episodes, I will explain how to include an action view, change action mode or even integrate Navigation Drawer. So please, stay tuned!