Reprint Please specify source: http://blog.csdn.net/guolin_blog/article/details/18234477
The main content of this article comes from Android Doc, I have done some processing after translation, English good friends can also directly read the original text.
Http://developer.android.com/guide/topics/ui/actionbar.html
The Action Bar is a new navigation bar feature that, after Android 3.0, is added to the system's API, which identifies the location of the user's current operating interface and provides additional user actions, interface navigation, and other functions. The advantage of using Actionbar is that it provides a global, unified UI interface that allows users to understand how to operate any software, and Actionbar can automatically adapt to screens of varying sizes. Here is an interface that uses Actionbar:
Where [1] is the Actionbar icon, [2] is a two action button, [3] is the overflow button.
Since the action bar was added to the version after 3.0, if you want to use Actionbar in the 2.x version, you need to introduce the support Library. However, before the 3.0 version of the market share is very small, here for the sake of simplicity we no longer consider to do backward compatibility, but only consider the usage of more than 4.0 version.
Add and remove Action Bar
The addition of Actionbar is very simple, Only the theme of application or activity that you specify in Androidmanifest.xml is Theme.holo or its subclasses, and projects created with Eclipse automatically designate application theme as Theme.hol O, so Actionbar is displayed by default. Create a new empty project and run it as shown in the results:
If you want to remove Actionbar, there are usually two ways, one is to designate theme as Theme.Holo.NoActionBar, to use a theme that does not contain actionbar, and to invoke the following methods in the activity:
ActionBar ActionBar = Getactionbar (); Actionbar.hide ();
Now rerun the program and you can see that the Actionbar is no longer displayed, as shown in:
Modify the icon and caption of the action bar by default, the system uses the image specified by the Icon property in <application> or <activity> as the Actionbar icon, but we can also change this default behavior. If we want to use another image as a actionbar icon, you can specify it in <application> or <activity> through the logo properties. For example, in the project's res/drawable directory, there is a picture of weather.png, which can be specified in Androidmanifest.xml:
<activity android:name= "com.example.actionbartest.MainActivity" android:logo= "@drawable/weather" ></activity>
Now run the program again, as shown in the results:
Ok,actionbar the icon has been modified successfully, then the title of the contents of how to modify it? It is also very simple to use the Label property to specify a string, as follows:
<activity android:name= "com.example.actionbartest.MainActivity" android:label= "Weather" Android:logo = "@drawable/weather" ></activity>
Now rerun the program and the results are as follows:
Add action button Actionbar can also provide action buttons related to the application's current functionality, which are displayed directly on the Actionbar as icons or text. Of course, if the button too much, Actionbar on the display, some of the extra buttons can be hidden inside the overflow (the right three points is the overflow button), click on the overflow button to see all the action button. When the activity starts, the system invokes the activity's Oncreateoptionsmenu () method to remove all the action buttons, and we just need to load a menu resource in this method. And all the action buttons are defined in the resource file. So let's take a look at how the menu resource file is defined, and the code looks like this:
<menu Xmlns:android= "Http://schemas.android.com/apk/res/android" xmlns:tools= "Http://schemas.android.com/tools" Tools: context= "Com.example.actionbartest.MainActivity" > <item android:id= "@+id/action_compose" android:i con= "@drawable/ic_action_compose" android:showasaction= "Always" android:title= "@string/action_compose"/> <item android:id= "@+id/action_delete" android:icon= "@drawable/ic_action_delete" Android:showasa Ction= "Always" android:title= "@string/action_delete"/> <item android:id= "@+id/action_settings" android:icon= "@drawable/ic_launcher" android:showasaction= "Never" android:title= "@string/action_settings" /></menu>
As you can see, here we define three action buttons through three <item> tags. There are also attributes in the <item> tag, where the ID is the unique identifier for the action button, and icon is used to specify the button's icons, title to specify the text that the button might display (the text is usually not displayed if the icon can be displayed). showasaction specifies where the button is displayed, mainly with the following values: Always means to be displayed forever in Actionbar, if the screen space is not enough to display, ifroom indicates that the screen space is sufficient to display in Actionbar, If not enough, it is shown in overflow, and never is always displayed in overflow. Next, rewrite the activity's Oncreateoptionsmenu () method, as shown in the following code:
@Overridepublic boolean Oncreateoptionsmenu (Menu menu) {menuinflater inflater = Getmenuinflater (); Inflater.inflate ( R.menu.main, menu); return Super.oncreateoptionsmenu (menu);}
This part of the code is simple enough to simply call the Menuinflater inflate () method to load the menu resource. Now rerun the program and the results are as follows:
As you can see, the Action_compose and Action_delete buttons have been shown in Actionbar, and action_settings This button is set to Showasaction due to the Never property. So is hidden in the overflow, just click on the overflow button to see it. Here we notice that the buttons displayed on the Actionbar have only one icon, and the text we specify in the title is not displayed. Yes, the content in title is usually only shown in overflow, and the title content is not displayed by default due to limited screen space in Actionbar. However, for the following reasons, even if the contents of title cannot be displayed, we should assign a title attribute to each item:
- When the remaining space in the Actionbar is insufficient, if the action button specifies the Showasaction property is Ifroom, the action button will appear in the overflow, at which point only the title can be displayed.
- If the action button is displayed in Actionbar, the user may look up the contents of the title by long pressing the action button.
Click event in response to action button when the user clicks on the action button, the system invokes the activity's onoptionsitemselected () method, through the method passed in the MenuItem parameter, we can call its getitemid () method is compared to the ID in the menu resource to identify which action button the user clicked on, such as:
@Overridepublic boolean onoptionsitemselected (MenuItem item) {switch (Item.getitemid ()) {case R.id.action_compose: Toast.maketext (This, "Compose", Toast.length_short). Show (); return true;case R.id.action_delete:toast.maketext (this , "Delete", Toast.length_short). Show (); return true;case R.id.action_settings:toast.maketext (this, "settings", Toast.length_short). Show (); return True;default:return super.onoptionsitemselected (item);}}
As you can see, we let each action button pop up with a toast when clicked, and now rerun the code, as shown in the following:
Navigation with the Action Bar icon enables the Actionbar icon navigation to allow users to switch between different interfaces based on the location of the current app. For example, a interface shows a list, click on an item and enter the B interface, then the B interface should enable the Actionbar icon navigation function, so you can go back to the A interface. We can enable the Actionbar icon navigation function by calling the Setdisplayhomeasupenabled () method, for example:
@Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Settitle ("Weather"); Setcontentview (R.layout.activity_main); ActionBar ActionBar = Getactionbar (); actionbar.setdisplayhomeasupenabled (true);}
Now rerun the program and the results are as follows:
As you can see, there is a left arrow on the left side of the Actionbar icon, which usually indicates the meaning of the return, so the simplest implementation is to add the finish () method to its Click event, as shown below:
@Overridepublic boolean onoptionsitemselected (MenuItem item) {switch (Item.getitemid ()) {case Android. R.id.home:finish (); return true;}}
When you click on the Actionbar icon, the system will also call the Onoptionsitemselected () method, and at this point the Itemid is android.r.id.home, so the finish () method is added here. Now it looks like the Actionbar navigation and back keys seem to be the same. Yes, if we simply finish, Actionbar navigation and back key function is exactly the same, but the Actionbar navigation is not designed to do so, and it and the function is still a bit different, for example.
Conversation list in the Inbox is the main interface, now we click on the first email will go to the Conversation1 details interface, and then click on the next message will go to the Conversation 2 details interface, Clicking on the next email will go to the Conversation3 details interface. OK, this time if we press the back button, we should return to the conversation 2 details interface, and then press the back key should return to the Conversation1 details interface, and then press the back key to return to conversation List. and Actionbar navigation should not show this behavior, no matter what we are currently in the conversation details interface, click the navigation button should go back to the Conversation list interface. This is the Actionbar navigation and back key in the design of the difference, then how to achieve such a function? In fact, it is not complicated to achieve the standard Actionbar navigation function only three steps away. The first step we've implemented is to call the Setdisplayhomeasupenabled () method and pass in true. The second step is to configure the parent activity in Androidmanifest.xml as follows:
<activity android:name= "com.example.actionbartest.MainActivity" android:logo= "@drawable/weather" > <meta-data android:name= "Android.support.PARENT_ACTIVITY" android:value= " Com.example.actionbartest.LaunchActivity "/></activity>
As you can see, the parent activity of Mainactivity is specified here through the meta-data tag launchactivity, which can also be used directly after Android 4.1 version: Parentactivityname This property to be specified as follows:
<activity android:name= "com.example.actionbartest.MainActivity" android:logo= "@drawable/weather" android:parentactivityname= "Com.example.actionbartest.LaunchActivity" ></activity>
The third step is required for Android. R.id.home This event for some special processing, as follows:
@Overridepublic boolean onoptionsitemselected (MenuItem item) {switch (Item.getitemid ()) {case Android. R.id.home:intent upintent = Navutils.getparentactivityintent (this); if (Navutils.shoulduprecreatetask (this, upIntent ) {taskstackbuilder.create (this). Addnextintentwithparentstack (upintent). Startactivities (); else {upintent.addflags (intent.flag_activity_clear_top); Navutils.navigateupto (this, upintent);} return true; ......}}
Where the call Navutils.getparentactivityintent () method can get to the intent that jumps to the parent activity, and then if the parent activity and the current activity are in the same task, The Navigateupto () method is called directly to jump, and if it is not in the same task, a new task needs to be created with Taskstackbuilder. In this way, the Actionbar navigation function is successfully implemented according to the standard specification.
Add Action Viewactionview is a control that can replace the action button in Actionbar, which allows the user to perform some of the richer operations through Actionbar without switching the interface. For example, if you need to complete a search function, you can add the Seachview control to the Actionbar. To declare a actionview, we can specify a control in the menu resource by using the Actionviewclass property, for example, you can add Searchview as follows:
<menu xmlns:android= "Http://schemas.android.com/apk/res/android" > <item android:id= "@+id/ Action_search " android:icon=" @drawable/ic_action_search " android:actionviewclass=" Android.widget.SearchView " android:showasaction=" Ifroom|collapseactionview " android:title=" @string/ Action_search "/> ......</menu>
Note In the Showasaction property we also declare a collapseactionview, which indicates that the control can be combined into an action button. Now run the program again, as shown in the results:
OK, sure enough, there is a search Style action button appears, now click on the Search button, the effect as shown:
As you can see, the Searchview expands to fill the entire actionbar, while the other action buttons are hidden in overflow because the Showasaction property is set to Ifroom. If you also want to configure Searchview properties in your code (such as adding listener events, etc.), there is no problem at all, just get an instance of the Actionview in the Oncreateoptionsmenu () method, as shown in the code below:
@Overridepublic boolean Oncreateoptionsmenu (Menu menu) {menuinflater inflater = Getmenuinflater (); Inflater.inflate ( R.menu.main, menu); MenuItem Searchitem = Menu.finditem (R.id.action_search); Searchview Searchview = (searchview) searchitem.getactionview ();//Configure Searchview Properties ... return Super.oncreateoptionsmenu (menu);}
Once you have an instance of Searchview, you can configure its various properties arbitrarily. For more detailed usage of Searchview, refer to the official document Http://developer.android.com/guide/topics/search/search-dialog.html. In addition, some programs may also want to display a different interface when the Actionview is expanded and merged, in fact, we only need to register a Actionview listener to implement such a function, the code is as follows:
@Overridepublic boolean Oncreateoptionsmenu (Menu menu) {menuinflater inflater = Getmenuinflater (); Inflater.inflate ( R.menu.main, menu); MenuItem Searchitem = Menu.finditem (R.id.action_search); Searchitem.setonactionexpandlistener (new Onactionexpandlistener () {@Overridepublic Boolean Onmenuitemactionexpand (MenuItem item) {LOG.D ("TAG", "on expand"); return true;} @Overridepublic boolean onmenuitemactioncollapse (MenuItem item) {LOG.D ("TAG", "on Collapse"); return true;}}); return Super.oncreateoptionsmenu (menu);}
As you can see, calling MenuItem's Setonactionexpandlistener () method registers a listener, and when Searchview expands, it calls back the Onmenuitemactionexpand () method, The Onmenuitemactioncollapse () method is called when Searchview merges, and we can do the corresponding UI actions in both methods.
Overflow button does not display the situation although we have mastered a lot of actionbar usage now, but when you really go to use it can still encounter a variety of problems, such as a lot of people will encounter the overflow button does not show the situation. Obviously is the same code, overflow button on some phones will be displayed, and on some phones just do not show, this is why? Later I summed up, overflow button display situation and the phone hardware situation is related, if the phone does not have physical menu key, overflow button can be displayed, if there is a physical menu key, overflow button will not be displayed. For example, if we start a simulator with a menu key and then run the code to the emulator, the result is as follows:
As you can see, the overflow button on the Actionbar's right is gone! So how do we look at the action button hidden in overflow? Actually very simple, click the menu key, the hidden content will come out from the bottom, as shown in:
See here believe a lot of friends are want to vomit trough, this is obviously a very painful design, in different mobile phones actually show the different interface, and the operation method is completely not the same, this will give users a very unaccustomed feeling. I don't quite understand why Google is designing Actionbar's overflow, but we still have a way to change the default behavior. In fact, in the Viewconfiguration class there is a static variable called Shaspermanentmenukey, the system is based on the value of this variable to determine whether the phone has a physical menu key. Of course this is an internal variable, and we can't access it directly, but it can be changed by reflection, so it's always false, and the code looks like this:
@Overrideprotected void OnCreate (Bundle savedinstancestate) {... setoverflowshowingalways ();} private void Setoverflowshowingalways () {try {viewconfiguration config = viewconfiguration.get (this); Field Menukeyfield = ViewConfiguration.class.getDeclaredField ("Shaspermanentmenukey"); Menukeyfield.setaccessible ( true); Menukeyfield.setboolean (config, false);} catch (Exception e) {e.printstacktrace ();}}
Here we call the Setoverflowshowingalways () method at the end of the OnCreate () method, and the inside of this method is to use reflection to set the value of Shaspermanentmenukey to False, Now rerun the code and the results are as follows:
You can see that even on the phone with the menu key, you can let the overflow button display, which can greatly increase the unity of our software interface and operation.
Let the options in overflow show the icon if you click the overflow button to see the Hidden action button, you will see that the action button is only showing the text without displaying the icon, as shown in:
This is the official default effect and Google believes that the action button hidden in overflow should only display text. Of course, if you think this is not beautiful enough, and you want the action button in overflow to display the icon, we can still find a way to change this default behavior. In fact, the action button in overflow should not display the icon, which is determined by the setoptionaliconsvisible variable of the Menubuilder class, if we assign this variable to True when overflow is expanded, Then the icon for each action button inside will be displayed. The method of assignment is, of course, still reflected, and the code looks like this:
@Overridepublic boolean onmenuopened (int featureid, menu menu) {if (Featureid = = Window.feature_action_bar && men U = null) {if (Menu.getclass (). Getsimplename (). Equals ("Menubuilder")) {try {Method m = Menu.getclass (). Getdeclaredmethod ("setoptionaliconsvisible", Boolean.type); m.setaccessible (true); M.invoke (menu, True);} catch (Exception e) {}}}return super.onmenuopened (Featureid, menu);}
As you can see, here we rewrite a onmenuopened () method, which is called back when overflow is expanded, The Menubuilder's setoptionaliconsvisible variable is then set to true on the inside of this method by returning the reflection method. Now rerun the code and the results are as follows:
Well, so far we have actionbar the basic knowledge of the introduction, then today's explanation to here, the next article I will lead you to more in-depth understanding of actionbar.