ActionBarCompat – Part 4

In the previous article we began converting our code to work with ActionBarCompat, but there are still some further changes required to get things working. In this article we’ll complete the code migration.

The next thing that we must do is change our ActionMode handling because ActionMode is unsurprisingly tied in to ActionBarCompat. Starting an ActionMode is simply a case of changing the method call to it’s support variant. So onOptionsItemSelected() changes from:

to:

The next thing that we must do is change our ActionView implementation. The existing code for this is:

While the import change has already converted most of this, the highlighted line does not work because the getActionView() method was added in API 11 so is unavailable to us. We can get around this thanks to a utility class from the compat library named MenuItemCompat which provides implementations of some of the ActionProvider / ActionView related methods which were added in API 11. In our case, we need the getActionView() method, and this is implemented as a static method which takes a single, MenuItem argument:

The final thing that we need to do is change the layout resources that we use for our Spinner Adapters:

Instead of android.R.layout.simple_spinner_dropdown_item we should use a layout provided by the library:

There is also a bug in the original code that we’re fixing here. We should be specifying a themed Context in the first argument of the SpinnerAdapter constructor, and we can obtain this from the support ActionBar implementation (Thanks to Chris Banes for pointing this out).

Our code migration to ActionBarCompat, and our project will now compile and run on devices back to API 7. However, things are not completely seamless and in the concluding article in this series we’ll compare things on different devices, and cover some of the differences that you should be aware of when using ActionBarCompat.

The source code for this article is available here.

© 2013 – 2014, Mark Allison. All rights reserved. This article originally appeared on Styling Android.

Portions of this page are modifications based on work created and shared by Google and used according to terms described in the Creative Commons 3.0 Attribution License

Creative Commons License
ActionBarCompat – Part 4 by Styling Android, unless otherwise expressly stated, is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Terms and conditions beyond the scope of this license may be available at blog.stylingandroid.com.

Tags: ,

3 Responses to “ActionBarCompat – Part 4”

  1. Bernardo says:

    hey mark, the link for source code is broken, would you repair it? anyway great post.

  2. Immran says:

    Hi.. When i run this project in Android API level 8. It crashes and i got the error like “java.lang.NoClassDefFoundError: com.stylingandroid.basicactionbar.MainActivity”

Leave a Reply