For those of you not in the loop, theActionBar a bar located at the very top of an activity that can show the activity icon, title, and actions that can be triggered (hence its name): things like additional views, other interactive buttons, app navigation, and so on and so forth. This replaces the older Android OptionsMenu that was opened when a user pressed the hardware Option button; theActionBar is preferable to it as it is clearly visible and shows the user what they can do and where they can do it. Read on for how to implement this in your app!
You use an activity to populate the ActionBarin its onCreateOptionsMenu()
method. These entries are called actions, and they’re normally defined in a typical XML resource file. TheMenuInflator class is used to inflate those actions set in the XML file and add them to an ActionBar.
You can use the showAsAction attribute to control how the action is displayed: for example, theifRoom
attribute labels the action as one that is only shown if there is enough room available for it.
04 | android:id = "@+id/action_settings" |
05 | android:orderInCategory = "100" |
06 | android:showAsAction = "always" |
07 | android:icon = "@drawable/ic_action_search" |
08 | android:title = "settings" /> |
10 | android:id = "@+id/action_kablam" |
11 | android:title = "Kablam!" > |
Once you have the XML ready to go, you can use the menuInflater()
method to access them:
2 | public boolean onCreateOptionsMenu(Menu menu) { |
3 | MenuInflater inflater = getMenuInflater(); |
4 | inflater.inflate(R.menu.mainmenu, menu); |
Reacting to an action is as follows: once an action is selected, the onOptionsItemSelected()
method gets called. It takes the selected action as a parameter, and based on this you decide what it should do.
02 | public boolean onOptionsItemSelected(MenuItem item) { |
03 | switch (item.getItemId()) { |
05 | Toast.makeText( this , "Number 1 on deck!" , Toast.LENGTH_SHORT) |
09 | Toast.makeText( this , "Number 2 on deck!" , Toast.LENGTH_SHORT) |
Also, a couple of things to note at this juncture: to change menu items, you have to use theinvalidateOptionsMenu()
method, since onCreateOptionsMenu()
is called only once. Also, you can search by id using the findItem()
method of the Menu class – something handy to know!
Conclusion
And there it is – a quick and dirty introduction to using
ActionBars in Android. There’s a whole lot more you can do with them, but that goes beyond the scope of this introduction – we do cover
ActionBar in detail in our
Android Bootcamp class. So go forth, hit the API, and give your app the much-vaunted power of the
ActionBar! Also, check out our new
Android tutorial section!
No comments:
Post a Comment