SoFunction
Updated on 2025-03-11

Android ActionBar usage tutorial

How to introduce ActionBar:

There are several types, starting with Android 3.0 (API lever 11), all activities that use the theme (or its subclass) contain an action bar, which is the default theme when the targetSdkVersion or minSdkVersion property is set to "11" or greater. In order to be compatible with the lower versions before Android 3.0, actionbar is usually implemented through the AppCompatActivity integrated under the Support package by extends, and the ActionBar theme is required (you just need to remove the ActionBar and use the theme or theme).
Note: If you want to add ActionBar using the setSupportActionBar() method, then you also want to use the ActionBar theme, then you must set the Actionbar in the theme to remove the Actionbar, <item name="windowActionBar">false</item>, and only one of them can be retained. Otherwise, an error will be reported:
: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.

        Toolbar toolbar = (Toolbar) findViewById();
        setSupportActionBar(toolbar);
NoteEven if you set <item name="windowActionBar">false</item>, as long as the theme of ActionBar is used, ActionBar still exists. The reason is unknown for the time being

V4 and V7 packages
The V4 package is designed for Android 1.6 (API Level  4) and above. It contains most APIs that are available in higher versions but not in lower versions, including application components, user interface features, accessibility, data handling, network connectivity, and programming utilities, and provides compatibility with higher version features after Android 3.0, such as Fragment and ViewPager:
Fragment: This allows the same program to adapt to different screens.
NotificationCompat: supports richer notification forms;
LocalBroadcastManager: Used to send Broadcasts between different components in the same application.

V7 package is Android 2.1 (API Level 7) and above versions Google provides a series of support packages
This library adds support for Action Bar user interface design mode. This library includes user interface implementations that support material design.
Note: This library depends on the v4 Support Library.
Here are some key classes included in the v7 appcompat library:
ActionBar: Provides the implementation of ActionBar user interface mode
AppCompatActivity: Add an Activity class, which can be used as a base class to support Activity implemented by ActionBar.
AppCompatDialog: Add a dialog class that can be used as a base class for appcompat theme dialog boxes.
ShareActionProvider: Adds a standardized shared action (such as email or sending to social networking sites), included in ActionBar.

In order to use Fragment in versions before 3.0, we need to inherit the FragmentActivity under Support v4 package. If you want to use ActionBar in versions before 3.0, you need to inherit the ActionBarActivity under Support V7 package. Use the series themes. ActionBarActivity is inherited from FragmentActivity. After Android 5.0, V7 packages are updated. Using ActionBar can inherit the AppCompatActivity in the V7 package, and also provides a series of new ActionBar themes ( )
1. Add the left return button:
Add the upper Activity for Activity in the manifest file: android:parentActivityName="."
At the same time, call the setDisplayHomeAsUpEnabled(true) method of ActionBar to set the return icon in the upper left corner, the default is the left arrow

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
  // If your minSdkVersion property is 11 or higher, it should be used like this:  // getActionBar().setDisplayHomeAsUpEnabled(true);

Note: If your compiled version compileSdkVersion 23 is higher than Android 5.0 (API level 21), you can only declare the parent activity in the Manifest file. Not tested earlier than 21. At the same time, if getActionBar().setDisplayHomeAsUpEnabled(false); the return button will definitely be cancelled

Note: A trick to roll back the activity: Include the FLAG_ACTIVITY_CLEAR_TOP flag in the Itent object. With this markup, if the activity you want to start already exists in the current task, then all the activities on the stack above the activity will be destroyed and the activity will be displayed to the user.
Note: This return will not retain the data in the previous Activity, nor can it be saved using the onSaveInstance() method.
At this time, special processing is required. In the rewrite onOptionsItemSelected method, determine whether the current Activity and the target parent Activity instance are on the same task stack. On the same task stack, clear the instance on the target parent Activity instance and start the target parent instance on the same task stack. Otherwise, create a new task stack to start. The original intention of this is that the upward navigation here is different from the simple finishing instance fallback. Here I hope to return to the main activity in a leapfrog manner.

 @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (()) {
      case :
        (this, "home");
        Intent upIntent = (this);
        //Judge whether the current Activity is navigating up to the target Intent upIntent needs to rebuild a new task stack.        if ((this, upIntent)) {
          //Rebuild a new task stack          (this)
              .addNextIntentWithParentStack(upIntent)
              .startActivities();
        } else {
          //Use the current task stack          (Intent.FLAG_ACTIVITY_CLEAR_TOP);//Clear all instances on the target Activity instance in the task stack          (this, upIntent);//Jump directly on the same task stack        }
        return true;//Consumption event    }
    return (item);
  }

Custom Home:
Cancel the upper left corner return button to display

 /*Set the upper left corner Logo Icon*/
    (.go_back_64px);//(Single setting does not work)    (true);// Whether to display the logo, it must be setLogo() for it to work    (true);//Whether to use the Activity logo, that is, the logo set by the setLogo() method 
    (false);// Whether to display the default return button in the upper left corner    (false);//Is the button clickable (actual test is useless, you can still click under false - the parent activity of the activity has been set)

Set the color of the title:
Setting it directly in the activity topic or in the ActionBar topic according to the test will not take effect. You can add the theme style of text by setting the titleTextStyle property for Activity or Actionbar theme. This style needs to be inherited from @android:style/TextAppearance:

&lt;!--Set the color of the title,Pay attention to using the properties under the compatible package--&gt;
    &lt;item name="android:titleTextStyle"&gt;@style/&lt;/item&gt;
    &lt;item name="titleTextStyle"&gt;@style/&lt;/item&gt;
 &lt;style name="" parent="@android:style/"&gt;
    &lt;item name="android:textColor"&gt;@color/blue&lt;/item&gt;
    &lt;item name="android:textSize"&gt;16sp&lt;/item&gt;
  &lt;/style&gt;

Note that if you use the ActionBar in Support, you need to use the property titleTextStyle instead of android:titleTextStyle, otherwise the set color will not take effect.
Set Actionbar float:
The method is: use hide() method to hide when you do not display ActionBar
Rewrite the onTouchEvent() method of the Activity:

 @Override
  public boolean onTouchEvent(MotionEvent event) {
    ("debug", "onTouchEvent");
    if (actionBar == null) {
      actionBar = getSupportActionBar();
    }
    switch (()) {
      case MotionEvent.ACTION_UP:
//        if (actionBar != null) {
        if (()) {
          //hide          ();
        } else {
          //show          ();
        }
//        }
        break;
    }
    return (event);
  }

Set the layout of the Activity not to redraw when the Actionbar is hidden:
Adjusting the layout size during the action bar hiding and displaying process will greatly affect the visual experience.
Requires API level 19 and above: Set content to fill the system status bar, there is no problem of re-layout

Copy the codeThe code is as follows:
getWindow().setFlags(.FLAG_TRANSLUCENT_STATUS, .FLAG_TRANSLUCENT_STATUS);

Or add properties to the Activity topic:
<item name="android:windowTranslucentStatus">true</item>
The method given by the official document is: set the overlay mode, unlimited version

 &lt;item name="android:windowActionBarOverlay"&gt;true&lt;/item&gt;
    &lt;!-- Compatible Support Library --&gt;
    &lt;item name="windowActionBarOverlay"&gt;true&lt;/item&gt;

Set the system status bar
Before android 4.4, the black system status bar was always retained above the app. After 4.4, the transparent status bar effect (Translucent System Bar) was introduced, so that the app can use all screens, and the system status bar and navigation bar are translucent.
In the theme of Activity

 &lt;item name="android:windowTranslucentStatus"&gt;true&lt;/item&gt;
    &lt;item name="android:windowTranslucentNavigation"&gt;true&lt;/item&gt;
//In addition, you can also set the color of the system status bar: it is a simple color for the page:&lt;item name="android:windowTranslucentStatus"&gt;false&lt;/item&gt;
    &lt;item name="android:windowTranslucentNavigation"&gt;true&lt;/item&gt;
    &lt;item name="android:statusBarColor"&gt;@android:color/transparent&lt;/item&gt;

Reference here: Best Practices for Translucent System Bar - Android - Bole Online

Set Menu menu not to obscure AcionBar:
Using the ActionBar under Support V7 package, the default Menu menu will reach the top of the screen and block the Actionbar. The desired effect is that the Menu is located below the ActionBar.
Add properties in the theme of Activity: actionOverflowMenuStyle

&lt;!--set upmenuThe menu is not blockedactionbar--&gt;
    &lt;item name="actionOverflowMenuStyle"&gt;@style/OverflowMenu&lt;/item&gt;
//Create this topic, inherit from the topic &lt;style name="OverflowMenu" parent=""&gt;
    &lt;!--compatibleApi 21Previous version --&gt;
    &lt;item name="overlapAnchor"&gt;true&lt;/item&gt;
 
    &lt;!-- Api 21--&gt;
    &lt;!--&lt;item name="android:overlapAnchor"&gt;false&lt;/item&gt;--&gt;
  &lt;/style&gt;

Eliminate the left blank space on the button on the left:
After setting the return button in the upper left corner does not display, the blank on its left is still displayed.

Set Menu Menu:
1. Cancel menu:
The onCreateOptionsMenu method can return false, or the method will not be copied.
Set the color of Menu menu button:
Note that you set the theme of the Activity instead of the theme of the Actionbar:

 &lt;!--set upmenuText color--&gt;
    &lt;!--&lt;item name="actionMenuTextColor"&gt;@color/yellow&lt;/item&gt;--&gt;
    &lt;!--&lt;item name="android:actionMenuTextColor"&gt;@color/yellow&lt;/item&gt;--&gt;
    &lt;!--上面两个set up是无效的--&gt;
    &lt;item name="android:itemTextAppearance"&gt;@style/myCustomMenuTextApearance&lt;/item&gt;
 &lt;style name="myCustomMenuTextApearance" parent="@android:style/"&gt;
    &lt;!--Text color--&gt;
    &lt;item name="android:textColor"&gt;@color/blue&lt;/item&gt;
    &lt;!--Text size--&gt;
    &lt;item name="android:textSize"&gt;16sp&lt;/item&gt;
  &lt;/style&gt;

2. Set the background color of the Menu menu:
It is also set in the activity theme

 &lt;!--sset upMenuMenu background color--&gt;
    &lt;item name="android:itemBackground"&gt;@color/black_light&lt;/item&gt;

3. Customize Menu Menu Items:
In addition to using the action given by the system, it can also be customized. This requires the use of the action view and action provider. Personally, it is a menu item that can provide visual effects and interactive functions.
To define an item in Menu, you need to use one of actionViewClass and actionLayout, where actionViewClass specifies the control class name used, such as search control SearchView, and actionLayout specifies the layout file you define 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:
   android:title="@string/action_search"
   android:icon="@drawable/ic_search"
   app:showAsAction="ifRoom|collapseActionView"
   app:actionViewClass="." />

Handle search events: get the reference to the control through menu's findItem() method and bind the listener for text query

 @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(.menu_main, menu);
    //How to find the UI component added on ActionBar:    mSearchView = (SearchView) ().getActionView();
    (new () {
      @Override
      public boolean onQueryTextSubmit(String string) {
        (, "Query:" + string, Toast.LENGTH_SHORT).show();
        return false;
      }
 
      @Override
      public boolean onQueryTextChange(String string) {
        return true;
      }
    });
}

The above is set for the item with the app:showAsAction="ifRoom|collapseActionView" attribute, where the meaning of collapseActionView is that when there is no interactive action (when not clicked), the search item is closed and only the icon is displayed. When there is interaction, the item expands and fills the remaining space of the actionbar. When paired with ifRoom, it means it is displayed on the App bar when there is space, and when there is no space, it means it is always used as menu item. Always says it has been displayed on the App bar.

2). Use actionLayout to add a custom search control
Add item

<item
    android:
    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:andro
  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>

At the same time, if the property app:showAsAction="collapseActionView" is set, you can also listen to shouqi/expand events: in the onCreateOptionsMenu(Menu menu) method

MenuItem collapseActionView = ();
    // Define the listener
     expandListener = new () {
      @Override
      public boolean onMenuItemActionCollapse(MenuItem item) {
        // Do something when action item collapses
        (, "action item collapses");
        return true; // Return true to collapse action view
 
      }
 
      @Override
      public boolean onMenuItemActionExpand(MenuItem item) {
        // Do something when expanded
        (, "action item expanded");
        return true; // Return true to expand action view
      }
    };
    (collapseActionView, expandListener);

The above is the Android ActionBar usage tutorial. I hope it will be helpful for everyone to learn Android software programming.