MasterofProject

UI Android twenty-fourth - Bar Action

Classification: Android finishing 62 people read Comment(0) Collection Report
The original text from Zhang Xingye blog:Http://prog3.com/sbdm/blog/xyz_lmn/article/details/8132420/
 Action BarIs a window function to identify the application and user location, and to provide users with the operation and navigation mode. In most of the cases, when you need to highlight the user behavior or the global navigation of the activity using bar action, becauseBar actionEnable the application to provide users with a consistent interface, and the system can be very good according to different screen configurations to adapt to the operation bar's appearance. You can useActionBarThe object of the API to control the behavior of the operation bar and visibility, these API are added in the Android3.0 (API Level 11).

      The main purpose of bar Action is:

1 provide a dedicated space for identifying the location of the application's mark and user.

The left of this space is the application of the icon or logo, as well as the title of the Activity. However, if you are a currently selected label that identifies the current View object's navigation tag, you can choose to remove the title of the Activity.

2 provide consistent navigation and visual experience in different applications.

Bar Action provides forFragmentBuilt in navigation tags. It also provides a drop down list of the current visual effects (such as a list of sorted by different conditions) for the replacement of a navigation mode or optimization.

3 key operations (such as "search", "create", "sharing", "Activity"), and provide users with quick access to the predictable method.

For key user operations, you can provide a quick access to the operating bar by using the options menu item as an action item. Operating the project also provides an operating window, which provides an embedded window member for a more direct action. The menu item in the overflow menu is not improved, the user can use the menu button on the device (the device has a button on the device), or the overflow menu button in the operation bar (when the device is not included in the menu button) to display the operation items.

       Summary of the above: bar Action is to replace the previous bar tittle and menu.

             

Figure 1 Gallery Honeycomb application, from the left, followed by the logo, Navigation Options tab, and operation item (a floating menu button inserted on the right).

Note:If Looking for information about the contextual action bar for displaying contextual action items you're, the seeMenuGuide.

Bar Design ActionDesign guidelines read, Android Design's ForBar ActionGuide.


Add Bar Action

From Android3.0 (API level 11), bar Action is included in all of the Activity (or sub classes of Activity) using the Theme.Hole theme, and when the targetSdkVersion or minSdkVersion property is set to "11" or more, this topic is the default theme. Such as:

  1. <Manifest...>  
  2.     <Uses-sdk Android:minSdkVersion="4"  
  3.               Android:targetSdkVersion="11" >  
  4. ...
  5. < /Manifest>  

In this example, the application requires that the minimum API version level is 4 (Android 1.6), but it also requires that the target API version level is 11 (Android 3). In this way, when the application runs on a Android3.0 or higher, the system will give each Activity applicationHolographic theme, so, each Activity will contain Action Bar.

If you want to useAPI ActionBarTo add a navigation mode and change the operation of the operation bar style, you should set the minSdkVersion property to "11" or greater value. There are a number of ways in which you can make your application support for older versions of API, while the Android level is 11 or more of the API class of machines that make your application support someAction BarAPI。为了保持后向兼容,请参考边框内的内容(边框内容如下)。

剩余向后兼容

如果你想在你的应用程序中提供一个操作栏,并与3岁以上的安卓版本保持兼容,你需要在活动的布局中创建动作栏(因为ActionBar等级 旧版本不可用。

为了帮助你,动作条兼容性示例应用程序提供了一个接口层和操作 酒吧布局,让您的应用程序使用一些ActionBarAPI 并且还支持旧版本的安卓通过替换传统的标题栏与自定义操作栏布局。

删除行动吧

如果你不想要作用条把活动,的主题设置为theme.holo.noactionbar就可以了,如:

  1. <活动 安卓:主题=“@安卓:风格/主题。noactionbar全息。”>  
         或者使用行动起来吧的hide()方法,如下:

  1. getactionbar() ActionBar ActionBar =;
  2. hide() ActionBar;

当行动吧隐藏时,系统会调整你的来填充当前有效的屏幕空间你能够使用show()方法来再次显示操作栏活动。

在隐藏和删除行动吧时,要当心为了适应被行动吧占用的空间而导致的活动的重新布局。如果你的活动有规律的隐藏和显示行动吧,你可能想要使用覆盖模式。覆盖模式在活动的顶部描画操作栏,而不是在它们所拥有的屏幕的区域。这样,在行动吧隐藏和重新显示时,你的布局保持不变。要使用覆盖模式,就要给活动创建一个主题,并且把安卓:windowactionbaroverlay属性设置为真实。

      提示:如果你有一个删除了行动吧的定制化的活动主题,它把Android:windowactionbar样式属性设置为假。但是,如果你使用了删除行动吧的一个主题,那么,创建窗口将不允许行动吧再显示,因此,你不能在以后给这个活动添加行动吧---因为getactionbar()方法将返回空。


添加操作项

有些时候,你可能想要让用户直接访问选项菜单中的一个项目,因此你要把应该在行动吧中显示的菜单项作为一个操作项来声明。操作项能够能够包含一个图标或文本标题。如果一个菜单项不作为一个操作项显示,那么系统就会把它放到悬浮菜单中。悬浮菜单既可以通过设备的菜单按钮来显示,也可以在行动吧中一个额外的按钮来显示。

当活动首次启动时,系统会调用onCreateOptionsMenu()方法给你的活动组装行动 酒吧和悬浮菜单。在这个回调方法中应该加载在XML文件中定义的菜单项资源,如:

  1. “重写”  
  2. 公共 布尔onCreateOptionsMenu(菜单){
  3. menuinflater气筒= getmenuinflater();
  4. 打气筒充气(r.menu.main_activity,菜单);
  5.     返回 真的
  6. }

             

图2。带有图标和文本标题的两个操作项,和悬浮菜单按钮。

在XML文件中,你能够通过给<item>元素声明Android:showasaction = ifRoom属性,请求把一个菜单项作为一个操作项来显示。用这种方式,只在有有效的空间时,菜单项才能显示在中如果没有足够的空间,这个菜单项会显示在悬浮菜单中动作条。

如果你的菜单项支持标题和图标---带有Android:标题和Android的图标属性---那么默认情况下,操作项仅显示图标。如果你要显示文本标题,就要给Android:showasaction属性添加文本设置,如:

  

  1. <?XML 版本=“1” 编码=“UTF-8”?>  
  2. <菜单 xmlns:Android=“http://schemas.android.com/apk/res/android”>  
  3.     <项目 安卓:身份证=“@ +身份证/ menu_save”  
  4.           安卓:图标=“@冲/ ic_menu_save”  
  5.           安卓:标题=“@字符串/ menu_save”  
  6.           安卓:showasaction=“ifroom |文本” / >  
  7. < /菜单>  

提示:WithText value bar Action to display text title. Bar Action will show the title as much as possible, but if the icon is valid and is limited by the bar Action space, the text title may not be displayed.

When a user selects an action item, the Activity receives aOnOptionsItemSelected ()The callback, the android:id attribute to support the ID passed to this method.

Defining the android:title attribute for each menu item is critical, even if you do not declare the operation item. The reasons are as follows:

1 if there is not enough space in the bar Action to display the operation items, the menu item will be displayed in the suspension menu, and only the title is displayed;

The 2 screen reader will read the menu item title for visually impaired users;

3 if you only use the icon to display the operation, then, the user can long press this project, with the title of the operation to display the message.

Be carefulIf you add the sourceFragmentObject menu item, then throughFragmentClassOnCreateOptionsMenu OnCreateOptionsMenuCallback method, when the user selects one of the Fragment menu item, the system will use thatFragmentObject correspondenceOnOptionsItemSelected() method. However, Activity has the opportunity to first deal with this event, because the system is called the correspondingFragmentObjectOnOptionsItemSelected() the same callback method that will be called before the Activity.

You can also declare a menu item, so that it will always be the operation item to display, but not in the suspended menu when the space is not enough. In most cases, you should not use the always attribute values to force a menu item always shown in the action bar, but when you provide an operating window that does not provide the default for the suspension menu, you need to always display a menu item. But to be alert, too many of the operating items will create a mess of UI, and will lead to the layout problem of a narrow screen device. The best way is to use the ifRoom property value, which allows the system to move the menu item to the suspended menu when the operation bar is insufficient.

Selection operation:

By evaluating some of the key features, you should carefully select the menu items in the options menu to display as an action item, usually, each operation should be at least one of the following characteristics:

1 often use: users more than seventy percent of the access to the use of the operation, or is to continue to use the operation of multiple times.

2 important: it is a user can easily find the operation, even if it is not a regular operation, but also need to be able to easily find it, and perform.

Such as, Wi-Fi settings in the network, etc..

3 typical: it is a typical operation provided by a number of similar applications, so the user is expected to be able to find it in the action bar.

For example, the "Refresh" operation in an email or social application.

If you want to adjust more than four menu items, then you should seriously consider their relative importance level, and try not to exceed four more than sets of operations (and also use the "ifRoom" attribute values, allowing the system to meet the relatively small space of the screen, can put on the suspension menu). Even in some widescreen equipment, ample space, you should not create a lot of operation, it will disrupt the UI layout and more like a desktop toolbar. Therefore, in order to hold a minimum number of operations.

In addition, the following actions should never be used as an action item to display: set, help, feedback, or similar operation. Always keep them in the suspension menu.

Be carefulNot all devices are provided to retrieve proprietary hardware buttons, so if it is an important feature in your application, it should always be displayed as an action item (and usually put in the first place, especially in the operating window).

Use separate operation

When your application is running on a Android4.0 (API level 14) or more, then there is an additional mode called the "separate operation bar" for bar action. When you enable separated operation mode bar, in the bottom of the screen will display a separate bar to show activity in the narrow screen devices, such as vertical screen mobile phone, running on the all operations.

Separate the bar action into separate operation items, and ensure that all operation items are displayed on a narrow screen device, while the navigation bar and the title element are left at the top.

To enable a separate column, you can simply add a splitActionBarWhenNarrow or uiOptions= element to the <application> or <activity> element.

Note that the Android will be based on the size of the current screen to adjust the appearance of the operation bar in various ways. Using a separate column is one of the options that you can enable to further optimize the user experience for a different screen size. You can also allow the operating bar to fold the Navigation Options tab to the main column. If you use the navigation option tab in the operating bar, once the operation is separated from a narrow screen device, the Navigation Options tab is likely to be filled to the main operating bar, and not to be separated from the stack up. Especially if you disable the icon and title of the action barSetDisplayShowHomeEnabled (false)AndSetDisplayShowTitleEnabled (false)Method), then the Navigation Options tab will be folded into the main operating bar, as shown in the second of the 3 devices in the following diagram:

                       

Figure 3 on the left is a separate operation bar with a navigation option tab, and the right side is a separate operation bar that is disabled by the application icon and title.

Be carefulAlthoughAndroid:uiOptionsAttributes are added to the Android4.0 (API level 14), but in order to maintain compatibility with the low version of minSdkVersion, even if your Android attribute values are less than 14, your application can also be safely contained android:uiOptions attributes. In the old version of the run, because the system can not understand the property, it is simply ignored the XML property. The only condition for this attribute in your manifest file is that you must compile your application on a platform that supports API level 14 or higher. To maintain compatibility, you can't use API, which is not supported by your application code, to be declared by the minSdkVersion property, and only the XML attribute can be ignored by the older version of the platform.

Navigation bar application icon

By default, the application icon is displayed on the left side of the action bar. You can use this icon as an action item. Application should respond to one of the following two operations on this icon:

1 return to the application's "master" Activity;

2 to the application of higher page navigation.

When the user touches the icon, the system calls Activity with ID android.R.id.homeOnOptionsItemSelected ()Method In this response, you can either start the master Activity, or you can return to the interface of a user in a structured hierarchy of your application.

If you want to return to the master Activity by applying the program icon, then you should include in the Itent objectFLAG_ACTIVITY_CLEAR_TOPIdentification With this tag, if you want to start the Activity already exists in the current task, then all of the Activity on the stack in this Activity has been destroyed, and the Activity display to the user. Add the logo is often important, because the main activity back quite a fallback action, and therefore should not generally create an instance of a new main activity, otherwise, may eventually in the current task produced a very long with a plurality of the main activity of the stack.

For example, in the case ofOnOptionsItemSelected() method to achieve the operation of the main Activity of the application:

  1. @Override  
  2. Public BooleanOnOptionsItemSelected (item MenuItem) {
  3.     Switch(item.getItemId ()) {
  4.         CaseAndroid.R.id.home:
  5.             App icon in action bar clicked / go home;  
  6. Intent Intent =NewIntent (This, HomeActivity.Class);
  7. Intent.addFlags (Intent.FLAG_ACTIVITY_CLEAR_TOP);
  8. StartActivity (intent);
  9.             Return True;
  10.         Default:
  11.             Return Super.onOptionsItemSelected (item);
  12. }
  13. }
You might want to add the user from another application to the current ActivityFLAG_ACTIVITY_NEW_TASKIdentification This logo ensures that the new Activity will not be added to the current task when the user returns to the home page or on the page, but in the task of your own application. For example, if the user starts a Activity in your application by using the Intent object that is called by another application, then select the action bar icon to return home page or page,FLAG_ACTIVITY_CLEAR_TOPThe logo starts the Activity (not the current task) in the task that belongs to your application. The system can use this new Activity to do root Activity to start a new task, you can also have this Activity instance of the existence of this Activity instance of a task to bring to the front, and the target will be acceptedOnNewIntent ()Callback. So if your Activity is to receive another application's Intent object, then it should be added to the Intent object.FLAG_ACTIVITY_NEW_TASKLogo, such as:
  1. Intent.addFlags (Intent.FLAG_ACTIVITY_CLEAR_TOP Intent.FLAG_ACTIVITY_NEW_TASK);

Be carefulIf you want to use the application icon to return home, pay attention to the beginning of the Android4.0 (API level 14), you must pass the callSetHomeButtonEnabled (true)Method to make sure that this icon can be used as an action item (in the previous version, by default, the icon can be used as an action item).

Navigation to Application Supervisor

As a traditional rollback navigation (the user back to historical task of a window) supplement, you can let the action bar icon provides to the parent page navigation function, it takes the user back to the parent page of your application. For example, when your application level is relatively deep in your application, you should return to the last page (the parent page of the current page).
          
        Figure 4 Email application of the standard icon (left) and the navigation icon (right). The system will automatically add up to the instructions.
For example, figure 5 shows the when the user from an application navigation to a belong to different applications of activity, "fallback" button of the behavior.

            

However, if you want to stay in the Email application after editing the message, then the navigation will allow you to navigate to the Email application to edit the page of the page, and not to return to the previous Activity. Figure 6 illustrates this scene, in the scene in the user enters into email applications, not by the backspace button, but according to the action bar icon to navigation.

       

Figure 6 behavior from the People application into the Email application, the navigation.

If the application icon is able to navigate, you want to call the SetDisplayHomeAsUpEnabledtrue (true) method in your ActionBar.

  1. Protected VoidOnCreate (savedInstanceState Bundle) {
  2.     Super.onCreate (savedInstanceState);
  3.   
  4. SetContentView (R.layout.main);
  5. ActionBar ActionBar = getActionBar ();
  6. ActionBar.setDisplayHomeAsUpEnabled (True);
  7. ...
  8. }

When the user touches the icon, the system calls the onOptionsItemSelected () method with ID android.R.id.home.

Remember to use the FLAG_ACTIVITY_CLEAR_TOP logo in the Intent object so you won't create a new instance when you don't have the parent Activity. For example, if you do not use the flag activity clear top identification, then backward navigation, then press the backspace button actually takes the user to the application of the lower page. This is very strange.

Be carefulIf there are a lot of users can get to the current Activity path in the application, then the icon should be gradually to the navigation of the current Activity.

Add operation window

The operating window is a visual member in the operation bar as an alternative to the operation project button. For example, if you have an optional menu item for the search, you can use the SearchView class to replace the search button on the operating bar, as shown in Figure 7:

             

Figure 7 (on), and expand the operation of the search window.

To declare an operating window, you can use the android:actionLayout attribute and the android:actionViewClass attribute to specify a layout resource or a visual component to be used. For example:

  1. <?XML Version="1" Encoding="Utf-8">?  
  2. <Menu Xmlns:android="Http://schemas.android.com/apk/res/android">  
  3.     <Item Android:id="@+id/menu_search"  
  4.           Android:title="@string/menu_search"  
  5.           Android:icon="@drawable/ic_menu_search"  
  6.           Android:showAsAction="IfRoom|collapseActionView"  
  7.           Android:actionViewClass="Android.widget.SearchView" >  
  8. < /Menu>  

The android:showAsAction attribute also contains the collapseActionView attribute values, which are optional, and declare that the operation window should be folded into a button, when the user selects the button, the operation window is started. Otherwise, this operation window is visible in the default, and it is also used to occupy the effective space of the operation bar even if the application is not suitable.

If you need to add a number of events to the operating window, you need to do this in the onCreateOptionsMenu () callback. You can get menu items by calling the findItem () method with the menu item getActionView, and then call the ID () element in the window. For example, use the following method to obtain the search window component in the above example.

  1. @Override  
  2. Public BooleanOnCreateOptionsMenu (menu Menu) {
  3. GetMenuInflater ().Inflate (R.menu.options, menu);
  4. SearchView SearchView = (SearchView) menu.findItem (R.id.menu_search).GetActionView ();
  5.     Configure the search info and add / any event listeners  
  6. ...
  7.     Return Super.onCreateOptionsMenu (menu);
  8. }

Handle the folding operation window

Operating windows allow you to provide users with fast access and rich operation without changing the Activity or Fragment. However, it is not appropriate to make the operation window visible by default. To ensure that the operating room (especially on the small screen device), you can put the operating window into an operating button. When the user selects the button, the operation window is displayed in the operation bar. If you define the ifRoom "android:showAsAction=" attribute, then the system may put the item in the overflow menu, but when the user has the option of this menu item, it will still be displayed in the operating bar. By adding the "collapseActionView" attribute to the android:showAsAction property, you can let the operating window be folded.

Because when the user selects the project, the system will start the operation window, so you don't need to respond to this menu item in the onOptionsItemSelected () callback method. When the user selects the menu item, the system will still call the onOptionsItemSelected () method, but the system will always start with the operating window unless you return the true (indicating that you have replaced the system to handle the event).

When the user selects the action bar "to" icon or press the backspace button, the system will fold the operating window.

If required, you can expand or collapse the operating window in code by using the expandActionView () and collapseActionView () method.

      Be carefulAlthough the operating window is optional, but, if it contains a SearchView object, we recommend that you always fold the window, and only when you need it, you can choose to start it. In the provision of a dedicated search button on the device should also be careful, if the user press the search button, then it should be to the search window to start, simply rewrite the onKeyUp Activity (KEYCODE_SEARCH) callback method, monitor the type of key events, and then call expandActionView () method, you can start the operation window.

If you need to update your Activity based on the visibility of the operating window, you can define a OnActionExpandListener event, and use the setOnActionExpandListener () method to register the event, and then accept the callback method as it is in the operating window:

  1. @Override  
  2. Public BooleanOnCreateOptionsMenu (menu Menu) {
  3. getmenuinflater()膨胀(r.menu.options,菜单);
  4. 菜单项的菜单项,菜单finditem(r.id.actionitem);
  5.   
  6. setonactionexpandlistener(菜单项。新的onactionexpandlistener() {
  7.         “重写”  
  8.         公共 布尔onmenuitemactioncollapse(菜单项){
  9.             崩溃时做某事  
  10.             返回 真的“返回”真实的“折叠行动”视图  
  11. }
  12.   
  13.         “重写”  
  14.         公共 布尔onmenuitemactionexpand(菜单项){
  15.             在扩展时做某事  
  16.             返回 真的扩大行动的观点  
  17. }
  18. });
  19. }

添加一个操作提供器

与操作视窗类似,操作提供器(由ActionProvider类定义的)用一个定制的布局代替一个操作项目,它还需要对所有这些项目行为的控制。当你在操作栏中给一个菜单项声明一个操作项目时,它不仅要一个定制的布局来控制这个菜单项的外观,而且当它在显示在溢出菜单中时,还要处理它的默认事件。无论是在操作栏中还是在溢出菜单中,它都能够提供一个子菜单。

例如,的扩展类ActionProvider ShareActionProvider,它通过在操作栏中显示一个有效的共享目标列表来方便共享操作。与使用传统的调用action_send类型意图对象的操作项不同,你能够声明一个ShareActionProvider对象来处理一个操作项。这种操作提供器会保留一个带有处理action_send类型意图对象的应用程序的下拉列表,即使这个菜单项显示在溢出菜单中。因此,当你使用像这样的操作提供器时,你不必处理有关这个菜单项的用户事件。

要给一个操作项声明一个操作提供器,就要在菜单资源中对应的<item>元素中定义Android:actionproviderclass属性,提供器要使用完整的类名例如:

  1. <?XML 版本=“1” 编码=“UTF-8”?>  
  2. <菜单 xmlns:Android=“http://schemas.android.com/apk/res/android”>  
  3.     <项目 安卓:身份证=“@ +身份证/ menu_share”  
  4.           安卓:标题=“@串/分享”  
  5.           安卓:showasaction=ifRoom  
  6.           安卓:actionproviderclass=“Android。Widget ShareActionProvider。” / >  
  7. < /菜单>  

在这个例子中,用ShareActionProvider类作为操作提供器,在这里,操作提供器需要菜单项的控制,并处理它们在操作栏中的外观和行为以及在溢出菜单中的行为你必须依然给这个菜单项提供一个用于溢出菜单的文本标题。

尽管操作提供器提供了它在溢出菜单中显示时所能执行的默认操作,但是活动(或片段)也能够通过处理来自onoptionsitemselected()回调方法的点击事件来重写这个默认操作。如果你不在这个回调方法中处理点击事件,那么操作提供器会接收onperformdefaultaction()回调来处理事件。但是,如果操作提供器提供了一个子菜单,那么活动将不会接收onoptionsitemselected()回调,因为子菜单的显示替代了选择时调用的默认菜单行为。

使用ShareActionProvider类

如果你想要在操作栏中提供一个”共享”操作,以充分利用安装在设备上的其他应用程序(如,把一张图片共享给消息或社交应用程序使用),那么使用ShareActionProvider类是一个有效的方法,而不是添加一个调用action_send类型意图对象的操作项。当你给一个操作项使用ShareActionProvider类时,它会呈现一个带有能够处理action_send类型意图对象的应用程序的下拉列表(如图8所示)。
                

图8。画廊应用截屏,用ShareActionProvider对象展开显示共享目标。

创建子菜单的所有逻辑,包括共享目标的封装、点击事件的处理(包在溢出菜单中的项目显示)等,都在ShareActionProvider类中实现了---你需要编写的唯一的代码是给对应的菜单项声明操作提供器,并指定共享的意图对象。

By default, the ShareActionProvider object is based on the user's usage frequency to retain the order of the shared object. The target application with a high frequency will be shown on the down list, and the most common target will be displayed directly on the operating bar as the default shared target. By default, the sort information is saved in a private file specified by the DEFAULT_SHARE_HISTORY_FILE_NAME. If you only use one type of ShareActionProvider class or its subclass, then you should continue to use this default history file, and don't need to do anything. However, if you use a ShareActionProvider class or a subclass of different types of multiple operations, then in order to maintain their own history, each ShareActionProvider class should specify their own historical documents. To specify a different history file for each ShareActionProvider class, call the setShareHistoryFileName () method, and provide a XML file name (e.g., custom_share_history.xml)

        Be carefulAlthough the ShareActionProvider class is based on the use of the frequency to align the shared goals, this behavior can be extended, and the ShareActionProvider class is able to perform different behavior and order based on historical documents.

To add a ShareActionProvider object, simply set the android.widget.ShareActionProvider property value for the android.actionProviderClass property. The only thing to do is to define the Intent object you want to share. You must call the getActionProvider () method to get the ShareActionProvider object that matches the menu item, and then call setShareIntent () method.

If you want to change the object to a variable that is selected from the Intent object's format, or other variables that are changed in the Activity lifetime, you should save the ShareActionProvider object in a member property, and call the setShareIntent () method to update it when needed. Such as:

  1. PrivateMShareActionProvider ShareActionProvider;
  2. ...
  3.   
  4. @Override  
  5. Public BooleanOnCreateOptionsMenu (menu Menu) {
  6. MShareActionProvider = (ShareActionProvider) menu.findItem (R.id.menu_share).GetActionProvider ();
  7.   
  8.     You use more than one / If ShareActionProvider, each for a different action,  
  9.     Use the following line to specify / a unique history file for each one.  
  10.     / / mShareActionProvider.setShareHistoryFileName ("custom_share_history.xml");  
  11.   
  12.     The default share intent / / Set  
  13. MShareActionProvider.setShareIntent (getDefaultShareIntent ());
  14.   
  15.     Return True;
  16. }
  17. When you need to update the / share intent somewhere else in the app, call  
  18. (/ / mShareActionProvider.setShareIntent)  
In the preceding example shareactionprovider object processing all with this menu item user interaction and does not require treatment from the click event onoptionsitemselected) (callback method.

Create a custom operation provider

When you want to create a dynamic behavior and have a default icon in the suspended menu, the ActionProvider class is a better solution to define these behaviors. To create your own operating provider, to provide an organization of reusable components, rather than in the Fragment or Activity code to deal with the transformation and behavior of various operations.

To create your own operation provider, simply inherit the ActionProvider class, and implement the appropriate callback method. You should implement the following important callback methods:

ActionProvider ()

  The constructor of the application context object transfer operation provider, you should save it in a member variable to other callback method.

OnCreateActionView ()

 This is where you define the operating window for the menu item. Use received from a constructor context object, obtain a layoutinflater object instance, and XML resources to fill the operating window and register event listeners. Such as:

  1. PublicOnCreateActionView View () {
  2.     Inflate the action view to be / shown on the action bar.  
  3. LayoutInflater LayoutInflater = LayoutInflater.from (mContext);
  4. View View = layoutInflater.inflate (R.layout.action_provider,Null);
  5. Button ImageButton = (ImageButton) view.findViewById (R.id.button);
  6. Button.setOnClickListener (NewView.OnClickListener () {
  7.         @Override  
  8.         Public VoidOnClick (V View) {
  9.             Do / / something...  
  10. }
  11. });
  12.     ReturnView;
  13. }

OnPerformDefaultAction ()
         
When the menu is selected, the system will call this method, and the operator should perform the default action for the selected menu item.

However, if your operation provides a sub menu, even if it is a menu item in the menu item, you can display a sub menu with the onPrepareSubMenu () callback method. Such onPerformDefaultAction () is not called when the child menu is displayed.

       Be carefulThe Activity or Frament object that implements the onOptionsItemSelected callback method is able to override the default behavior of the operator by handling the item-selected event (and returns true). The system does not call the onPerformDefaultAction () callback method.

Add Navigation Options tab

       When you want in an activity to provide navigation tags, the use of the action bar tab is a very good choice, rather than using the tabwidget, because the system will adjust the action bar tab to adapt to the needs of different size screen --- when the screen wide enough, the navigation tab will is put into the main action bar; when the screen is too narrow, the tab will was placed in a separate bar, as shown in Figure 9 and figure 10.
      
          Figure 9Honeycomb GalleryThe application of the action bar option tab in the screenshot
      
Figure 10 in narrow screen devices are stacked in the action bar tab screenshot

To switch between Fragmengt, you must perform a Fragment transaction each time you select an option tab. If you are not familiar with how to use the FragmentTransaction object to change the Fragment, please readFragmentDevelopment guide.

First, your layout must contain a ViewGroup object that is used to place the tag associated with each Fragment object. And make sure that the ViewGroup object has a resource ID, so you can refer to it in the option label switching code. In addition, if the content of the Options tab is filled in the layout of the Activity (not including the operation bar), then the Activity does not need any layout (you don't even need to call the setContentView () method). Instead, you can put each Fragment object into the default root ViewGroup object, you can use ID android.R.id.content to refer to the ViewGroup object (in the Fragment execution of the transaction, you can see how to use this ID in the following sample code.

Determines the display position of the Fragment object in the layout, and the basic process of adding an option tag is as follows:

1 ActionBar.TabListener interface. The callback method in this interface will respond to user events on the tab, so you can switch to the Fragment object;

2. For each to add the Options tab, to instantiate a actionbar. Tab object and call setTabListener () method to set the actionbar. Tab object event listeners. You can also use the setText () or setIcon () method to set the title or icon for an option label.

3 by calling the addTab () method, add each tab to the action bar.

In viewActionBar.TabListenerInterface, note that the callback method provides only the selected ActionBar.Tab object and the Fragment object transactionFragmentTransactionObject - no description of any of the Fragment switches. So. You have to define your own.ActionBar.TabThe association between, andActionBar.TabRepresents the fit of the Fragment object (in order to execute the appropriate Fragment transaction). Depending on your design, there are several different ways to define the association. In the following example,ActionBar.TabListenerProvide a constructor interface, so that each new tab will use its own instance of the listener. Each instance of the listener defines several transactions in the corresponding Fragment object must be the member variables.

For example, the following example isActionBar.TabListenerAn implementation of the interface, in this implementation, each tab uses its own instance of the listener:

  1. Public Static ClassTabListener<TExtendsFragment>ImplementsActionBar.TabListener {
  2.     PrivateMFragment Fragment;
  3.     私人 最后活动mactivity;
  4.     私人 最后字符串MTAG;
  5.     私人 最后类mclass <T>;
  6.   
  7.     每次一个新的标签被创建时,每个构造函数使用。 
  8. * @param活动主办的活动,用来实例化的片段 
  9. * @param标记标识符标记片段 
  10. * @param该片段的类,用来实例化的片段 
  11. *  
  12.     公共tablistener(活动,字符串标签,类<T> CLZ){
  13. mactivity =活动;
  14. mTag =标签;
  15. mclass = CLZ;
  16. }
  17.   
  18.     /*以下各的actionbar.tablistener回调* /  
  19.   
  20.     公共 无效ontabselected(TAB选项卡,fragmenttransaction英尺){
  21.         检查碎片是否已初始化  
  22.         如果(mfragment = =){
  23.             /如果不是,实例化并将其添加到活动  
  24. mfragment =片段。实例化(mactivity mclass,getname()。);
  25. ft.add(android.r.id.content,mfragment,mTag);
  26. }其他的{
  27.             如果它存在,简单地附加它,以显示它  
  28. ft.attach(mfragment);
  29. }
  30. }
  31.   
  32.     公共 无效ontabunselected(TAB选项卡,fragmenttransaction英尺){
  33.         如果(mfragment!=){
  34.             分离的片段,因为另一个被连接  
  35. ft.detach(mfragment);
  36. }
  37. }
  38.   
  39.     公共 无效ontabreselected(TAB选项卡,fragmenttransaction英尺){
  40.         / /用户选择已选定的标签。通常不做任何事。  
  41. }
  42. }

警告:针对每个回调中的片段事务,你都不必调用commit()方法---系统会调用这个方法,并且如果你自己调用了这个方法,有可能会抛出一个异常事务添加到回退堆栈中你也不能把这些片段。

在这个例子中,当对应的选项标签被选择时,监听器只是简单的把一个片段对象附加(attach()方法)到活动布局上---或者,如果没有实例化,就会创建这个片段对象,并且把它添加(()方法)到布局中(android.r.id.content ViewGroup的一个子类),当这个选项标签解除选择时,对应的片段对象也会被解除与布局的依附关系。

tablistener ActionBar。的实现做了大量的工作,剩下的事情就是创建每个ActionBar。标签对象并把它添加到ActionBar对象中,另外,你必须调用setnavigationmode(navigation_mode_tabs)方法来让选项标签可见。如果选项标签的标题实际指示了当前的观对象,你也可以通过调用setdisplayshowtitleenabled(假)方法来禁用活动的标题。

例如,下面的代码使用上面定义的监听器在操作栏中添加了两个选项标签。

  1. “重写”  
  2. 受保护的 无效onCreate(Bundle savedinstancestate){
  3.     好极了onCreate(savedinstancestate);
  4.     //注意setcontentview()是没有用的,因为我们使用的根  
  5.     / / android.r.id.content作为每个片段的容器  
  6.   
  7.     为制表符设置动作栏  
  8. getactionbar() ActionBar ActionBar =;
  9. setnavigationmode ActionBar。(ActionBar。navigation_mode_tabs);
  10. setdisplayshowtitleenabled(ActionBar。);
  11.   
  12. 制表= ActionBar。newtab()
  13. 。setText(R.string。艺术家)
  14. settablistener(。新的tablistener artistfragment >(<
  15.                     “艺术家”,artistfragment。等级);
  16. addtab ActionBar(标签);
  17.   
  18. 标签= newtab() ActionBar。
  19. 。setText(R.string。专辑)
  20. settablistener(。新的tablistener albumfragment >(<
  21.                 “专辑”,albumfragment。等级);
  22. addtab ActionBar(标签);
  23. }

注意:以上有关ActionBar。tablistener的实现,只是几种可能的技术之一在。应用程序编程接口(Application Programming Interface) 演示应用中你能够看到更多的这种样式。

如果活动终止了,那么你应该保存当前选择的选项标签的状态,以便当用户再次返回时,你能够打开合适的选项标签。在保存状态的时刻,你能够用getselectednavigationindex()方法查询当前的被选择的选项标签这个方法返回被选择的选项标签的索引位置。

Warning: to save the necessary state of each Fragment is critical, because when the user uses the option to switch between the Fragment object, it will look at the Fragment when it is left.

Note: in some cases, the Android system will display the operating bar option label as a drop down list to ensure that the operating bar is optimized for display.

Add drop navigation

As a navigation (or filtering) mode inside the Activity, the operation bar provides a built-in drop-down list. The drop-down list is able to provide a different sort of Activity content.

The basic process of enabling drop - down navigation is as follows:

1 create a drop-down list to provide optional items, use and list of project layout drawing;

2 to implement the ActionBar.OnNavigationListener callback, defining the behavior that occurs when a user selects a item in a list of items in this callback;

3 use setNavigationMode () method to enable navigation mode, such as:

  1. ActionBar ActionBar = getActionBar ();
  2. ActionBar.setNavigationMode (ActionBar.NAVIGATION_MODE_LIST);

4 use setListNavigationCallbacks () method to set up a callback method, such as:

  1. ActionBar.setListNavigationCallbacks (mSpinnerAdapter, mNavigationCallback);

This method requires SpinnerAdapter andActionBar.OnNavigationListenerObject. Here is SpinnerAdapterAndActionBar.OnNavigationListenerExamples.

SpinnerAdapter and OnNavigationListener Example

Set the style of the operation bar

If you have a custom design for visual components in your application, you may also have to do some redesign of the operating bar to match the application's design. To do so, you need to use the Android style and some special style properties in the theme framework to re set the style of the operation bar.

Note: changes the appearance of background picture dependent and the button state (selection, press, deselect), so you use can be painted resources must be a painted state list.

Warning: for you all can describe the background to ensure the use of ninepatch type resource can be painted, so as to allow the picture of stretch. NinePatch type of picture should be 40 pixels higher than 30 pixels wide picture to be small.


Common appearance

Android:windowActionBarOverlay

This property declares whether the operation should cover the Activity layout, and not the offset of the relative Activity layout. The default value for this property is false.

Often, on the screen, the operation bar needs its own space, and the rest of the space is used to fill the layout of the Activity. When the action bar four coverage model, the activity will use all available space, the system will be in activity above the painted the action bar. If you want to hide and display in the action bar, the layout of the content to maintain a fixed position, then this cover mode is useful. You may only use it in order to display the effect, because you can set up a semi transparent background, so that users can still see the Activity layout behind the operation bar.

Note: by default, Holo theme to depict the action bar with translucent background. However, you can use your own style to modify it, and by default, the DeviceDefault theme may use an opaque background on different devices.

When the overlay mode is enabled, the Activity layout is not aware of the operation bar to cover it up, and therefore, in the area covered by the operating bar, it is best not to place some important information or UI components. If it is appropriate, you can refer to the actionBarSize value of the platform to determine the height of the operating bar, for example, reference the value in the XML layout file.

  1. <SomeView  
  2. ...
  3.     Android:layout_marginTop="Android:attr/actionBarSize?" >  

You can also use the getHeight () method to get the height of the operating bar at run time. If this method is called early in the Activity life cycle, the height of the operating column that is reflected by the call is not included in the operating column that was stacked (because the navigation option tag). To see how to determine the total height of the operating column at run time (including the operation of the stack), please seeHoneycomb GallerySample applicationTitlesFragmentClass.

Operating element

Android:actionButtonStyle
Defining the style resource for the operating items.
Android:actionBarItemBackground
Can draw resources to the background definition of each operation item (to be added in API level 14).
Android:itemBackground
Can be painted background resources to define each suspended menu item.
Android:actionBarDivider
The dividing line between the operation to define traceableness resources (to be added in API level 14)
Android:actionMenuTextColor
To display the text definition color in an operation item.
Android:actionMenuTextAppearance
To display text definition style resources in an action item.
Android:actionBarWidgetTheme
Define the theme resource for the visual component in the operating column as an operating window (which is added to the API level 14).Navigation Options tab

Android:actionBarTabStyle
Define style resources for option tags in the action bar.
Android:actionBarTabBarStyle
To display in the thin style under resources navigation options tab.
Android:actionBarTabTextStyle
Defining style resources for text in the navigation options tab.Drop down list

Android:actionDropDownStyle
Define style (e.g. background and text style) for the drop-down navigation list.For example, the next example XML file to define a number of custom style:

  1. <?XML Version="1" Encoding="Utf-8">?  
  2. <Resources>  
  3.     <! -- the theme applied to the application or activity -- >  
  4.     <Style Name="CustomActivityTheme" Parent="@android:style/Theme.Holo">  
  5.         <Item Name="Android:actionBarTabTextStyle">@style/CustomTabTextStyle< /Item>  
  6.         <Item Name="Android:actionBarDivider">@drawable/ab_divider< /Item>  
  7.         <Item Name="Android:actionBarItemBackground">@drawable/ab_item_background< /Item>  
  8.     < /Style>  
  9.   
  10.     <! -- style for the action bar tab text -- >  
  11.     <Style Name="CustomTabTextStyle" Parent="@android:style/TextAppearance.Holo">  
  12.         <Item Name="Android:textColor">#2456c2< /Item>  
  13.     < /Style>  
  14. < /Resources>  

Note: be sure to declare a parent theme in the <style> tag, so that the custom theme can inherit all the styles that are not explicitly declared. Using the parent theme is essential when you modify the operating bar style, which allows you to override the action bar style you want to change, and not affect the style you want to change (such as the appearance of a text or the edge of an operating term).

You can apply the custom theme to the entire application or a separate Activity object in the manifest file:

  1. <Application Android:theme="@style/CustomActivityTheme"...>  

Advanced style

If you need to be more advanced than the above, you can include in the theme of the ActivityAndroid:actionBarStyleAnd android:actionBarSplitStyle properties. Each of these two attributes specifies an alternative that is capable of defining a variety of properties for an operating column, including a different background with android:backgroundSplit, android:backgroundStacked, and android:background properties. If you want to cover the action bar style, make sure you define an image.Widget.Holo.ActionBarSuch a parent action bar style.

For example, if you want to change the operating bar background, you can use the following styles:

  1. <?XML Version="1" Encoding="Utf-8">?  
  2. <Resources>  
  3.     <! -- the theme applied to the application or activity -- >  
  4.     <Style Name="CustomActivityTheme" Parent="@android:style/Theme.Holo">  
  5.         <Item Name="Android:actionBarStyle">@style/MyActionBar< /Item>  
  6.         <! -- other activity and action bar styles here -- >  
  7.     < /Style>  
  8.   
  9.     <! -- style for the action bar backgrounds -- >  
  10.     <Style Name="MyActionBar" Parent="@android:style/Widget.Holo.ActionBar">  
  11.         <Item Name="Android:background">@drawable/ab_background< /Item>  
  12.         <Item Name="Android:backgroundStacked">@drawable/ab_background< /Item>  
  13.         <Item Name="Android:backgroundSplit">@drawable/ab_split_background< /Item>  
  14.     < /Style>  
  15. < /Resources>  


Original address:Http://developer.android.com/guide/topics/ui/actionbar.html#ActionView

Top
0
Step
0
Guess what you're looking for.
View comments
* above the user's comments only represent their personal views, do not represent the views or position of the CSDN website
    Personal data
    • Visit36085 times
    • Integral:1740
    • Grade
    • Rank:13010th
    • Original144
    • Reprint:36
    • Translation:1
    • Comment:9
    Latest comments