Android Learning Note: Actionbar usage Introduction

Source: Internet
Author: User

First, the basic concept

See Google's API documentation for the most authoritative and official presentations

Http://developer.android.com/training/basics/actionbar/setting-up.html

Http://developer.android.com/guide/topics/ui/actionbar.html

Actionbar Therefore, the meaning of the action Bar, usually located at the top of the activity, you can place text tags, search boxes, buttons, icons and so on. is supported by ANDROID3.

Create a default activity in Eclipse, as shown in the default display of the app's icon and app name, and note that there may be a slight difference between different versions.

Let's look at the example map given in the Google API documentation

In the image above, ① is the icon of the app, the ② is two action buttons, one is the search button, and ③ is the overflow button (the meaning of overflow is described later).

Second, the setting does not display Actionbar

If you want activity to not show Actionbar, there are two ways to do this:

1) Specify the theme of application or activity in androidmanifest.xml such as:

Android:theme= "@android: Style/theme.light.notitlebar"

2) in the activity of the OnCreate event through the code settings, as follows:

@Overrideprotected void onCreate (Bundle savedinstancestate) {    Super. OnCreate (savedinstancestate);    Setcontentview (r.layout.activity_main);    ActionBar ActionBar = getactionbar ();    Actionbar.hide ();}  

In this way, the activity will not show Actionbar.

Third, change the default icon and title

By default, activity uses the image specified by the Application icon property in Androidmanifest.xml as the Actionbar icon, such as:

<application
Android:allowbackup= "true"
Android:icon= "@drawable/ic_launcher"

But we can also change this default behavior, if we want to use another image as a actionbar icon, you can set the activity's logo properties to be specified.

For example, in the project's res/drawable directory, there is a picture of mylogo.png, which can be specified in Androidmanifest.xml:

<activity
Android:logo= "@drawable/mylogo"

Headings can be set by setting the Android:label property in the configuration file or by code, such as:

    @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); Settitle ("My App");}

Iv. 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. If the button is too many, actionbar on the display, some of the extra buttons can be hidden in the overflow (the right three points is the overflow button, mentioned earlier), 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.

1. First add the configuration file in the Res\menu directory, such as Main.xml (the file will be created by default when created with Eclipse)

<menu xmlns:android= "Http://schemas.android.com/apk/res/android" xmlns:          tools= "Http://schemas.android.com/tools" tools:context= "com.example.testactionbar.MainActivity" > <item Android:id= "@+id/action1" android:icon= "@drawable/a1" android:showasaction= "Always" Android: title= "Action1"/> <item android:id= "@+id/action2" android:icon= "@drawable/a2" Androi          d:showasaction= "Ifroom" android:title= "Action2"/> <item android:id= "@+id/action3" android:icon= "@drawable/a3" android:showasaction= "Never" android:title= "Action3"/> </menu> 

In the above file, 3 action buttons have been added through the item tag. There are also attributes in the <item> tag, where the ID is the unique identifier of the action button, and icon is used to specify the button's icons, title is used to specify the text that the button might display (no text is displayed on the Actionbar if the icon is set). Showasaction Specifies the position that the button displays, 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 (this is the default).

2. Next, rewrite the activity's Oncreateoptionsmenu () method, as shown in the code below:

@Overridepublic boolean Oncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (R.menu.main, menu); return true;}

If it is a project created with Eclipse, this code is not available in the provincial capital.

V. Response events for adding action buttons

When you click the action button, you can trigger an event, and you can make your own processing in the event code, such as displaying a new interface. 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, and then make the appropriate action, such as:

@Overridepublic boolean onoptionsitemselected (MenuItem item) {switch (Item.getitemid ()) {case R.id.action1: Toast.maketext (This, "I Am" +item.gettitle (), Toast.length_short). Show (); return true;case R.id.action2: Toast.maketext (This, "I Am" +item.gettitle (), Toast.length_short). Show (); return true;case R.id.action3: Toast.maketext (This, "I Am" +item.gettitle (), Toast.length_short). Show (); return True;default:return super.onoptionsitemselected (item);}}

Vi. the overflow button does not show the situation

Although we have mastered a lot of actionbar usage now, when you really go to use it, you may encounter a variety of problems, such as many 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 a physical menu key, the overflow button can be displayed, if there is a physical menu key, the overflow button will not be displayed, The buttons hidden in overflow are only displayed when the physical button is pressed. But many users may not know this.

This is obviously a very painful design, on different mobile phones actually show a different interface, and the operation method is 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:
@Override  protected 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 ();      }  }  

So as long as there is a button that is not full, the overflow button will always be displayed.

Seven, let overflow in the option to display the icon

If you click on the overflow button to see the Hidden action button, you will find that this section of the action button displays only the text without displaying the icon.

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, is determined by the Setoptionaliconsvisible method of the Menubuilder class, if we give this method true when overflow is expanded, Then the icon for each action button inside will be displayed. The method that is called is, of course, still reflected with the code as follows:
@Override Public  boolean onmenuopened (int featureid, menu menu) {      if (Featureid = = Window.feature_action_bar & amp;& Menu! = 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.

Android Learning Note: Actionbar usage Introduction

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.