"Android UI design and development" phase 12th: Top title bar (iii) Actionbar to achieve the return effect of hierarchical navigation

Source: Internet
Author: User

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

Today we continue to explain the use of actionbar, it is not clear that this class of readers can go through the blogger's previous articles or on the Internet to check the relevant

Information, the article on this kind of explanation is still a lot of, the function is really also very powerful. OK, don't say a word, let's get to the point quickly.

First, use the application icon to achieve hierarchical navigation

By default, the application icon appears to the left of the action bar. You can use this icon as an action item, and the application can

One of the following two actions on an icon:

<1> return to the application's "main" Activity;

<2> Navigate to the application's ancestor page.

To implement an application icon to navigate up, first call the Setdisplayhomeasupenabledtrue (True) method in your Actionbar.

protected void onCreate (Bundle savedinstancestate) {    super. OnCreate (savedinstancestate);    Setcontentview (R.layout.main);     = Getactionbar ();    Actionbar.setdisplayhomeasupenabled (true);    ...}

When the user touches the icon, the system invokes the activity's onoptionsitemselected () method with the Android.r.id.home ID. In this ring

Should, you can either start the main activity or return to the interface of the user's previous action in the structured hierarchy of your application.

If you want to return to the main activity through the response of the application icon, you should include the Itent object in the

Flag_activity_clear_top identification. With this tag, if the activity you want to start already exists in the current task, then the stack

All activity on top of the activity is destroyed, and the activity is displayed to the user. It is often important to add this identity because it returns the primary

Activity is quite the same as a fallback action, so you should not normally create a new instance of the main activity, or you might end up in the current task

A very long stack with multiple main activity.

For example, the onoptionsitemselected () method of the following example implements the operation that returns the main activity of the application:

@Override Public Booleanonoptionsitemselected (MenuItem item) {Switch(Item.getitemid ()) { CaseAndroid. R.id.home:intent Intent=NewIntent ( This, Homeactivity.class);            Intent.addflags (Intent.flag_activity_clear_top);            StartActivity (Intent); return true; default:            return Super. onoptionsitemselected (item); }}

You may also want to add the Flag_activity_new_task identity when the user enters the current activity from another application. This

Identity ensures that new activity is not added to the current task when the user returns to the home or parent page, but rather in a

The task starts. For example, if a user initiates an activity in your application through a intent object that is called by another application, select

When you select the Action Bar icon to return to the home or parent page, the Flag_activity_clear_top logo launches in the task that belongs to your application.

Activity (not a current task). The system can either use this new activity as a root activity to start a new task, or it can

A saved task with this activity instance is brought to the foreground, and the target activity accepts the onnewintent () callback. So, if your activity

To receive the intent object for another application, you should typically add a flag_activity_new_task identity to the intent object, such as:

@Override Public Booleanonoptionsitemselected (MenuItem item) {Switch(Item.getitemid ()) { CaseAndroid. R.id.home://This was called when the Home (UP) button is pressed//In the Action Bar.Intent parentactivityintent =NewIntent ( This, Myparentactivity.class); Parentactivityintent.addflags (Intent.flag_activity_clear_top|intent.flag_activity_new_task);             StartActivity (parentactivityintent);             Finish (); return true; }     return Super. onoptionsitemselected (item);}

When the current activity is paged out from a task that belongs to a different app, the button should create a new task for that app.

@Override Public Booleanonoptionsitemselected (MenuItem item) {Switch(Item.getitemid ()) { CaseAndroid. R.id.home:intent upintent=NewIntent ( This, Myparentactivity.class); if(Navutils.shoulduprecreatetask ( This, Upintent)) {                 //This activity isn't part of the application's task, so create a new task//With a synthesized the back stack.Taskstackbuilder.from ( This). Addnextintent (NewIntent ( This, Mygreatgrandparentactivity.class). Addnextintent (NewIntent ( This, Mygrandparentactivity.class) . Addnextintent (upintent). Startactivities ();             Finish (); } Else {                 //This activity was part of the application ' s task, so simply//Navigate up to the hierarchical parent activity.Navutils.navigateupto ( This, upintent); }             return true; }     return Super. onoptionsitemselected (item);}

Second, the implementation of hierarchical navigation in the fragments

When using fragments in an application, a single Fragmenttransaction object can represent changes in the environment and should be added to the back stack.

For example, if you want to implement a master/detail process, by swapping out fragments, you should make sure that you click the Back button on the detail interface to rewind to

Master interface.

Getfragmentmanager (). BeginTransaction (). Add (Detailfragment, "detail")           //          . Addtobackstack ()         . commit ();

If the Fragmenttransaction object is on the back stack, the activity's Fragmentmanager handles the Click event of the Back button. When this

When an event occurs, Fragmentmanager pops the last transaction from the back stack and reverses the behavior. If your application updates the other

User interface elements to reflect the current fragment state, such as Action Bar, and remember to update the UI when a commit transaction is in effect.

Getfragmentmanager (). Addonbackstackchangedlistener (         new  Fragmentmanager.onbackstackchangedlistener () {             publicvoid  onbackstackchanged () {                  //             }         });

Third, navigate to the external interface

When activating another application's activity to allow users to write a message, or pick a photo attachment, you generally do not want the user to return to this interface when restarting the program in launcher. This can cause confusion for users. To prevent this from happening, simply add the flag_activity_clear_with_task_reset tag to the intent to start the external ACTIVITY:

New Intent (Intent.action_pick); Externalactivityintent.settype ("image/*"); Externalactivityintent.addflags (Intent.flag_activity_clear_when_task_reset); StartActivity (externalactivityintent);

Iv. Realization OF

Five, the project structure chart

Six, detailed code writing

1, the Code of this project is not many, the first is the main layout page, Activity_main.xml:

<relativelayout xmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:tools= "Http://schemas.android.com/tools"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent" > <Button Android:id= "@+id/other_btn"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:layout_centerhorizontal= "true"Android:layout_margintop= "160DP"Android:text= "Other_activity"/> <Button Android:id= "@+id/external_btn"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:layout_alignparentleft= "true"Android:layout_below= "@+id/other_btn"Android:text= "External_activity"/></relativelayout>

2, then the layout of another interface, Activity_other.xml:

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" Match_parent "    android:layout_height = "Match_parent" ></RelativeLayout>

3, main interface activity class, Mainactivity.java:

 Packagecom.yangyu.myactionbar04;ImportAndroid.app.ActionBar;Importandroid.app.Activity;Importandroid.content.Intent;ImportAndroid.os.Bundle;ImportAndroid.view.View; Public classMainactivityextendsActivity { Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main);    Initview (); }    /*** Initialize Components*/    Private voidInitview () {FinalActionBar ActionBar =Getactionbar (); Actionbar.sethomebuttonenabled (false);  This. Findviewbyid (R.ID.OTHER_BTN). Setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (view view) {Intent Intent=NewIntent (mainactivity. This, Otheractivity.class);            StartActivity (Intent);                }        });  This. Findviewbyid (R.ID.EXTERNAL_BTN). Setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (view view) {//call the picture browserIntent externalactivityintent =NewIntent (Intent.action_pick); Externalactivityintent.settype ("Image/*");                 Externalactivityintent.addflags (Intent.flag_activity_clear_when_task_reset);             StartActivity (externalactivityintent);    }         }); }}

4. Go to another activity interface, Otheractivity.java:

 Packagecom.yangyu.myactionbar04;ImportAndroid.app.ActionBar;Importandroid.content.Intent;ImportAndroid.os.Bundle;Importandroid.support.v4.app.FragmentActivity;Importandroid.support.v4.app.NavUtils;ImportAndroid.support.v4.app.TaskStackBuilder;ImportAndroid.view.MenuItem; Public classOtheractivityextendsfragmentactivity { Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);           Setcontentview (R.layout.activity_other); FinalActionBar ActionBar =Getactionbar (); Actionbar.setdisplayhomeasupenabled (true); } @Override Public Booleanonoptionsitemselected (MenuItem item) {Switch(Item.getitemid ()) { CaseAndroid. R.id.home:intent upintent=NewIntent ( This, Mainactivity.class); if(Navutils.shoulduprecreatetask ( This, Upintent)) {Taskstackbuilder.from ( This)                            //If there's a lot of primitive activity here, they should be added here .. Addnextintent (upintent). Startactivities ();                Finish (); } Else{Navutils.navigateupto ( This, upintent); }                return true; }        return Super. onoptionsitemselected (item); } }

Source

"Android UI design and development" phase 12th: Top title bar (iii) Actionbar to achieve the return effect of hierarchical navigation

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.