Android Actionbar Use tutorial _android

Source: Internet
Author: User

Actionbar Introduction Method:

There are several, starting with the Android 3.0 (API lever 11), all activity using the Theme.holo theme (or its subclasses) contains action Bar, when Targetsdkversion or minsdkversion property is set to "11" or greater, it is the default theme. In order to be compatible with the earlier versions of Android3.0, Actionbar is typically implemented through the appcompatactivity implementation of extends integration support packages, along with Theme.appcompat theme ( To remove Actionbar use Theme.AppCompat.NoActionBar themes or Theme.Holo.NoActionBar themes.
Note: If you want to use the Setsupportactionbar () method to add Actionbar, and you want to use the Actionbar theme, you must set the removal Actionbar,<item name= in the theme. Windowactionbar ">false</item>, the two can only retain one. Otherwise there will be an error:
java.lang.IllegalStateException:This activity already has a action bar supplied by the window decor. Don't request Window.feature_support_action_bar and set Windowactionbar to False in your theme to use a Toolbar instead.< /c1>

Toolbar Toolbar = (Toolbar) Findviewbyid (R.id.toolbar);
Setsupportactionbar (toolbar);
Note : even if the set <item name= "Windowactionbar" >false</item>, as long as the use of the Actionbar theme, Actionbar still exist, for the time being unknown

V4 Packs and V7 packs
The V4 package is designed for the Android 1.6 (API level 4) and above, and contains APIs that are not available in most of the newer versions, including application components, user interface features, accessibility, data handling, network connectivity, and programming utilities, providing fragment, Compatibility of later versions of Viewpager such as Android3.0:
Fragment: It allows the same program to fit a different screen.
Notificationcompat: To support a richer form of notification;
Localbroadcastmanager: Used to send broadcast between different components within the same application.

V7 package is the Android 2.1 (API level 7) and above the version of Google offers a series of support packs
This library adds support for the Action Bar user interface design pattern. This library includes a user interface implementation that supports material design.
Note: This library relies on the V4 Support library.
Here are some key classes included in the V7 AppCompat library:
Actionbar: Providing Actionbar user interface model implementation
Appcompatactivity: Adds an activity class that can be used as a base class for activity that supports Actionbar implementations.
Appcompatdialog: Adds a dialog box class that can be used as a base class for AppCompat theme dialogs.
Shareactionprovider: Add a standardized shared action (such as email or send to a social networking site), included in the Actionbar.

In order to use fragment in a version prior to 3.0 we will inherit the fragmentactivity under the Support V4 package, and if you want to use Actionbar before 3.0, you need to inherit support The actionbaractivity under the V7 package, using the Theme.holo series theme, Actionbaractivity is inherited from Fragmentactivity. V7 package Update after Android5.0, use Actionbar to inherit appcompatactivity from V7 package, while providing a series of new Actionbar topics (THEME.APPCOMPAT)
1. Add left back button:
Add ancestor activity:android:parentactivityname= to the activity in the manifest file. Activity. Imageshowactivity "
Call the Actionbar setdisplayhomeasupenabled (True) method to set the upper left corner to return the icon, default is the left arrow

Getsupportactionbar (). Setdisplayhomeasupenabled (true);
  If your minsdkversion property is 11 or higher, you should use this:
  //Getactionbar (). Setdisplayhomeasupenabled (True);

Note: If your compiled version Compilesdkversion 23 is higher than Android5.0 (API level 21), just declare the parent activity in the manifest file. Less than 21 lower version is not tested. Also, if Getactionbar (). Setdisplayhomeasupenabled (False) is set actively, the return button must be canceled

Note: A tip for rollback activity: The Itent object includes the Flag_activity_clear_top identity. With this tag, if the activity you want to start is already present in the current task, then all of the tasks on the stack are destroyed and displayed to the user.
Note: This return does not preserve data in the previous activity, nor can you use the Onsaveinstance () method to save
This requires special processing, in the Onoptionsitemselected method of replication, to determine whether the current activity and the target parent active instance are on the same task stack, emptying the instance above the target parent activity instance on the same task stack, and start the target parent instance on the same task stack. Otherwise create a new task stack to start. The idea is that the upward navigation here is different from the fallback simple finish instance, where you want to jump back to the main activity.

 @Override Public
  Boolean onoptionsitemselected (MenuItem item) {
    switch (Item.getitemid ()) {case
      Android. R.id.home:
        toastutils.show (This, "home");
        Intent upintent = Navutils.getparentactivityintent (this);
        Determine if the current activity is navigating up to the target intent upintent whether a new task stack needs to be rebuilt,
        if (Navutils.shoulduprecreatetask (this, upintent)) {
          // Rebuild the new task stack
          taskstackbuilder.create (this)
              . Addnextintentwithparentstack (upintent)
              . Startactivities () ;
        } else {
          ///Use the current task stack
          upintent.addflags (intent.flag_activity_clear_top);//Empty all instances
          above the target activity instance on the task stack Navutils.navigateupto (this, upintent);//directly on the same task stack jump
        } return
        true;//consume event
    }
    return super.onoptionsitemselected (item);
  }

Custom home:
also suppresses the upper left corner return button

 /* Set the top left corner logo icon*/
    Actionbar.setlogo (r.drawable.go_back_64px);//(Separate settings do not work)
    Actionbar.setdisplayshowhomeenabled (true);/whether the logo is displayed, must be Setlogo () for him to function
    actionbar.setdisplayuselogoenabled ( true)/whether to use the logo of the activity, that is, the logo actionbar.setdisplayhomeasupenabled (false) set by the Setlogo () method,
 
    or whether to display the default return button in the upper left corner
    actionbar.sethomebuttonenabled (FALSE);//button can be clicked (measured useless, false can still click--has set the activity's parent activity)

To set the color of a caption:
It is not effective to set the test directly in the subject of the activity or in the subject of Actionbar. You can add the theme style of the text by setting the TitleTextStyle attribute for the activity or Actionbar theme, which needs to be inherited from the @android:style/textappearance:

<!--set the color of the caption, note the use of the properties under the Compatibility Pack-->
    <item name= "Android:titletextstyle" > @style mytheme.actionbar.titletextstyle</item>
    <item name= "TitleTextStyle" > @style mytheme.actionbar.titletextstyle</item>
 <style name= "MyTheme.ActionBar.TitleTextStyle" parent= "@ Android:style/textappearance.holo.widget.actionbar.title ">
    <item name=" Android:textcolor "> @color blue</item>
    <item name= "android:textsize" >16sp</item>
  </style>

Note that if you use the Actionbar in support, you need to use attribute TitleTextStyle instead of android:titletextstyle, otherwise the color set will not take effect.
set Actionbar float:
Use the Hide () method to hide the Actionbar when you do not show it
Rewrite the Ontouchevent () method of the activity:

 @Override Public
  Boolean ontouchevent (Motionevent event) {
    log.d ("Debug", "Ontouchevent");
    if (Actionbar = = null) {
      Actionbar = Getsupportactionbar ();
    }
    Switch (event.getaction ()) {case
      motionevent.action_up:
//        if (Actionbar!= null) {
        if ( Actionbar.isshowing ()) {
          //hidden
          actionbar.hide ();
        } else {
          //display
          actionbar.show ();
        }        } break
        ;
    Return Super.ontouchevent (event);
  }

To set the layout of an activity not to be redrawn when Actionbar is hidden:
Resizing the layout while the action bar is hidden and displayed affects the visual experience.
API level 19 and above required: set content to populate the system status bar, there is no problem with the re-layout

Copy Code code as follows:
GetWindow (). SetFlags (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_ Translucent_status);

Or add attributes for the activity topic:
<item name= "Android:windowtranslucentstatus" >true</item>
The Official document gives the following method: Set overlay mode, not limited to version

 <item name= "Android:windowactionbaroverlay" >true</item>
    <!--compatible support library-->
    <item name= " Windowactionbaroverlay ">true</item>

To set the system status bar
Before android4.4, there was always a dark system status bar on top of the app, and a transparent status bar effect (translucent system bar) was introduced after 4.4, allowing the app to use all the screens while making the system status bar and navigation bar translucent
In the subject of activity

 <item name= "Android:windowtranslucentstatus" >true</item>
    <item name= "Android: Windowtranslucentnavigation ">true</item>
//In addition, you can set the color of the system status bar: Apply to the page is pure color:
<item name=" Android:windowtranslucentstatus ">false</item>
    <item name=" Android:windowtranslucentnavigation " >true</item>
    <item name= "Android:statusbarcolor" > @android:color/transparent</item>

Here for reference: Best practices for translucent System Bar-android-Bole online

Set Menu menu does not mask Acionbar:
using the Actionbar under the support V7 Package, the default menu will top up to the top of the screen, blocking to the actionbar, and the desired effect is that the menu is located below the Actionbar.
Add attributes to the subject of the activity: Actionoverflowmenustyle

<!--set Menu menu does not mask actionbar-->
    <item name= "Actionoverflowmenustyle" > @style/overflowmenu</item >
//create this theme, inherit from theme Widget.AppCompat.PopupMenu
 <style name= "Overflowmenu" parent= " Widget.AppCompat.PopupMenu.Overflow ">
    <!--Compatibility API 21 prior to version-->
    <item name=" Overlapanchor "> True</item>
 
    <!--Api 21-->
    <!--<item name= "Android:overlapanchor" >false</item> -->
  </style>

To remove left-side whitespace from the left-hand button:
when the setting does not show the back button in the upper left corner, the left margin is still displayed.

To set menu menus:
1. Cancel Menu:
The Oncreateoptionsmenu method of the replication returns false, or the method is no longer written.
To set the menu button color:
Note Set the subject of the activity instead of the Actionbar theme:

 <!--set Menu text color-->
    <!--<item name= "Actionmenutextcolor" > @color/yellow</item>-->
    <!--<item name= "Android:actionmenutextcolor" > @color/yellow</item>-->
    <!-- The above two settings are invalid-->
    <item name= "android:itemtextappearance" > @style/mycustommenutextapearance</item >
 <style name= "mycustommenutextapearance" parent= "@android: Style/textappearance.widget.iconmenu.item" >
    <!--text color-->
    <item name= "Android:textcolor" > @color/blue</item>
    <!--text Size-- >
    <item name= "android:textsize" >16sp</item>
  </style>

2. Set Menu background color:
is also set in the subject of the activity

 <!--s Sets the background color of the menu-->
    <item name= "Android:itembackground" > @color/black_light</item>

3. Customize Menu Menu items:
In addition to using a system-given action, you can customize it by using the action view and action provider, which is a menu item that can provide visual effects and interactivity.
Also define item in menu, you need to use one of Actionviewclass and Actionlayout, where actionviewclass specifies the name of the control class used, such as the search control Searchview, ACTIONLAYOUT specifies your own defined layout file as the view of the action.
Actionviewclass:the Class of a widget that implements the action.
Actionlayout:a layout Resource describing the action ' s components.
1. Use Actionviewclass to add a system search item:
Add Item:

<item android:id= "@+id/action_search"
   android:title= "@string/action_search" android:icon= "
   @drawable Ic_search "
   app:showasaction=" Ifroom|collapseactionview "
   app:actionviewclass=" Android.support.v7.widget.SearchView "/>

Handling Search Events: Using the FindItem () method of the menu to get a reference to the control, the listener that binds the text query

 @Override Public
  Boolean oncreateoptionsmenu (Menu menu) {
    //inflate the menu; This adds items to the Action bar I F it is present.
    Getmenuinflater (). Inflate (R.menu.menu_main, menu);
    Find the way to add UI components on Actionbar:
    Msearchview = (searchview) menu.finditem (R.id.searchitem). Getactionview ();
    Msearchview.setonquerytextlistener (New Searchview.onquerytextlistener () {
      @Override public
      Boolean Onquerytextsubmit (String string) {
        Toast.maketext (showimageactivity.this, "Query:" + String, Toast.length_short). Show ();
        return false;
      }
 
      @Override Public
      Boolean Onquerytextchange (String string) {return
        true;
      }
    });

The item is set with the app:showasaction= "Ifroom|collapseactionview" attribute, where collapseactionview meaning is no interactive action (when not clicked) The search item is closed to show only icon, When there is an interaction, the item expands to fill the actionbar remaining space. Paired with Ifroom indicates that there is space to show on app Bar, when there is no room for the menu item.never as the menu item. Always says it's been shown on app bar.

2. Add a custom search control by using Actionlayout
Add Item

<item
    android:id= "@+id/custom_search"
    android:icon= "@drawable/ic_action_search" android:title= "
    Custom_search "
    app:actionlayout=" @layout/search_layout "
    app:showasaction=" collapseactionview|always| Withtext "/>

Layout file: Search_layout.xml

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android=
"http://schemas.android.com/apk/" Res/android "
  android:layout_width=" 200DP "
  android:layout_height=" wrap_content "
  android:gravity=" Center_vertical "
  android:orientation=" horizontal "
  android:padding=" 5DP ">
 
  <imageview
    Android:layout_width= "Wrap_content"
    android:layout_height= "wrap_content"
    android:padding= "5DP"
    android:src= "@drawable/ic_action_search"/>
 
  <edittext
    android:layout_width= "200DP"
    Android : layout_height= "wrap_content"
    android:layout_weight= "1"/>
</LinearLayout>

Also, if you set the app:showasaction= "Collapseactionview" attribute, you can listen for shouqi/expansion events: In the Oncreateoptionsmenu (Menu menu) method

MenuItem Collapseactionview = Menu.finditem (R.id.searchitem);
    Define the listener
    menuitemcompat.onactionexpandlistener Expandlistener = new Menuitemcompat.onactionexpandlistener () {
      @Override public
      boolean onmenuitemactioncollapse (MenuItem Item) {
        //do something when action item collapses
        toastutils.show (showimageactivity.this, "Action item collapses"); C7/>return true; Return true to collapse action view
 
      }
 
      @Override public
      boolean Onmenuitemactionexpand (MenuItem item) { c11/>//do something when expanded
        toastutils.show (showimageactivity.this, "Action item expanded");
        return true; return true to expand action View
      }
    ;
    Menuitemcompat.setonactionexpandlistener (Collapseactionview, Expandlistener);

This is the Android Actionbar tutorial that I hope will help you learn about Android software programming.

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.