Adding an Action Provider


Similar to an action view, an action provider replaces an action button with a customized layout. However, unlike an action view, an action provider takes control of all the action's behaviors and an action provider can display a submenu when pressed.

Figure 6. An action bar withShareActionProvider expanded to show share targets.

To declare an action provider, supply the actionViewClass attribute in the menu <item> tag with a fully-qualified class name for an ActionProvider.

You can build your own action provider by extending the ActionProvider class, but Android provides some pre-built action providers such as ShareActionProvider, which facilitates a "share" action by showing a list of possible apps for sharing directly in the action bar (as shown in figure 6).

Because each ActionProvider class defines its own action behaviors, you don't need to listen for the action in the onOptionsItemSelected() method. If necessary though, you can still listen for the click event in the onOptionsItemSelected() method in case you need to simultaneously perform another action. But be sure to return false so that the the action provider still receives the onPerformDefaultAction() callback to perform its intended action.

However, if the action provider provides a submenu of actions, then your activity does not receive a call to onOptionsItemSelected() when the user opens the list or selects one of the submenu items.

Using the ShareActionProvider

To add a "share" action with ShareActionProvider, define the actionProviderClass for an <item> tag with the ShareActionProvider class. For example:

 Use ShareActionProvider The first 1 Step , stay menu.xml A statement in item The property of is android:actionProviderClass="xxx.ShareActionProvider"
 <?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res-auto" >
<item android:id="@+id/action_share"
android:title="@string/share"
yourapp:showAsAction="ifRoom"
yourapp:actionProviderClass="android.support.v7.widget.ShareActionProvider"
/>
...
</menu>

Now the action provider takes control of the action item and handles both its appearance and behavior. But you must still provide a title for the item to be used when it appears in the action overflow.

The only thing left to do is define the Intent you want to use for sharing. To do so, edit your onCreateOptionsMenu() method to call MenuItemCompat.getActionProvider() and pass it the MenuItem holding the action provider. Then call setShareIntent() on the returned ShareActionProvider and pass it an ACTION_SEND intent with the appropriate content attached.

You should call setShareIntent() once during onCreateOptionsMenu() to initialize the share action, but because the user context might change, you must update the intent any time the shareable content changes by again calling setShareIntent().

 Use ShareActionProvider The first 2 Step , In the code find in menu In support of ActionPorivder Operation items for , Set the share type in the code .

For example:

 private ShareActionProvider mShareActionProvider;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_activity_actions, menu);
// Set up ShareActionProvider's default share intent
MenuItem shareItem = menu.findItem(R.id.action_share);
mShareActionProvider = (ShareActionProvider)
MenuItemCompat.getActionProvider(shareItem);
mShareActionProvider.setShareIntent(getDefaultIntent());
return super.onCreateOptionsMenu(menu);
}
/** Defines a default (dummy) share intent to initialize the action provider.
* However, as soon as the actual content to be used in the intent
* is known or changes, you must update the share intent by again calling
* mShareActionProvider.setShareIntent()
*/
private Intent getDefaultIntent() {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
return intent;
}

The ShareActionProvider now handles all user interaction with the item and you do not need to handle click events from the onOptionsItemSelected() callback method.

By default, the ShareActionProvider retains a ranking for each share target based on how often the user selects each one. The share targets used more frequently appear at the top of the drop-down list and the target used most often appears directly in the action bar as the default share target. By default, the ranking information is saved in a private file with a name specified by DEFAULT_SHARE_HISTORY_FILE_NAME. If you use the ShareActionProvider or an extension of it for only one type of action, then you should continue to use this default history file and there's nothing you need to do. However, if you use ShareActionProvider or an extension of it for multiple actions with semantically different meanings, then each ShareActionProvider should specify its own history file in order to maintain its own history. To specify a different history file for the ShareActionProvider, call setShareHistoryFileName() and provide an XML file name (for example,"custom_share_history.xml").

Note: Although the ShareActionProvider ranks share targets based on frequency of use, the behavior is extensible and extensions of ShareActionProvider can perform different behaviors and ranking based on the history file (if appropriate).

Creating a custom action provider

Creating your own action provider allows you to re-use and manage dynamic action item behaviors in a self-contained module, rather than handle action item transformations and behaviors in your fragment or activity code. As shown in the previous section, Android already provides an implementation of ActionProvider for share actions: the ShareActionProvider.

To create your own action provider for a different action, simply extend the ActionProvider class and implement its callback methods as appropriate. Most importantly, you should implement the following:

 Customize ActionProvider Inheritance ActionProvider class , The relevant interfaces are as follows , After defining an interface , And then as before in menu,xml Specify a item For this new definition of ActionProvider Subclass can be .
ActionProvider()
This constructor passes you the application  Context, which you should save in a member field to use in the other callback methods.
onCreateActionView(MenuItem)
This is where you define the action view for the item. Use the  Context acquired from the constructor to instantiate a  LayoutInflater and inflate your action view layout from an XML resource, then hook up event listeners. For example:
 public View onCreateActionView(MenuItem forItem) {
// Inflate the action view to be shown on the action bar.
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
View view = layoutInflater.inflate(R.layout.action_provider, null);
ImageButton button = (ImageButton) view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Do something...
}
});
return view;
}
onPerformDefaultAction()
The system calls this when the menu item is selected from the action overflow and the action provider should perform a default action for the menu item.
However, if your action provider provides a submenu, through the  onPrepareSubMenu() callback, then the submenu appears even when the action provider is placed in the action overflow. Thus, onPerformDefaultAction() is never called when there is a submenu.

Note: An activity or a fragment that implements onOptionsItemSelected() can override the action provider's default behavior (unless it uses a submenu) by handling the item-selected event (and returningtrue), in which case, the system does not call onPerformDefaultAction().

For an example extension of ActionProvider, see ActionBarSettingsActionProviderActivity.

ActionBar The official tutorial (8)ShareActionProvider More about custom action item providers

  1. ActionBar The official tutorial (7) Of custom action items view, How to get it and deal with its events

    Adding an Action View An action view is a widget that appears in the action bar as a substitute for ...

  2. ActionBar The official tutorial (11) Customize ActionBar The style of ( Contains important style property sheets and exercise examples )

    Styling the Action Bar If you want to implement a visual design that represents your app's brand, th ...

  3. ActionBar The official tutorial (4) to ActionBar Add action items and their event handling

    Adding Action Items The action bar provides users access to the most important action items relating ...

  4. ActionBar The official tutorial (10)ActionBar Drop down list mode of

    Adding Drop-down Navigation As another mode of navigation (or filtering) for your activity, the acti ...

  5. ActionBar The official tutorial (9)ActionBar At the top of the tab Pattern ( Be careful , It has been deprecated )

    This interface is deprecated.Action bar navigation modes are deprecated and not supported by inline ...

  6. ActionBar The official tutorial (6) Turn the icon into a button to return to the higher level , The same app between , Different app between , Different fragment between

    Navigating Up with the App Icon Enabling the app icon as an Up button allows the user to navigate yo ...

  7. ActionBar The official tutorial (5)ActionBar The split mode of ( Bottom tab style ), Hide the title , Hide icons

    Using split action bar Split action bar provides a separate bar at the bottom of the screen to displ ...

  8. ActionBar The official tutorial (3) Change the picture in the title

    Using a logo instead of an icon By default, the system uses your application icon in the action bar, ...

  9. ActionBar The official tutorial (2) Choose a topic to support or not support ActionBar And support ActionBar How to hide and show the application of

    Adding the Action Bar As mentioned above, this guide focuses on how to use the ActionBar APIs in the ...

Random recommendation

  1. svn update -r m path Restore the code to a version ( So before log The log is gone , It's empty log journal )

    [root@ok database ]# svn log resume ------------------------------------------------------------------------ r ...

  2. Ecplise + Xdebug After a lot of twists and turns, we can finally debug in one step

    http://my.oschina.net/012345678/blog/152889 Ecplise + Xdebug After a lot of twists and turns, we can finally debug in one step Published in 2 Years ago (2013-08-15 15:50)   ...

  3. 【 Problem solving report 】[ Dynamic programming ] CodingTrip - Ctrip Programming Contest ( The first game of the preliminaries )- Clever monkey

    The original title is : Clever monkey Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 32768/32768K (Java/Other) Problem D ...

  4. java.lang and java.lang.annotation To realize Annotation Class summary of

    Annotated , It's like some kind of marking , No addition , There is no mark , in the future , Other programs can use reflection to find out if there are any tags on your class , Look at your marks , Just do the right thing . Tags can be added to classes , Method , Field , On the bag , Method parameters . (1)  ...

  5. alloc、init You understand 50% Did you? ?

    Preface This is a record of me alloc.init Analytical thinking notes . If readers want to understand my second thought , You may need to at least understand the segmented paging management of memory , If you don't know anything about it , You can read this soft article first to have a simple understanding . Another important point is , ...

  6. vb.net Common functions

    Of course , All of these can be obtained from MSDN find out , But sometimes open to help the old slow , So let's put it here first , It's faster to look up a function or something . It's all from the Internet .Abs(number) Get the absolute value of the value . Asc(String) Get character ...

  7. Spring.NET Of IOC( Dependency injection )

    (1)  ioc, intend Inversion of control,( Inversion control ), Inversion of control , It means exchange of control . It's not generally used now , In general use dependency injection( Dependency injection ). rely on ...

  8. java NIO Detailed explanation

    http://zalezone.cn/2014/09/17/NIO%E7%B2%BE%E7%B2%B9/ 1. Preface We're writing java When it comes to programming , To optimize , Put all the energy into processing efficiency , But yes. IO ...

  9. bzoj4557【JLOI2016】 Detective guards

    This problem is not very simple for me , just so so . Update blog Tree form DP f[i][j] Express i In the subtree , Up to i Next j The minimum cost of layers . g[i][j] Express i All the subtrees are covered , It can also cover up j The minimum cost of layers . ...

  10. node Garbled when requesting to download interface

    Let's talk about the problem first A previous project , Simultaneous development of three terminals (PC.WEB.APP), Because of the architecture , Services are not open to the public , Naturally, the interface address will not be exposed , All requests go through node forward , This is the background .... The website has a scan ...