"Android UI design and development" phase 11th: Top title bar (ii) Actionbar Implement Tab tab and drop-down navigation list

Source: Internet
Author: User
Tags event listener

Reprint Please specify source: http://blog.csdn.net/yangyu20121224/article/details/9050573

In the previous article, we just had a general understanding of the simple usage of the Actionbar class, and today I will continue to take a more in-depth look at the examples.

First, Implement TAB Options tab

When you want to provide tab tabs in an activity, using the Tab tab of the Actionbar is a good choice (rather than using the Tabwidget Class), as the system adjusts the Actionbar option label to suit the needs of different screen sizes. For example, when the screen is wide enough, the Tab tab will be placed in the main action bar, and when the screen is too narrow, tab tab will be placed in a separate bar, 1 and Figure 2:

Figure 1

Figure 2

To switch between fragmengt using the TAB Options tab, you must perform a fragment transaction each time you select an option label. If you are unfamiliar with how to use the Fragmenttransaction object to change fragment, read the detailed introduction and usage of the article fragment in front of the blogger.

First, your layout must contain a ViewGroup object that is used to place the option label associated with each fragment object. And make sure that the ViewGroup object has a resource ID so that you can reference it in the switch code of the option tag. In addition, if the contents of the option label are populated in the activity's layout (excluding the action Bar), then the activity does not require any layout (you do not even need to call the Setcontentview () method). Instead, you can put each fragment object in the default root ViewGroup object, and you can use Android. R.id.content ID to refer to this ViewGroup object (you can see how to use this ID in the following sample code during the fragment execution of the transaction).

After determining where the Fragment object appears in the layout, the basic procedure for adding Tab tab tabs is as follows:

<1> implement Actionbar.tablistener interface. The callback method in this interface responds to user events on the Options tab so that you can toggle the fragment object;

<2> for each option label that you want to add, instantiate an Actionbar.tab object and call the Settablistener () method to set the event listener for the Actionbar.tab object. You can also use the SetText () or SetIcon () method to set the title or icon of the option label;

<3> add each option label to the action Bar by calling the AddTab () method.

Second, the Realization tab option label

Three, the project structure chart

D. Detailed code writing

1, in the above, the title bar to the right of a clock, this effect is purely entertainment, the implementation of the method is very simple, in the menu layout file defined an Activity view action View,main.xml:

<menu xmlns:android= "Http://schemas.android.com/apk/res/android" >    <item        android:id= "@ +id/action_clock "        android:orderincategory="        android:showasaction= "Always"         android:title= "@string/action_settings"        android:actionlayout= "@layout/clock"/>    </menu>

2, in writing a clock layout file, Clock.xml:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" Match_parent "    android:layout_height=" Match_parent "     android:orientation= "vertical" >    <analogclock        android:id= "@+id/ AnalogClock1 "        android:layout_width=" Wrap_content "        android:layout_height=" Wrap_ Content "/></linearlayout>

3, in the definition of a layout file to store fragment layout, list one, Fragment_1.xml:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" Fill_parent "    android:layout_height=" Fill_parent ">    <ImageView        android:id= "@+id/imageview"        android:layout_width= "Fill_parent"         android:layout_height= "Fill_parent"        android:scaletype= "Fitcenter"         Android:src= "@drawable/xianjian01" >    </ImageView></LinearLayout>

4, define a class implementation Actionbar.tablistener interface, in this implementation, each tab option tag uses its own listener, Mytablistener.java:

 PackageCom.yangyu.myactionbar02;ImportAndroid.app.ActionBar.Tab;ImportAndroid.app.ActionBar.TabListener;Importandroid.app.Activity;Importandroid.app.Fragment;Importandroid.app.FragmentTransaction; Public classMytablistener<textendsFragment>ImplementsTablistener {PrivateFragment Fragment; Private FinalActivity mactivity; Private FinalClass<t>MClass;  PublicMytablistener (activity activity, class<t>CLZ) {mactivity=activity; MClass=CLZ; } @Override Public voidontabselected (Tab tab, fragmenttransaction ft) {if(Fragment = =NULL) {Fragment=fragment.instantiate (mactivity, Mclass.getname ()); Ft.add (Android. R.id.content, fragment,NULL);      } Ft.attach (fragment); } @Override Public voidontabunselected (Tab tab, fragmenttransaction ft) {if(Fragment! =NULL) {Ft.detach (fragment); }} @Override Public voidontabreselected (Tab tab, fragmenttransaction ft) {}}

Warning: for fragment transactions in each callback, you do not have to call the commit () method because the system calls this method, and if you call this method yourself, you may throw an exception. You also can't add these fragment transactions to the fallback stack.

In this code, when the corresponding option tag is selected, the listener simply attaches a fragment object (Attach () method) to the activity layout, or if it is not instantiated, creates the fragment object and adds it (add () method) into the layout (Android. R.id.content ViewGroup), when the option label is dismissed, the corresponding fragment object is also removed from the attachment to the layout.

5, Actionbar.tablistener the implementation of a lot of work, the remaining thing is to create each Actionbar.tab object and add it to the ActionBar object, in addition, you must call Setnavigationmode ( Navigation_mode_tabs) method to make the option label visible. If the title of the option label actually indicates the current view object, you can also disable the activity's caption by calling the Setdisplayshowtitleenabled (false) method Mainactivity.java:

 PackageCom.yangyu.myactionbar02;ImportAndroid.app.ActionBar;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.view.Menu; Public classMainactivityextendsActivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);                Setcontentview (R.layout.activity_main);    Initview (); }        /*** Initialize Components*/    Private voidInitview () {//Tip Getactionbar method must be behind Setcontentview        FinalActionBar ActionBar =Getactionbar ();        Actionbar.setnavigationmode (Actionbar.navigation_mode_tabs); Actionbar.setdisplayoptions (0, Actionbar.display_show_title); Actionbar.addtab (Actionbar.newtab (). SetText (Tab tab one). Settablistener (NewMytablistener<fragmentpage1> ( This, FragmentPage1.class))); Actionbar.addtab (Actionbar.newtab (). SetText (Tab tab two). Settablistener (NewMytablistener<fragmentpage2> ( This, FragmentPage2.class))); } @Override Public BooleanOncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (R.menu.main, menu); return true; }}

Note: the above implementation of Actionbar.tablistener is just one of several possible technologies. You can see more of this style in the API Demos app.

If the activity is terminated, you should save the status of the currently selected option label so that when the user returns again, you will be able to open the appropriate Options tab. At the moment of saving, you can use the Getselectednavigationindex () method to query the current Selection tab. This method returns the index position of the selected option label.

Warning: It is critical to save the required state for each fragment, because when the user switches between fragment objects with option labels, it will see what the fragment looks like when it leaves.

Note: In some cases, the Android system will display the Action Bar option label as a drop-down list to ensure optimal display of the action Bar.

6. Finally, a class showing fragment is listed, Fragmentpage1.java:

 PackageCom.yangyu.myactionbar02;Importandroid.app.Fragment;ImportAndroid.os.Bundle;ImportAndroid.view.LayoutInflater;ImportAndroid.view.View;ImportAndroid.view.ViewGroup; Public classFragmentPage1extendsfragment{@Override PublicView Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {returnInflater.inflate (R.layout.fragment_1,NULL); }    }

V. Implementation of the dropdown navigation list

As an alternative navigation (or filtering) mode within the activity, the action Bar provides a built-in drop-down list. Drop-down list to provide content in activity

The different sort modes.

The basic process for enabling pull-down navigation is as follows:

<1> Create a list of optional items for the drop-down and the layout used to draw the list items;

<2> implements the Actionbar.onnavigationlistener callback, which defines the behavior that occurs when the user selects an item in the list;

<3> Use the Setnavigationmode () method to enable navigation mode for the action bar;

<4> Use the Setlistnavigationcallbacks () method to set the callback method for the drop-down list.



Six, pull down navigation implementation


VII. Project Structure diagram

Eight, detailed code writing

1, this code is relatively simple, mainly called the Spinneradapter and Actionbar.onnavigationlistener objects

 Packagecom.yangyu.myactionbar03;ImportAndroid.app.ActionBar;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.view.Menu;ImportAndroid.widget.ArrayAdapter;ImportAndroid.widget.SpinnerAdapter; Public classMainactivityextendsActivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);                Setcontentview (R.layout.activity_main);    Initview (); }    /*** Initialize Components*/    Private voidInitview () {ActionBar ActionBar=Getactionbar ();                Actionbar.setnavigationmode (actionbar.navigation_mode_list); //define a drop-down list data adapterSpinneradapter Mspinneradapter = Arrayadapter.createfromresource ( This, R.array.action_list, Android.                            R.layout.simple_spinner_dropdown_item); Actionbar.setlistnavigationcallbacks (Mspinneradapter,NewActionbar.onnavigationlistener () {@Override Public BooleanOnnavigationitemselected (intItemposition,LongitemId) {                return true;                                              }        }); } @Override Public BooleanOncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (R.menu.main, menu); return true; }}

"Android UI design and development" phase 11th: Top title bar (ii) Actionbar Implement Tab tab and drop-down navigation list

Related Article

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.