Basic Android ActionBar usage

Source: Internet
Author: User

This article translated this article: Using the Android action bar (ActionBar)-Tutorial

1. ActionBar Overview
The ActionBar is located at the top of the Activity and can be used to display the activity title, Icon, Actions, and some views for interaction. It can also be used for application navigation.
ActionBar is added to SK in Android 3.0 (API 11). To use ActionBar in earlier versions, you have two options: Use a http://actionbarsherlock.com or use Support Library v7.
The following is an ActionBar interface:

[1] is the ActionBar icon, [2] is two action buttons, and [3] is the overflow button.

2. Use ActionBar

To develop a program below API11, you must first specify the theme of the Application or Activity in AndroidManifest. xml as Theme. Holo or its subclass. Otherwise, ActionBar cannot be used.

2.1 create Actions

Actions is each interaction item in the ActionBar. You can create an Action in the code or specify it in the XML file (IN res/menu ). To define an Action in the menu resource file, follow these steps:

     
      
      
  
  
The showAsAction attribute defines how each Action is displayed.
Always displayed in ActionBar. If the screen space is insufficient, it cannot be displayed. ifRoom indicates that the screen space is displayed in ActionBar when the screen space is sufficient, and if the screen space is insufficient, it will be displayed in overflow, never indicates that it is always displayed in overflow.
The Action code for creating a ctionBar in the Activity is located in onCreateOptionsMenu (). The following code shows the creation process:

@Override  public boolean onCreateOptionsMenu(Menu menu) {    MenuInflater inflater = getMenuInflater();    inflater.inflate(R.menu.mainmenu, menu);    return true;  } 
2.2 button interaction of Action

If an Action is clicked, onOptionsItemSelected () in the activity will be called. The input parameter of this function is a MenuItem. By judging the MenuItem Id, you can determine which Action is clicked. The following code shows how to use the function.

Override  public boolean onOptionsItemSelected(MenuItem item) {    switch (item.getItemId()) {    // action with ID action_refresh was selected    case R.id.action_refresh:      Toast.makeText(this, "Refresh selected", Toast.LENGTH_SHORT)          .show();      break;    // action with ID action_settings was selected    case R.id.action_settings:      Toast.makeText(this, "Settings selected", Toast.LENG          .show();      break;    default:      break;    }    return true;  } 

OnCreateOptionsMenu () is called only once. If you want to change the Menu, you can call invalidateOptionsMenu (). This will make onCreateOptionsMenu () be called again.
3. Custom ActionBar
3.1 change the display of ActionBar
To display and hide an ActionBar at runtime, follow these steps:

ActionBar actionBar = getActionBar();actionBar.hide();// more stuff here...actionBar.show(); 
You can change the text displayed next to the program icon, as shown below:

ActionBar actionBar = getActionBar();actionBar.setSubtitle("mytest");actionBar.setTitle("vogella.com"); 
3.2 hide navigation buttons
You can use the following code to hide the navigation button.

getWindow().  getDecorView().  setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); 
3.3 Use full screen mode
The full screen mode can be used for Android 4.4 (API 19) applications, as shown in the following code.

// This method hides the system bars and resize the content  private void hideSystemUI() {    getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar            | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar            // remove the following flag for version < API 19            | View.SYSTEM_UI_FLAG_IMMERSIVE);   } 
3.4 use Split action bar
When the screen is very narrow (such as in portra mode), you can use the Split action bar to display all the actions at the bottom of the screen, in this way, more meaningful elements such as navigation and titles are displayed on the top of the activity.
Enable split action bar to define android: uiOptions = "SplitActionBarWhenNarrow" in AndroidManifest. xml"
4. Add action to action bar in Fragment
Call setHasOptionsMenu (true) in onCreate ). Android Framework calls onCreateOptionsMenu () in Fragement to add an item to the Menu of the Activity.

5. dynamically set action bar
5.1. View displayed in the Custom action bar
You can add custom views, such as buttons or text, to the action bar.
You can use setCustomView of ActionView and setDisplayOptions (ActionBar. DISPLAY_SHOW_CUSTOM) to Enable custom View.
Example: first define a layout file containing EditText.

 
  
The following code adds the layout file to the action bar of an Activity.

package com.vogella.android.actionbar.customviews;import android.app.ActionBar;import android.app.Activity;import android.os.Bundle;import android.view.KeyEvent;import android.widget.EditText;import android.widget.TextView;import android.widget.TextView.OnEditorActionListener;import android.widget.Toast;public class MainActivity extends Activity {  @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    ActionBar actionBar = getActionBar();    // add the custom view to the action bar    actionBar.setCustomView(R.layout.actionbar_view);    EditText search = (EditText) actionBar.getCustomView().findViewById(R.id.searchfield);    search.setOnEditorActionListener(new OnEditorActionListener() {      @Override      public boolean onEditorAction(TextView v, int actionId,          KeyEvent event) {        Toast.makeText(MainActivity.this, "Search triggered",            Toast.LENGTH_LONG).show();        return false;      }    });    actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM        | ActionBar.DISPLAY_SHOW_HOME);  }} 
Complete source code download location: Custom Android Action Bar Layout

5.2. Action View
The Action View control can replace the Action icon of the Action bar. You can use this feature to replace an Action item with a ProgressBar. You can use android: actionLayout or android: actionViewClass to define a layout file or Widg as the Action view of the action.
Action View uses the following.




The first is two layout files. The first is used for action view.

 
  
The second is used for menu settings.

     
      
  
  
The Activity code is as follows:

package com.vogella.android.actionbar.progress;import android.app.ActionBar;import android.app.Activity;import android.os.AsyncTask;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;public class MainActivity extends Activity {  private MenuItem menuItem;  @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    ActionBar actionBar = getActionBar();    actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME        | ActionBar.DISPLAY_SHOW_TITLE | ActionBar.DISPLAY_SHOW_CUSTOM);  }  @Override  public boolean onCreateOptionsMenu(Menu menu) {    getMenuInflater().inflate(R.menu.main, menu);    return true;  }  @Override  public boolean onOptionsItemSelected(MenuItem item) {    switch (item.getItemId()) {    case R.id.menu_load:      menuItem = item;      menuItem.setActionView(R.layout.progressbar);      menuItem.expandActionView();      TestTask task = new TestTask();      task.execute("test");      break;    default:      break;    }    return true;  }  private class TestTask extends AsyncTask
 
   {    @Override    protected String doInBackground(String... params) {      // Simulate something long running      try {        Thread.sleep(2000);      } catch (InterruptedException e) {        e.printStackTrace();      }      return null;    }    @Override    protected void onPostExecute(String result) {      menuItem.collapseActionView();      menuItem.setActionView(null);    }  };} 
 
Complete source code: dynamically change the ActionBar icon
6. Action Provider
Action Provider provides multiple interaction methods in a single component. It can be used to create an action view, dynamically pop up a sub menu, and process action call events. The base class is ActionProvider.
Currently, the Android platform provides two types of action providers: MediaRouteActionProvider and ?actionprovider.
The following uses an example to calculate the usage of consumer actionprovider. Use this action provider to get the program from the Intent that has registered Intent. ACTION_SEND.
First, define the Menu XML file and set the android: actionProviderClass = "android. widget. Define actionprovider" of the Item"

 
    
      
      
  
  
Set an Intent that contains the data to be shared and send it.

@Override  public boolean onCreateOptionsMenu(Menu menu) {    getMenuInflater().inflate(R.menu.activity_main, menu);    // Get the ActionProvider for later usage    provider = (ShareActionProvider) menu.findItem(R.id.menu_share)        .getActionProvider();    return true;  }  @Override  public boolean onOptionsItemSelected(MenuItem item) {    switch (item.getItemId()) {    case R.id.menu_share:      doShare();      break;    default:      break;    }    return true;    }  public void doShare() {    // populate the share intent with data    Intent intent = new Intent(Intent.ACTION_SEND);    intent.setType("text/plain");    intent.putExtra(Intent.EXTRA_TEXT, "This is a message for you");    provider.setShareIntent(intent);  } 
7. Use the program icon to navigate
7.1. Use the program icon as the home icon
The icon on the left of the Action Bar is called the home icon. You can set an Action for this icon. We recommend that you press this icon and return it to the Home Activity.
The following code describes how to use home aciton in versions earlier than Android4.1. The key point is to use android. R. id. home in onOptionsMenuItemSelected () and enable HomeIcon of actionbar. SecondActivity uses MainActivity as HomeActivity.
Package com. vogella. android. actionbar. homebutton; import android. OS. bundle; import android. app. actionBar; import android. app. activity; import android. content. intent; import android. view. menu; import android. view. menuItem; public class SecondActivity extends Activity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // enable the home button ActionBar actionBar = getActionBar (); actionBar. setHomeButtonEnabled (true); // or use actionBar. setDisplayHomeAsUpEnabled (true) ;}@ Override public boolean onCreateOptionsMenu (Menu menu) {getMenuInflater (). inflate (R. menu. main, menu); return true ;}@ Override public boolean onOptionsItemSelected (MenuItem item) {switch (item. getItemId () {case android. r. id. home: Intent intent = new Intent (this, MainActivity. class); intent. setFlags (Intent. FLAG_ACTIVITY_CLEAR_TOP); startActivity (intent); break; // Something else case R. id. action_settings: intent = new Intent (this, ThirdActivity. class); startActivity (intent); default: break;} return super. onOptionsItemSelected (item );}}
In Android 4.1 or later versions, you can set the parentActivityName attribute in AndroidManifest. xml as follows.
Complete code: Use HomeIcon of ActionBar for navigation

The above are some basic operations on ActionBar. Because ActionBar is often used together with other controls such as Drawer and Tab, I will write an article to introduce how to combine ActionBar with other controls and provide the source code as a backup.

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.