Android Activity Bar (Actionbar) use details (ii)

Source: Internet
Author: User

1. Using Actionbar for tab navigationthe idea of using Actionbar for tab navigation is thatAcitonbar is typically used in conjunction with fragment to implement tab navigation . Actionbar generates multiple tab tabs at the top, and when the user taps a tab tag, the system specifies the tab page based on the user's Click event navigation. The implementation steps are as follows:(1) Call ActionBar's Setnavigationmode (Actionbar.navigation_mode_tabs) method to set the tab navigation mode;(2) Call Actionbar's AddTab () method to add multiple tab tabs and add event listeners for each tab tag.Source code Combat:(1) Src/mfragment.javafunction: Implements a fragment subclass. The Getarguments () method can be used to get the parameter bundle that was passed when the fragment was created, and then, using the GetXXX (key) of the bundle object to get the data that the activity passed into the fragment, and display the corresponding components of the custom layout to fragment.
package com.example.actionbar;import android.app.fragment;import android.os.Bundle; Import Android.view.gravity;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;import android.widget.textview;/** * Project name/version number: actionbar/v1.0 * Package Name: Com.example.actionbar * Class Description: Implement a simple fragment that shows only one TextView component * Creator: Jiangdongguo * created: 2015-6-12 9:42:35 * Blog Address: http://blog.csdn.net/ u012637501 */public class Mfragment extends Fragment {public static final String arg_text_data= "Text_data";//bundle required key value /** * The return value of this method is the view component displayed by the fragment * */public view Oncreateview (Layoutinflater inflater, ViewGroup container,bundle Savedinstancestate) {TextView TextView = new TextView (getactivity ()); textview.setgravity (Gravity.start); Textview.setscrollcontainer (True);//a. Gets the parameter passed in when the fragment was created bundlebundle bundle = Getarguments ();// B. Display the incoming data to Textview.settext (Bundle.getstring (Arg_text_data));//c. Returns the Viewreturn TextView;}} 
(2) Src/mainactivity.javafunction: Because this application is only used to implement tab navigation with Actionbar and fragment, the key code of the activity is mainly a) setting the navigation mode of actionbar---tab navigation, Then add multiple tab pages in turn and add event listeners for each tab tag, b) Implement the Tab Event Listener ontabselected () method, and replace the new fragment with the tab tag selected by the user in the method as follows:> Create a custom Subclass object that inherits from fragment;> Creates a Bundle object and packages the data that needs to be passed into the fragment subclass into the bundle object;> invokes the Setarguments (bundle) method of the Fragment object to transmit data to fragment;> Gets the Fragmenttransaction object and calls its replace (int containerviewid, Fragment Fragment) method to make Fragment replace the activity's container ( The LinearLayout component is used here, and finally, the thing is submitted. fragment.setarguments (bundle);
Fragmenttransaction fragmenttransaction = Getfragmentmanager (). BeginTransaction ();
Fragmenttransaction.replace (R.id.mcontainer, fragment);
Fragmenttransaction.commit ();

Package Com.example.actionbar;import Java.io.file;import Java.io.fileinputstream;import java.io.IOException;import Java.io.inputstream;import Org.textmining.text.extraction.wordextractor;import Android.app.ActionBar;import Android.app.actionbar.tab;import Android.app.activity;import Android.app.fragment;import Android.app.fragmenttransaction;import Android.content.res.assetmanager;import Android.os.Bundle;import android.os.environment;/** * Project name/version number: actionbar/v1.0 * Package Name: Com.example.actionbar * Class Description: * Creator: Jiangdongguo * Creation time: 2015-6-12 9:29:17 * Blog Address: http://blog.csdn.net/u012637501 */public class Mainactivity extends Activity implements Actionbar.tablistener {private static final String Selection_item = "Select_item";//private assetmanager Assetmanager = n        ull; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);      Setcontentview (R.layout.activity_main); A. If the program has the active bar enabled correctly, a ActionBar object will be returned, otherwise null ActionBar ActionBar = Getactionbar ();        B. Set the ActionBar navigation mode, that is, tab navigation Actionbar.setnavigationmode (Actionbar.navigation_mode_tabs);        C. Add three tab pages in turn and add Event listener Actionbar.addtab (Actionbar.newtab (). SetText ("JJ Lin") to the Three tab tabs. Settablistener (this));        Actionbar.addtab (Actionbar.newtab (). SetText ("China"). Settablistener (this));    Actionbar.addtab (Actionbar.newtab (). SetText ("Dapeng"). Settablistener (this)); } @Overrideprotected void Onrestoreinstancestate (Bundle savedinstancestate) {if (Savedinstancestate.containskey ( Selection_item) {//Select the Fragment page Getactionbar () that corresponds to the previously saved index. Setselectednavigationitem (Savedinstancestate.getint ( Selection_item));}} @Overrideprotected void Onsaveinstancestate (Bundle outstate) {//Saves the index of the currently selected fragment to the Bundle Outstate.putint ( Selection_item, Getactionbar (). Getselectednavigationindex ());} /** * Method Name (overloaded): ontabselected * Function Description: Fires the method when the specified tab is selected. In this method, replace the new fragment * date:2015-6-12[j] */@Overridepub based on the tab tag selected by the user. LIC void ontabselected (Actionbar.tab Tab, fragmenttransaction ft) {ASsetmanager Assetmanager = Getresources (). Getassets (); Gets the assets resource object InputStream InputStream = null; Wordextractor extractor = null;//a. Create a new fragment object fragment fragment = new Mfragment ();// B. Create a bundle object to pass in parameter (data) Bundle bundle = new Bundle () to fragment, try {if (tab.getposition () ==0) {InputStream = Assetmanager.open ("Linjunjie.txt");//get the input stream corresponding to the asset file}else if (tab.getposition () ==1) {InputStream = Assetmanager.open (" China.txt ");//obtain the input stream corresponding to the asset file}int length = inputstream.available ();//Get the total number of bytes contained in the input stream byte[] buffer = new Byte[length];  Create a cache byte array inputstream.read (buffer); Reads input stream data into a byte array bundle.putstring (Mfragment.arg_text_data, new string (buffer, "GB2312"));//converts byte array data to a string, Save to bundle Object Inputstream.close ();} catch (IOException e) {e.printstacktrace ();} catch (Exception e) {e.printstacktrace ();} C. Incoming data fragment.setarguments (bundle) to fragment;//d. Get Fragmenttransaction Object Fragmenttransaction Fragmenttransaction = Getfragmentmanager (). BeginTransaction ();// C. Use fragment instead of the Containner component in the activity fragmenttransaction. replace (R.id.mcontainer, fragment);//d. Submit things Fragmenttransaction.commit ();} @Overridepublic void ontabunselected (Tab tab, fragmenttransaction ft) {} @Overridepublic void ontabreselected (Tab tab, Fragmenttransaction ft) {}}
(3) Res/layout/main,xmlfunction: The activity's interface layout defines only a simple container (such as LinearLayout), which allows the activity to use the container for fragment.
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"    android:id= "@+id/mcontainer"    android:layout_width= "match_parent"    android:layout_height= "match_parent"     android:orientation= " Vertical "/>
(4) Effect demonstration
(5) Fragment technologyfragment is equivalent to a fragment of activity that can be combined with multiple fragment (i.e. one activity with multiple interfaces) or multiple activity to reuse a single fragment. The fragment corresponds to the modular area of activity, and the main features are as follows:a) Fragment has its own life cycle, which can receive, process events belonging to itself, and allow the activity to dynamically add or remove fragment during operation. b) Fragment allows you to define your own layout, or you can define your own behavior through life cycle callback methods, similar to activity;c) Developer-defined fragment needs to inherit fragment and rewrite its life cycle method, typically overriding fragment's Oncreateview () to return to Freagment view.
2. Using Actionbar to implement pull-down navigation

Actionbar provides a drop-down (DropDown) navigation method In addition to tab navigation support. The Actionbar feature of pull-down navigation is that a drop-down list box is generated at the top of the interface, and when the user clicks on a list item, the system navigates to the specified fragment based on the user's Click event. The implementation steps are as follows:Call ActionBar's Actionbar.setnavigationmode (actionbar.navigation_mode_list) method to set the navigation mode using the drop-down list;Call ActionBar's Setlistnavigationcallbacks (Spinneradapter Adapter,actionbar.onnavigationlistener callback) () Add multiple list items and set up event listeners for each list item. The first parameter, adapter, is responsible for providing multiple list items, and the second parameter is the event listener.
Package Com.example.actionbar;import Java.io.file;import Java.io.fileinputstream;import java.io.IOException;import Java.io.inputstream;import Org.textmining.text.extraction.wordextractor;import Android.app.ActionBar;import Android.app.actionbar.onnavigationlistener;import Android.app.actionbar.tab;import Android.app.Activity;import Android.app.fragment;import Android.app.fragmenttransaction;import Android.content.res.assetmanager;import   Android.os.bundle;import Android.os.environment;import android.widget.arrayadapter;/** * Project name/version number: Actionbar/v1.0 * Pack Name: Com.example.actionbar * Class Description: * Creator: Jiangdongguo * created: 2015-6-12 9:29:17 * Blog Address: http://blog.csdn.net/u012637501 * * public class Mainactivity extends Activity implements Actionbar.tablistener, Onnavigationlistener {private static final S    Tring Selection_item = "Select_item";//private assetmanager assetmanager = null;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); SetcoNtentview (R.layout.activity_main);           A. If the program has the active bar enabled correctly, a ActionBar object will be returned, otherwise null ActionBar ActionBar = Getactionbar ();        Sets whether ActionBar displays the title actionbar.setdisplayshowtitleenabled (true);        Set navigation mode, use LIST navigation Actionbar.setnavigationmode (actionbar.navigation_mode_list); Add Arrayadapter actionbar.setlistnavigationcallbacks (new arrayadapter<string> (mainactivity.this) for ActionBar Android. R.layout.simple_list_item_1, Android.    R.ID.TEXT1, new string[] {"JJ Lin", "China", "Dapeng"}), this); } @Override protected void Onrestoreinstancestate (Bundle savedinstancestate) {if (Savedinstancestate.containskey ( Selection_item) {//Select the Fragment page Getactionbar () that corresponds to the previously saved index. Setselectednavigationitem (Savedinstancestate.getint (  Selection_item)); }} @Override protected void Onsaveinstancestate (bundle outstate) {//To save the index of the currently selected fragment to the Bundle Outstate.putint (sele Ction_item, Getactionbar (). Getselectednavigationindex ()); }/** * Method name (overloaded): OnnavigationitemselecTed * Feature Description: Fires the method when the specified item is selected. In this method, replace the new fragment * date:2015-6-13[j] */@Override public boolean Onnavi based on the tab tag selected by the user gationitemselected (int itemposition, long itemId) {Assetmanager Assetmanager = getresources (). Getassets ();//  Gets the assets resource object InputStream InputStream = null;  Wordextractor extractor = null;  A. Create a new Fragment object Fragment Fragment = new Mfragment ();  B. Create a bundle object to pass in the parameter (data) Bundle bundle = new Bundle () to the fragment; try {if (itemposition==0) {InputStream = Assetmanager.open ("Linjunjie.txt");//Gets the input stream corresponding to the asset file}else if (Itemposi tion==1) {InputStream = Assetmanager.open ("China.txt");//get the input stream corresponding to the asset file} int length = Inputstream.available ();// Gets the total number of bytes that the input stream contains byte[] buffer = new Byte[length]; Create a cache byte array inputstream.read (buffer); Reads input stream data into a byte array bundle.putstring (Mfragment.arg_text_data, new string (buffer, "GB2312"));//converts byte array data to a string,  Save to bundle Object Inputstream.close ();  } catch (IOException e) {e.printstacktrace (); } catch (Exception e) {  E.printstacktrace ();  }//c. Incoming data fragment.setarguments (bundle) to fragment;  D. Get the Fragmenttransaction object fragmenttransaction fragmenttransaction = Getfragmentmanager (). BeginTransaction ();  C. Use fragment instead of the Containner component in the activity Fragmenttransaction.replace (R.id.mcontainer, fragment);    D. Submission of things fragmenttransaction.commit (); return true; }}
Effect Demo:
Note: Here we only need to set Actionbar to the drop-down list navigation mode, in the list to the event listener onnavigationitemselected (int itemposition, long itemId) Replace with the corresponding fragment according to Itempostion (the specified list item id).

Android Activity Bar (Actionbar) use details (ii)

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.