Android toolbar use and toolbar processing in fragment

Source: Internet
Author: User

Toolbar as an introduction to Actionbar use

This article describes how to use toolbar as a Actionbar in Android.
It also describes things to be aware of when using toolbar as Actionbar in fragment and nested fragment.

Using the Support Library's toolbar

Android Actionbar Each version will make some changes, so the native actionbar may look different on various systems.
Use the Support library version of toolbar to keep your app consistent across multiple device types. The support library always contains the latest features.
Android from 5.0 (API level 21) to provide material Design, using the V7 version of toolbar, on any Android 2.1 (API level 7) above the machine can see material Design-style toolbar.

Using toolbar in Activity

1. First add the item Gradle:

' com.android.support:appcompat-v7:23.4.0 '

2. Ensure activity InheritanceAppCompatActivity

3. Use the Noactionbar theme in the application settings:

<application    android:theme="@style/theme.appcompat.light.noactionbar"     />

4. Write the toolbar in the layout

<Android.support.v7.widget.Toolbar Android:id="@+id/my_toolbar"Android:layout_width="match_parent"Android:layout_height="? attr/actionbarsize"Android:background="? attr/colorprimary"android:elevation="4DP"Android:theme="@style/themeoverlay.appcompat.actionbar"App:popuptheme="@style/themeoverlay.appcompat.light"/>

5. Set toolbar as Actionbar in activity

First put toolbar find out and then call the Setsupportactionbar method
Set the toolbar to your own actionbar.

 Public class Toolbardemoactivity extends Appcompatactivity {    @BindView (r.id.toolbar)    toolbar toolbar;    @Override    protectedvoid  onCreate (Bundle savedinstancestate) {        super.oncreate ( Savedinstancestate);        Setcontentview (R.layout.activity_toolbar_demo);        Butterknife.bind (this);        Setsupportactionbar (toolbar);    }}

Then you can use the Getsupportactionbar to get the Actionbar type of object and use the Actionbar method.

Add Action Buttons

Define Menu:

<?xml version="1.0"encoding="Utf-8"? ><menu xmlns:android="http://schemas.android.com/apk/res/android"Xmlns:app="Http://schemas.android.com/apk/res-auto"> <Item Android:id="@+id/action_android"Android:icon="@drawable/IC_ANDROID_BLACK_24DP"Android:title="@string/action_android"app:showasaction=" always"/> <Item Android:id="@+id/action_favourite"Android:icon="@drawable/IC_FAVORITE_BLACK_24DP"Android:title="@string/action_favourite"app:showasaction="Ifroom"/> <Item Android:id="@+id/action_settings"Android:title="@string/action_settings"app:showasaction="never"/></menu>

Then inflate and handle its click events in the code:

@Override Publicboolean Oncreateoptionsmenu (Menu menu) {log.i (TAG,"Oncreateoptionsmenu ()");    Getmenuinflater (). Inflate (R.menu.menu_activity_main, menu); returnsuper.oncreateoptionsmenu (menu);} @Override Publicboolean onoptionsitemselected (MenuItem item) {Switch(Item.getitemid ()) { Caser.id.action_android:log.i (TAG,"Action Android selected"); return true;  Caser.id.action_favourite:log.i (TAG,"Action Favourite Selected"); return true;  Caser.id.action_settings:log.i (TAG,"Action Settings selected"); return true; default:            returnsuper.onoptionsitemselected (item); }}

Add an action to return up

Add an action that returns parent:

@Override protected void onCreate (Bundle savedinstancestate) {    super.oncreate (savedinstancestate);    Setcontentview (R.layout.activity_toolbar_demo);    Butterknife.bind (this);    Setsupportactionbar (toolbar);     // Add a left arrow to the back to parent activity    , // no need to handle action selected event, this was handled by Super    Getsupportactionbar (). setdisplayhomeasupenabled (true);

Then you only need to specify the parent in manifest:

<activity    android:name=". toolbar. Toolbardemoactivity"    android:parentactivityname=". Mainactivity"></activity>

Using toolbar in Fragment

The steps to use toolbar in fragment are similar to the activity.
Add a toolbar to the fragment layout and find it, and then call the activity method to set it to Actionbar:

((appcompatactivity) getactivity ()). Setsupportactionbar (toolbar);

Note that there is a strong turn, it must be appcompatactivity to have this method.

However, after running to fragment, it is found that the text and buttons on the toolbar all come from the activity, because only the activity is onCreateOptionsMenu() called, but fragment is not called.
Add this sentence to the fragment:

Sethasoptionsmenu (true);

At this point the fragment onCreateOptionsMenu() callback is transferred, but the inflate button is displayed together with the actions in the activity.

Because the activity onCreateOptionsMenu() will be called before.
So in the fragment wrote this:

@Override  Public void Oncreateoptionsmenu (Menu menu, Menuinflater inflater) {    "oncreateoptionsmenu ()  ");    Menu.clear ();    Inflater.inflate (r.menu.menu_parent_fragment, menu);}

That is clear () first, so that the button is only set in the fragment of their own, there will be no activity in the button.

Using toolbar in nested sub-fragment

As already described earlier, fragment can be nested using: Android fragment use (ii) nesting fragments (Nested fragments) and common errors.
So in front of the fragment again show a sub-fragment, and with a different toolbar, what else do you need to deal with?
First, there is still a need in Java code:

Sethasoptionsmenu (true) ((appcompatactivity) getactivity ()). Setsupportactionbar (toolbar);

Then, depending on whether you need a menu button, overwrite the Oncreateoptionsmenu () method to inflate your menu file.

There is no difference between feeling and using toolbar as Actionbar in ordinary fragment.
But if you have multiple fragment with different toolbar menu options, there may be some confusion if you don't understand the principles.
Here's a look at the relevant methods.

Invocation of the Oncreateoptionsmenu () method

Once called

((appcompatactivity) getactivity ()). Setsupportactionbar (toolbar);

Will cause the activity onCreateOptionsMenu() method to be called, and the activity will invoke fragment based on whether fragment is set to Sethasoptionsmenu (true).
onCreateOptionsMenu()method, the invocation order is tree-shaped, called hierarchically, and skips if there is false in the middle.

Assuming the current activity, both the Parent fragment and the child fragment set their own toolbar to Actionbar.
When you open the child fragment, onCreateOptionsMenu() the order of the calls is.
Activity -> Parent -> Child.The parent and child fragment are now set to Sethasoptionsmenu (true).

Here are a few more things to do:

- 如果Parent的`setHasOptionsMenu(false)`, Child为true, 则Parent的`onCreateOptionsMenu()`不会调用, 打开Child的时候Activity -> Child.- 如果Child的`setHasOptionsMenu(false)`, Parent为true, 则打开Child的时候仍然会调用Activity和Parent的onCreateOptionsMenu()方法.- 如果Parent和Child都置为false, 打开Parent和Child Fragment的时候都会调用Activity的onCreateOptionsMenu()方法.

Only the switch of the Child Fragment Show () hide (), activity and parent fragment's Oncreateoptionsmenu () will also be re-entered.
This point I have not thought to understand, is encountered in the project, the preliminary speculation may be the menu of the obvious changes invalidate the menu, another time to try again.

The mechanism above is often the cause of confusion on the buttons above the toolbar.
example:
If we now have different fragment buttons for activity and Parent toolbar, But the child has only text and no buttons.
Oncreateoptionsmenu () method in child.
But at this point, the Oncreateoptionsmenu () method of the parent is called, so that when we open the child, The button on the parent is magically appearing on the toolbar.

@Override  Public void Oncreateoptionsmenu (Menu menu, Menuinflater inflater) {    "oncreateoptionsmenu ()" );    Menu.clear ();     if 0 {        inflater.inflate (r.menu.menu_parent_fragment, menu);}    }

In addition, setSupportActionBar() if we want to actively trigger onCreateOptionsMenu() the invocation of the method, we can use the

invalidateOptionsMenu()Method.

Invocation of the onoptionsitemselected () method

When the activity and the fragment have Options menu, note that the ID of the menu item should not be duplicated.
The distribution of click events is also distributed from activity, and if the ID of an option in child fragment duplicates the ID of an option in activity, it will be processed in the activity and will not continue to be distributed.

Back key processing with nested fragment

In the absence of nested fragment, as long as the fragment is added to the back stack, the pop action is automatically done when the back button is pressed.
While adding child fragment to the back stack, pressing the back key still pops the parent fragment, leaving only the activity.
This is because the back key only checks the back stack of the first layer of fragment, and for child fragment, it needs to be handled by itself in its parent.
For example, this process:

In the activity

@Override  Public void onbackpressed () {    = getsupportfragmentmanager (). Findfragmentbyid (Android. r.id.content);     if (fragment instanceof toolbarfragment) {        if  (((toolbarfragment) fragment). onbackpressed ()) {            return;        }    }    Super.onbackpressed ();}

Where Toolbarfragment is directly added to the activity as the parent fragment.

In the parent fragment (that is, in toolbarfragment):

 Public Boolean onbackpressed () {    return  Getchildfragmentmanager (). Popbackstackimmediate ();}

This demo address: demo on GitHub

One of: Toolbardemoactivity is the toolbar Demo.
This article address: Android fragment use (iv) toolbar use and toolbar processing in fragment

Android toolbar use and toolbar processing in fragment

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.