Android actionbar Application One: Actionbar return to any page and search bar

Source: Internet
Author: User


Reprint Please specify source: http://blog.csdn.net/cyp331203/article/details/44922863


Action Bar is a square area at the top of the app app that doesn't always appear (such as full-screen theme), it's part of the window, and it's a bit like the title bar of a Windows window, as shown in:




Actionbar Brief Introduction:


As shown, the title bar typically has three types of buttons:

1, can be called home area, there is a button to identify the app, this button is not activated by default, the image display by default and the app's icon consistent

2, can be called button area, display in the button area of multiple title bar buttons

3, "More" button, click can pull out the hidden title bar button, commonly known as: "Overflow"


The point to be clear is:

Actionbar's API was first added to Android at Android 3.0 (API level 11), but we can also use it on Android 2.1 (API Level 7), just to add a support package, which is usually said v4 Support Library and V7 Support Library


In general, for compatibility reasons, when writing an application, the Actionbar-related APIs in the Compatibility Pack are used instead of the system's own, so the sections that follow are described by default based on the contents of the V4 and V7 packages.


In importing the Actionbar to use the Compatibility Pack, our mainactivity or other xxxactivity cannot be inherited from the activity, need to be replaced by: actionbaractivity, and then need to be in the manifest file, Change to AppCompat theme or its sub-theme, about the theme can see this article Actionbar theme color:


get the Actionbar object:

public class Mainactivity extends Actionbaractivity<activity android:theme= "@style/theme.appcompat.light" ... >

then, you can get the Actionbar object by the following code:

ActionBar Mactionbar = Getsupportactionbar ();


You can then invoke the following two sentences to show or hide the entire actionbar:

Mactionbar.hide (); Mactionbar.show ();


To activate the Home area button:but just to get this object, and no use, or can not click, need to do further processing, here is similar to the button's enable settings, setenable:

Mactionbar.sethomebuttonenabled (True); mactionbar.setdisplayshowhomeenabled (true);// These two sentences can let the Actionbar icon can respond to the Click event mactionbar.setdisplayhomeasupenabled (TRUE);//This sentence is mainly used to return the effect back, the following will speak

To Set the button area:

Above the button area, you need to use an XML file that represents menu, usually stored under res/menu/, and then override the Oncreateoptionsmenu () method to set, Res/menu/main_activity_ The Actions.xml file is as follows:


<?xml version= "1.0" encoding= "Utf-8"? ><menu xmlns:android= "Http://schemas.android.com/apk/res/android" xmlns:alex= "Http://schemas.android.com/apk/res-auto" > <item android:id= "@+id/action_search" alex:s howasaction= "Collapseactionview|ifroom|withtext" android:icon= "@drawable/ic_action_search" android:title= "search        "/> <item android:id=" @+id/action_share "alex:showasaction=" Collapseactionview|ifroom|withtext " android:icon= "@drawable/ic_action_share" android:title= "Share"/> <item android:id= "@+id/action_sea Rch2 "alex:actionviewclass=" Android.support.v7.widget.SearchView "alex:showasaction=" Collapseactionview|ifro Om|withtext "android:icon=" @drawable/ic_action_search "android:title=" search "/> <item android:id = "@+id/action_share2" alex:showasaction= "Collapseactionview|ifroom|withtext" android:icon= "@drawable/ic_acti On_share "android:title="Share"/> <item android:id= "@+id/action_hide" alex:showasaction= "Collapseactionview|ifroom|withtext" android:icon= "@drawable/ic_action_share" android:title= "hidden Buttons"/></menu>


See above used a custom attribute: Showasaction, this property is used to indicate the way the button is displayed commonly used is: Ifroom (indicates that there is space will be displayed), Withtext (indicating with a name, but not necessarily display, the general text will appear under the "More" button) , never (which is never displayed directly on the Actionbar, means that the button will always appear on the drop-down menu of the "More" button), be aware that the "more" button does not necessarily appear, if there is not enough space or the Never property of the button, it will be displayed, otherwise it will not be displayed. StackOverflow has studied how to let more always show, interested can see: http://stackoverflow.com/questions/20444596/ How-to-force-action-bar-overflow-icon-to-show

In addition, the above XML also has the button ID and image and title attributes.


The icons can then be displayed by overriding the onCreateOptionsMenu() methods:

@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);    return Super.oncreateoptionsmenu (menu);}


To handle a click event:

The goal can be achieved by overriding the Onoptionsitemselected () method, but one thing to note is that for the Actionbar icon, the icon for that app, its ID is: Android. R.id.home.

@Overridepublic boolean onoptionsitemselected (MenuItem item) {int itemId = Item.getitemid (); switch (itemId) {case Android. R.id.home:toast.maketext (This, "home", 0). Show (); Break;case R.id.action_search:toast.maketext (This, "search", 0). Show (); Break;default:toast.maketext (This, "itemid=" + itemId, 1). Show (); return super.onoptionsitemselected (item);}


Complete the above section, you can get a similar to the following interface





the ability to return to the previous/arbitrarily developed activity is achieved through Actionbar:


When writing an app, you will often want to need a function that returns the initial/first page activity from any activity, which can be done easily using the Actionbar button.


There are two ways to do this: the XML manifest file configuration and the Java code approach.


There are two ways to set up one of the properties mentioned above:

@Overrideprotected void OnCreate (Bundle savedinstancestate) {    super.oncreate (savedinstancestate);    Setcontentview (r.layout.activity_details);    ActionBar ActionBar = Getsupportactionbar ();    Actionbar.setdisplayhomeasupenabled (true);    ...}


method One: The XML manifest file configuration method implementation returns:


If two activity:a and B,b want to return a, set the full class name of Android.support.PARENT_ACTIVITY to a in the position of the manifest file B, as shown in the following code, in Meta-data way.


<application ... > ...    <!--the main/home activity (has no parent activity)--    <activity        android:name= " Com.example.myfirstapp.ActivityA "...> ...    </activity>    <!--A Child of the main activity--    <activity        android:name= " Com.example.myfirstapp.ActivityB "        android:label=" @string/title_activity_display_message "        android: Parentactivityname= "Com.example.myfirstapp.MainActivity" >        <!--Parent activity meta-data to the support API Level 7+--        <meta-data            android:name= "Android.support.PARENT_ACTIVITY"            android:value= " Com.example.myfirstapp.ActivityA "/>    </activity></application>

Then, click Actionbar's Home button, you can go straight from activityb back to Activitya.



method Two: Rewrite the getSupportParentActivityIntent() and onCreateSupportNavigateUpTaskStack() methods in the Activityb.

In fact, these two methods are not necessarily rewritten, getsupportparentactivityintent () for the activity within the app jump, Oncreatesupportnavigateuptaskstack () The activity used to jump to other apps is more complicated, and there's no discussion here, so you can see http://developer.android.com/guide/topics/ui/actionbar.html#ActionViewCollapsing


Getsupportparentactivityintent () returns a intent to jump, so it's only necessary to return a intent object that points to the activity we want to jump to.


In contrast, the code is more flexible.


It is worth noting that both of these methods can only be applied to jumps between activity, and if you want to apply between fragment , you need to use the onSupportNavigateUp() and Popbackstack () method.



Explore Android Search bar:


First, you need to add a custom property to this button by adding a Searchview to the item in the above menu's XML file, such as the item in the Action_search above:

<item        android:id= "@+id/action_search"        alex:actionviewclass= "Android.support.v7.widget.SearchView"        alex:showasaction= "Collapseactionview|ifroom|withtext"        android:icon= "@drawable/ic_action_search"        android:title= "Search"/>



Then you need to create this searchview in the Oncreateoptionsmenu method:

@Overridepublic boolean Oncreateoptionsmenu (Menu menu) {    getmenuinflater (). Inflate (r.menu.main_activity_ actions, menu);    MenuItem Searchitem = Menu.finditem (r.id.action_search);    Searchview Searchview = (searchview) menuitemcompat.getactionview (searchitem);    Configure the search info and add any event listeners ...    return Super.oncreateoptionsmenu (menu);}


After adding a click on the Search button, the corresponding search bar will be displayed:




But it's not so cool right now ... No search hint text, two no real ability to search, the following to do these two steps:


Search hint TEXT (hint):


Here is a need to write a searchable XML file into the Res/xml/folder:

Res/xml/searchable.xml


<?xml version= "1.0" encoding= "Utf-8"? ><searchable xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:hint=" @string/search_hint "    android:label=" @string/app_label "></searchable>



The above is a simple searchable, in fact, the properties of searchable can be many, but most of them are not used, unless you need voice search or other additional functions.


Next It is necessary to associate this searchable.xml with the activity that we want to show the search results in the manifest file, which is also used in the Meta-data, note that the location is the activity to display the search results, not necessarily the current activity:

<application >        <activity android:name= "com.example.actionbarex.SecondActivity" >            < intent-filter>                <action android:name= "Android.intent.action.SEARCH"/>            </intent-filter>            <meta-data                android:name= "android.app.searchable"                android:resource= "@xml/searchable"/>        </activity>    ...</application>

here the android.app.searchable, representing the search properties, hint hints, etc., can not be changed; @xml/searchable represents res/xml/searchable.xml file


Then we also need to link the search input box to the corresponding search activity by default, but also to use meta-data, but it needs to be configured within the application or other activity to be searched, here is an example of unloading the application:

<application >        <meta-data            android:name= "android.app.default_searchable"            android:value= " Com.example.actionbarex.SecondActivity "/>    ...</application>


Once this is configured, we will receive the Intent object from the OnCreate method in the activity that will display the search results, and then determine whether the Intent object is requesting a search: Intent.action_search

@Overridepublic void OnCreate (Bundle savedinstancestate) {    super.oncreate (savedinstancestate);    Setcontentview (r.layout.search);    Get the intent, verify the action and get the query    Intent intent = getintent ();    if (Intent.ACTION_SEARCH.equals (Intent.getaction ())) {      String query = Intent.getstringextra (searchmanager.query );      dosearching (query);}    }


private void Dosearching (String query) {System.out.println ("Do some search for time-consuming operations ....");}

After the above operation, you can build a simple search structure, and then we in the dosearching, then to do real search operations, query database or search network, etc...


The following puts the return function and search together, the effect



Reprint Please specify source: http://blog.csdn.net/cyp331203/article/details/44922863




Android actionbar Application One: Actionbar return to any page and search bar

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.