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.
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:
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:
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:

If you need to access Action Bar programatically, you will call getSupportActionBar()
In next episodes, I will explain how to include an action view, change action mode or even integrate Navigation Drawer. So please, stay tuned!
Coding
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:
1
2
3
4
| < application android:label = "@string/app_name" android:icon = "@drawable/ic_launcher" android:theme = "@style/Theme.AppCompat.Light.DarkActionBar" > |
1
2
3
4
5
6
7
8
9
10
| 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); } } |
But what if we want to add some menu items? It’s pretty much the same, but some attributes require our custom namespace:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| > < 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 > |
Now you can inflate the menu:
1
2
3
4
5
| @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!
Comments
Post a Comment