This article translated this article:Using the Android Action Bar (ActionBar)-Tutorial
1, Actionbar's introduction
Actionbar is located at the top of the activity and can be used to display the activity's title, Icon, actions, and some view for interaction. It can also be used for navigation of applications.
ActionBar is added to the SK in Android 3.0 (API 11), there are two options for using ActionBar in a lower version: using http://actionbarsherlock.com or using the support Library v7.
Here is an interface that uses Actionbar:
Where [1] is the Actionbar icon, [2] is the two action button, [3] is the overflow button
2. Using Actionbar
To develop a program API11 the following, you must first specify that the theme of application or activity in the Androidmanifest.xml is Theme.holo or its subclasses, otherwise you will not be able to use Actionbar.
2.1 Creating actions
Actions, which are each interaction item in Actionbar, can be created in code or specified in an XML file (located at Res/menu). The method for defining an action in the menu resource file is as follows:
<menu xmlns:android= "Http://schemas.android.com/apk/res/android" > <item android:id= "@+id/ Action_refresh "android:orderincategory=" "android:showasaction=" Always " android:icon=" @ Drawable/ic_action_refresh " android:title=" Refresh "/> <item android:id=" @+id/action_settings " android:title=" > "Settings"
The Showasaction property is used to define how each action is displayed, always representing
Always appear in Actionbar, if the screen space is not enough to display, ifroom indicates that the screen space is sufficient to display in Actionbar, not enough to show in overflow, never is always displayed in overflow.
The action code that creates Ctionbar in activity is in Oncreateoptionsmenu (), and the following code shows the creation process:
@Override Public Boolean oncreateoptionsmenu (Menu menu) { Menuinflater inflater = Getmenuinflater (); Inflater.inflate (R.menu.mainmenu, menu); return true;
2.2 Action's button interaction
If an action is clicked, the onoptionsitemselected () in the activity is called. The passed-in parameter of the function is a MenuItem. By judging the ID of the MenuItem, you can confirm which action was clicked. The following code shows the use of the function.
Override Public Boolean onoptionsitemselected (MenuItem item) { switch (Item.getitemid ())} { //action with ID Action_refresh is selected case R.id.action_refresh: toast.maketext (This, "Refresh selected", Toast.length_short) . Show (); break; Action with ID action_settings is selected case r.id.action_settings: toast.maketext (This, "settings Selected ", Toast.leng . Show (); break; Default: Break ; } return true;
Oncreateoptionsmenu () will only be called once. If you want to change the menu, you can call Invalidateoptionsmenu (), which will cause oncreateoptionsmenu () to be called again.
3. Custom Actionbar
3.1 Changing the display of Actionbar
The ways to show and hide Actionbar at run time are as follows:
You can change the text that appears next to the program icon, as follows:
3.2 Hide navigation buttons
You can use the following code to hide the navigation buttons.
GetWindow (). Getdecorview ().
3.3 Using full-screen mode
For Android 4.4 (API 19) applications, you can use full-screen mode, as shown in the following code.
This method hides the system bars and resize the content private void Hidesystemui () { GetWindow (). Getdecorview (). setsystemuivisibility (View.system_ui_flag_layout_fullscreen | View.system_ui_flag_hide_navigation//HIDE nav bar | View.system_ui_flag_fullscreen//Hide status bar //Remove the following FLAG for version < API | view.system_ui_flag_immersive);
3.4 Using the split action Bar
When the screen is very narrow (as in Portra mode), you can use the split action Bar to display all the actions at the bottom of the screen so that more meaningful elements such as navigation, headings, and so on are displayed at the top of the activity.
Enable split Action Bar to define android:uioptions= "Splitactionbarwhennarrow" in Androidmanifest.xml
4. Add action to Action bar in fragment
Call Sethasoptionsmenu (True) in OnCreate (). The Android framework calls Oncreateoptionsmenu () in Fragement to add item to the activity's menu.
5. Dynamic Set Action Bar
5.1. Customize the view displayed in the Action Bar
You can add a custom view, such as a button or text, to the action bar.
You can use Actionview's Setcustomview and then use Setdisplayoptions (actionbar.display_show_custom) to enable custom view.
Example: First define a layout file that contains the EditText.
<?xml version= "1.0" encoding= "Utf-8"? ><edittext xmlns:android= "http://schemas.android.com/apk/res/ Android " android:id=" @+id/searchfield " android:layout_width=" match_parent " android:layout_height=" Match_parent "
The following code adds the above layout file to an activity's action bar.
Package Com.vogella.android.actionbar.customviews;import Android.app.actionbar;import Android.app.Activity;import Android.os.bundle;import Android.view.keyevent;import Android.widget.edittext;import Android.widget.TextView; Import Android.widget.textview.oneditoractionlistener;import Android.widget.toast;public class MainActivity extends Activity {@Override protected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); ActionBar ActionBar = Getactionbar (); Add the custom view to the Action Bar Actionbar.setcustomview (R.layout.actionbar_view); EditText search = (EditText) Actionbar.getcustomview (). Findviewbyid (R.id.searchfield); Search.setoneditoractionlistener (New Oneditoractionlistener () {@Override public boolean oneditoraction (TextView V, int ActionId, keyevent event) {Toast.maketext (Mainactivity.this, "Search triggered", Toast . Length_long). Show (); return false; } }); Actionbar.setdisplayoptions (Actionbar.display_show_custom | Actionbar.display_show_home); }}
Full Source Download location:Customize the layout of the Android Action bar
5.2. Action View
The Action view control can replace the action button icon on the Action bar. You can use this feature to replace an action item with a ProgressBar. You can define a layout file or WIDG as Action view by Android:actionlayout or Android:actionviewclass.
Action view uses the following.
First, there are two layout files, the first one for the action view
<?xml version= "1.0" encoding= "Utf-8"? ><progressbar xmlns:android= "http://schemas.android.com/apk/res/ Android " android:id=" @+id/progressbar2 " android:layout_width=" Wrap_content "
The second one for the menu setting
<menu xmlns:android= "Http://schemas.android.com/apk/res/android" > <item android:id= "@+id/menu_ Settings " android:orderincategory=" android:showasaction= "Always " android:title= "Settings" /> <item android:id= "@+id/menu_load" android:icon= "@drawable/navigation_refresh" android:orderincategory= "" android:showasaction= "Always "
The activity code is as follows:
Package Com.vogella.android.actionbar.progress;import Android.app.actionbar;import Android.app.activity;import Android.os.asynctask;import Android.os.bundle;import Android.view.menu;import Android.view.MenuItem;public class Mainactivity extends Activity {private MenuItem MenuItem; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); ActionBar ActionBar = Getactionbar (); Actionbar.setdisplayoptions (Actionbar.display_show_home | Actionbar.display_show_title | Actionbar.display_show_custom); @Override public boolean Oncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (R.menu.main, menu); return true; } @Override public boolean onoptionsitemselected (MenuItem item) {switch (Item.getitemid ()) {case R.id.menu_load: MenuItem = Item; Menuitem.setactionview (R.layout.progressbar); Menuitem.expandactionview (); Testtask task = new Testtask (); Task.execute ("test"); Break Default:break; } return true; } private class Testtask extends Asynctask<string, Void, string> {@Override protected String doinbackground ( String ... params) {//simulate something long running try {thread.sleep (2000); } catch (Interruptedexception e) {e.printstacktrace (); } return null; } @Override protected void OnPostExecute (String result) {Menuitem.collapseactionview (); Menuitem.setactionview (NULL); } };}
Full-Source:dynamically changing the Actionbar icon
6. Action Provider
Action provider provides a way to provide multiple ways of interacting in a single component. It can be used to create an action view, to dynamically popup a submenu, to handle an action call event. Base class is Actionprovider
The Android platform currently offers two types of action Provider:mediarouteactionprovider and Shareactionprovider.
The following example calculates the usage of Shareactionprovider. Use this ACTION provider to get the program from the intent that registered Intent.action_send.
First define the menu XML file and set the item's android:actionproviderclass= "Android.widget.ShareActionProvider"
<?xml version= "1.0" encoding= "Utf-8"? ><menu xmlns:android= "Http://schemas.android.com/apk/res/android" > <item android:id= "@+id/menu_share" android:title= "Share" android:showasaction= "Ifroom" android:actionproviderclass= "Android.widget.ShareActionProvider"/> <item android:id= "@+id/item1" android:showasaction= "Ifroom" android:title= "more entries ..." >
Set up a intent that contains the data you want to share, and send it.
@Override Public Boolean oncreateoptionsmenu (Menu menu) { getmenuinflater (). Inflate (R.menu.activity_main, menu); Get the Actionprovider for later usage Provider = (Shareactionprovider) menu.finditem (r.id.menu_share) . Getactionprovider (); return true; } @Override Public Boolean onoptionsitemselected (MenuItem item) { switch (Item.getitemid ()) { case R.id.menu_share: doshare (); break; Default: Break ; } return true; } public void Doshare () { //populate the share intent with data intent intent = new Intent (intent.action_send);
intent.settype ("Text/plain"); Intent.putextra (Intent.extra_text, "This was a message for you"); Provider.setshareintent (Intent);
7. Navigating with program icons
7.1. Use the program icon as home icon
The left icon of Action Bar is called home icon, and you can set an action for this icon. The recommended practice is to return to the home activity when the icon is pressed.
The following code describes the use of home Aciton on the previous version of Android4.1. The key point is to use Android in Onoptionsmenuitemselected (). R.id.home and enable Actionbar's Homeicon. Secondactivity the mainactivity as homeactivity.
Package Com.vogella.android.actionbar.homebutton;import Android.os.bundle;import Android.app.actionbar;import Android.app.activity;import Android.content.intent;import Android.view.menu;import Android.view.MenuItem;public Class Secondactivity extends Activity {@Override protected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Enable the home button ActionBar ActionBar = Getactionbar (); Actionbar.sethomebuttonenabled (TRUE);//or use actionbar.setdisplayhomeasupenabled (true); @Override public boolean Oncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (R.menu.main, menu); return true; } @Override public boolean onoptionsitemselected (MenuItem item) {switch (Item.getitemid ()) {case Android. R.id.home:intent Intent = new Intent (this, mainactivity.class); Intent.setflags (Intent.flag_activity_clear_top); StartActivity (Intent); Break Something Else Case r.id.action_settings:intent = new Intent (this, thirdactivity.class); StartActivity (Intent); Default:break; } return super.onoptionsitemselected (item); }}
On Android 4.1 or later, you can set the Parentactivityname property in Androidmanifest.xml as follows.
Full code: Navigate using Actionbar's Homeicon
Above is some basic usage of actionbar. Since Actionbar is often used in conjunction with other controls such as Drawer,tab, I'll write an article about Actionbar's collocation with other controls and provide the source code as a fallback.