Use of "Android" Actionbar (1)

Source: Internet
Author: User

former (FEI) (Hua): A career in iOS development for half a year, a long time no contact with Android, a few days ago to class, listening to really boring, picked up a classmate of the "Android UI design", found that there are many basic knowledge of their own although used, But all is the original Android development, when the project needs to use the time to go to Baidu, Control+c and Control+v, then hastily finished, so that sometimes need to use a certain control or function, then go to Baidu or check the previous code. Although once did 2 years of Android development, but just do a few very water app, in order not to owe that two years of youth struggle, now, I will write some blog about the foundation of Android, Memorial to the two years of Android's youth. Needless to say, this is the first article in this series, "The Use of Actionbar (1)"


1. What is Actionbar?

The Android Action Bar is a window feature that shows which page of the app the user is currently in (the page title is displayed), provides action buttons (search, new, etc.), and navigates (returns), just like iOS uinavigationbar. Directly on the official map:


This is a actionbar example that contains [1] app icon, [2] Two action items, and [3] action overflow.


Actionbar from Android 3.0 (API level 11), if our new project only supports Android 3.0 and above, we can directly use the Actionbar API in the framework. If you want to use it in Android 2.1 (API level 7) or later, you can use it after adding Android-support-v4.jar. In the two cases mentioned above, most of the API is the same, but the package name is different:

API11 or more

Import Android.app.ActionBar

API11 below

Import Android.support.v7.app.ActionBar

Considering that the current Android phone version is in 4.0 and above, this article mainly uses Android.app.ActionBar.


When you create a new project, if targetsdkversion or minsdkversion is set to "11" or above, activity defaults to using the theme Theme.holo, are Actionbar, and if you don't need to use Actionbar, you can set the theme to Theme.Holo.NoActionBar.



1. Get, hide, and display Actionbar

ActionBar ActionBar = getactionbar();//Get ActionBar

ActionBar. hide ();//Hidden Actionbar

When Actionbar is hidden, the system automatically adjusts the layout to fit the screen space, and you can call show () to have the Actionbar displayed again.

* When using ANDROID-SUPPORT-V4, change Getactionbar () to Getsupportactionbar()


2. Add Action Items

when our activity start, the system invokes the activity's The Oncreateoptionsmenu () method to create an action item that uses this method to load a menu resource that defines the action items, for example, to add two action items, create a new folder in the Res directory , Name menu, and create a new XML file named Main_activity_actions.xml and add the following code, which defines two action items:

Res/menu/main_activity_actions.xml

<menu xmlns:android= "Http://schemas.android.com/apk/res/android" > <item android:id= "@+id/action_search" android:icon= "@drawable/ic_action_search" android:title= "@string/action_search"/> <item android:id= " @+id/action_compose "android:icon=" @drawable/ic_action_compose "android:title=" @string/action_compose "/ ></menu>


in the activity's Oncreateoptionsmenu () method, load the above layout

@Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu items for use in the action bar Menuinf    Later inflater = Getmenuinflater ();    Inflater.inflate (r.menu.main_activity_actions, menu); return Super.oncreateoptionsmenu (menu);}

The post-operation effect is as follows:




But our demand is that action item is displayed directly on Actionbar, not in action overflow, so you need to add showasaction= "Ifroom" in each <item>, As long as there is enough space, each action item will be displayed separately (never recommended), for example:

<menu xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:yourapp= "http://schemas.android.com/          Apk/res-auto "> <item android:id=" @+id/action_search "android:icon=" @drawable/ic_action_search " android:title= "@string/action_search" yourapp:showasaction= "Ifroom"/> ...</menu>

The effect is as follows:




If you want the action item to display both the picture and the text, we just modify the value of the showasaction:

showasaction= "Ifroom|withtext"

3. Handling Click events for action Items When the user clicks on action, the system invokes the activity's onoptionsitemselected () method, calling MenuItem's Getitemid () method to get The value of the id attribute in <item> to determine which action was clicked:

@Overridepublic boolean onoptionsitemselected (MenuItem Item) {//Handle presses on the Action Bar items switch (ite            M.getitemid ()) {case R.id.action_search:opensearch ();        return true;            Case R.id.action_compose:composemessage ();        return true;    Default:return super.onoptionsitemselected (item); }}private void OpenSearch () {System.out.println ("Action_search was clicked");} private void Composemessage () {System.out.println ("Action_compose was clicked");}

If you are using fragment to inflate the menu, when the user clicks the action item, the system invokes the callback of the Oncreateoptionsmenu () of the Fragment class. Onoptionsitemselected () method. However, the activity will deal with the Click event First, so in the activity's onoptionsitemselected () , to return to the fragments in ture,activity to have the opportunity to execute fragment Oncreateoptionsmenu () method.


4. Use the delimited action bar

First on the official:


Delimited Actionbar can place the action item at the bottom of the screen. How to achieve it?

1. If the API is 14 and above, simply add Android in each <activity> or <application> :uioptions= " Splitactionbarwhennarrow "

2. If the API is below 14, you need to add <meta-data>in each <activity> as follows:


<manifest ...> <activity uioptions= "Splitactionbarwhennarrow" ... > <meta-data android:name= "android Oid.support.UI_OPTIONS "android:value=" Splitactionbarwhennarrow "/> </activity></manifest >

If you want to hide the effect of the icon and title in Figure 3, you need to add the following two lines of code to the activity:

Actionbar.setdisplayshowhomeenabled (false); actionbar.setdisplayshowtitleenabled (false);

5. Use the icon on the Actionbar to navigate You can use the icon on Actionbar as the back button, like the Leftbarbuttonitem in the navigation bar in iOS, such as screen a displays a list, select an item in the class table, jump to screen B, and screen B can include a Back button to return to screen a.

Call the setdisplayhomeasupenabled () method of the Actionbar instance to display the Actionbar return button (such as the following code). Now you can see the return icon.

Actionbar.setdisplayhomeasupenabled (TRUE);

However, by default, it does not have any effect. Therefore, you need to configure it with either of the following two methods:

Method one. Declare the parent activity in the manifest file

If the parent activity is fixed, simply declare in manifest, the user presses the Back button, Actionbar will automatically jump back to the corresponding activity, at the beginning of Android 4.1 (API level 16), you can < set the parentactivityname property directly in Activity> to set the parent activity, and in the previous version, add a <meta-data> element to set the parent activity:


<application >    ...    <!--the main/home activity (has no parent activity)-->&nbsp ;   <activity        android:name= "com.example.myfirstapp.MainActivity" ...>        ...    </activity>    <!--A Child of the main activity-->  &NB Sp <activity        android:name= "com.example.myfirstapp.DisplayMessageActivity"         android:label= "@string/title_activity_display_message"         Android: Parentactivityname= "Com.example.myfirstapp.MainActivity" >        <!--Parent activity  Meta-data to support API level 7+-->        <meta-data            Android:name= "Android.support.PARENT_ACTIVITY"             android:value= " Com.example.myfirstapp.MainActivity "/>    </activity></appLication> 

Method Two. by overrideGetsupportparentactivityintent () and Oncreatesupportnavigateuptaskstack () in activity Method

This method is suitable for The user may be through different activity to jump to the current activity situation, this article does not do a detailed introduction, you can see the official document:http://developer.android.com/training/ Implementing-navigation/ancestral.html



6. Add an action View

Sometimes, a simple button does not meet our needs, and in order to achieve more, we can also use the action view. Action view is displayed on Actionbar as a wedget equivalent to the action button, for example, if a search function is required, you can add an action that embeds the Searchview widget View into the Actionbar. is a actionbar that contains a collapsible search bar.



To declare an action view, use the actionlayout and actionviewclass properties to specify which layout or widget to use, for example, the following code adds Searchview Widget:

<?xml version= "1.0" encoding= "Utf-8"? ><menu xmlns:android= "Http://schemas.android.com/apk/res/android" >    <item android:id= "@+id/action_search"          android:icon= "@drawable/ic_action_search"          android: title= "@string/action_search"          android:showasaction= "ifroom| collapseactionview"          android:actionviewclass = "Android.widget.SearchView"/>   </menu>

If you want to configure an action view (for example, to add a listener), you can pass Menu.finditem (r.id.action_search) in oncreateoptionsmenu () . Getactionview () To obtain, for example:

@Overridepublic boolean Oncreateoptionsmenu (Menu menu) {    //inflate the menu items for use in the action bar    Menui Nflater inflater = Getmenuinflater ();    Inflater.inflate (r.menu.main_activity_actions, menu);        Searchview Searchitem = (searchview) menu.finditem (r.id.action_search). Getactionview ();    Make Searchview settings, such as setting up listeners, etc.        .. return Super.oncreateoptionsmenu (menu);}

Where the use of Searchview controls is outside the scope of this document, you can refer to the official documentation: http://developer.android.com/guide/topics/search/search-dialog.html


As a result of the space relationship, the use of Actionbar (1) First mentioned here, the next article, "Actionbar (2)" will continue to introduce Actionbar other uses (Action Provider, Navigation Tabs, Drop-down Navigation, etc.), I hope you continue to pay attention, I will update as soon as possible.



Use of "Android" Actionbar (1)

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.