Reprint Please specify source: http://blog.csdn.net/guolin_blog/article/details/25466665
The main content of this article comes from Android Doc, I have done some processing after translation, English good friends can also directly read the original text.
Http://developer.android.com/guide/topics/ui/actionbar.html
Confined to the reason of space, in the previous article we only learned Actionbar basic part of the knowledge, then this article we will continue to study the contents of the previous chapter, explore Actionbar more advanced knowledge. If you have not read the previous article, it is recommended to first read the Android actionbar full parsing, using the official recommended best navigation bar (above).
Add Action Provider
A bit like action view, action provider can also replace an action button with a custom layout. But the difference is that action provider can completely control all the behavior of the event, and can also display submenus when clicked.
To add an action Provider, we need to specify a Actionviewclass attribute in the <item> tag that fills in the full class name of the action Provider. We can create our own action Provider by inheriting the Actionprovider class, and Android also provides several built-in action Provider, such as Shareactionprovider.
Since each action provider is free to control the event response, they do not need to listen for the Click event in the Onoptionsitemselected () method, but should be in the onperformdefaultaction () method to execute the corresponding logic.
So let's take a look at the simple usage of shareactionprovider, edit the menu resource file, add the Shareactionprovider declaration, as follows:
<menu xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http://schemas.android.com /tools " tools:context=" com.example.actionbartest.MainActivity "> <item android:id=" @+id/ Action_share " android:actionproviderclass=" Android.widget.ShareActionProvider " android:showasaction=" Ifroom " android:title=" @string/action_share "/> ......</menu>
Note that Shareactionprovider will handle its display and events on its own, but we still have to remember to add a title to it to prevent it from appearing in the overflow.
Then the rest is to define what you want to share by intent, and we just need to call MenuItem's Getactionprovider () in Oncreateoptionsmenu (). method to get the Shareactionprovider object, and then through the Setshareintent () method to choose what kind of a intent to build it. The code looks like this:
@Overridepublic boolean Oncreateoptionsmenu (Menu menu) {menuinflater inflater = Getmenuinflater (); Inflater.inflate ( R.menu.main, menu); MenuItem Shareitem = Menu.finditem (R.id.action_share); Shareactionprovider Provider = (Shareactionprovider) shareitem.getactionprovider ();p rovider.setshareintent ( Getdefaultintent ());...... return super.oncreateoptionsmenu (menu);} Private Intent getdefaultintent () { Intent Intent = new Intent (intent.action_send); Intent.settype ("image/*"); return intent;}
As you can see, here we have built a intent with the Getdefaultintent () method, which represents the extent to which all the images can be shared are listed. Run the program again, as shown in the results:
Careful you must observe, this shareactionprovider can be expanded after the click, a bit similar to the overflow effect, this is the Action Provider submenu. In addition to using Shareactionprovider, we can also customize an action Provider, for example, if you want to create an action Provider with two submenus, you can write:
public class Myactionprovider extends Actionprovider {public Myactionprovider (context context) {super (context);} @Overridepublic View Oncreateactionview () {return null;} @Overridepublic void Onpreparesubmenu (submenu submenu) {submenu.clear (); Submenu.add ("Sub item 1"). SetIcon ( R.drawable.ic_launcher). Setonmenuitemclicklistener (New Onmenuitemclicklistener () {@Overridepublic Boolean Onmenuitemclick (MenuItem Item) {return true;}}); Submenu.add ("Sub Item 2"). SetIcon (R.drawable.ic_launcher). Setonmenuitemclicklistener (New Onmenuitemclicklistener ( {@Overridepublic Boolean Onmenuitemclick (MenuItem item) {return false;}});} @Overridepublic Boolean Hassubmenu () {return true;}}
Here we create a new myactionprovider inherited from Actionprovider, in order to indicate that the action provider has a submenu, you need to override the Hassubmenu () method and return True, The submenu is then added in Onpreparesubmenu by calling the Add () Method of submenu.
Then modify the menu resource to add the Myactionprovider declaration:
<menu xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http://schemas.android.com /tools " tools:context=" com.example.actionbartest.MainActivity "> <item android:id=" @+id/ Action_share " android:actionproviderclass=" Com.example.actionbartest.MyActionProvider " android:icon=" @ Drawable/ic_launcher " android:showasaction=" ifroom " android:title=" @string/action_share "/> ......</menu>
Now rerun the code and the result:
Add Navigation tabs
Tabs's application can be quite extensive, which makes it very easy for users to switch between different views in your application. And Android is more recommended to use the tabs features provided in Actionbar, because it is more intelligent, can automatically adapt to the size of various screens. For example, there is plenty of room on the tablet screen, and the tabs will be displayed on the same line as the action button, as shown in:
If the screen space is not large enough on the phone, the tabs and action buttons are displayed in two lines, as shown in:
Let's take a look at how to use the TAB function provided by Actionbar, which can be broadly divided into the following steps:
1. Implement the Actionbar.tablistener interface, which provides various callbacks for the tab event, such as when the user clicks on a tab, you can switch tab operation.
2. Create an instance of Actionbar.tab for each tab you want to add, and call the Settablistener () method to set the Actionbar.tablistener. In addition, you need to call the SetText () method to set the caption for the current tab.
3. Finally call Actionbar's AddTab () method to add the Created tab to the Actionbar.
It doesn't look complicated, it's only three steps in total, so let's try it now. The first step is to create a class that implements the Actionbar.tablistener interface, as shown in the following code:
public class Tablistener<t extends fragment> implements Actionbar.tablistener {private Fragment mfragment; Private final Activity mactivity; Private final String Mtag; Private final class<t> MClass; Public Tablistener (activity activity, String tag, class<t> clz) {mactivity = activity; Mtag = tag; MClass = CLZ; } public void ontabselected (Tab tab, fragmenttransaction ft) {if (mfragment = = null) {mfragment = F Ragment.instantiate (Mactivity, Mclass.getname ()); Ft.add (Android. R.id.content, Mfragment, Mtag); } else {Ft.attach (mfragment); }} public void ontabunselected (Tab tab, fragmenttransaction ft) {if (mfragment! = null) {Ft.det Ach (mfragment); }} public void ontabreselected (Tab tab, fragmenttransaction ft) {}}
This code is not long, let's analyze it briefly. The ontabselected () method is called when the tab is selected, where we first determine if the mfragment is empty, if it is empty, create an instance of fragment and call the Add () method of Fragmenttransaction. Call Fragmenttransaction's Attach () method if it is not empty.
When the tab is not selected, the Fragmenttransaction detach () method is called and the UI resource is freed.
The ontabreselected () method is called when tab is re-selected, and is usually not required if there is no special requirement.
The next step is to create an instance of Actionbar.tab for each tab, before you have to prepare the corresponding fragment for each tab page. For example, here we want to create two tab pages, artist and album, so we need to prepare the corresponding fragment for the two tab pages. First create a new artistfragment, as shown in the code below:
public class Artistfragment extends Fragment {@Overridepublic View oncreateview (layoutinflater inflater, ViewGroup Container,bundle savedinstancestate) {TextView TextView = new TextView (getactivity ()); Textview.settext ("Artist Fragment "); textview.setgravity (gravity.center_horizontal); LinearLayout layout = new LinearLayout (getactivity ()); Layoutparams params = new Layoutparams (layoutparams.match_parent, layoutparams.wrap_content); Layout.addview ( TextView, params); return layout;}}
There is no real code, just a string that shows the artist fragment in TextView.
Then follow the example and create a new albumfragment with the following code:
public class Albumfragment extends Fragment {@Overridepublic View oncreateview (layoutinflater inflater, ViewGroup Container,bundle savedinstancestate) {TextView TextView = new TextView (getactivity ()); Textview.settext ("Album Fragment "); textview.setgravity (gravity.center_horizontal); LinearLayout layout = new LinearLayout (getactivity ()); Layoutparams params = new Layoutparams (layoutparams.match_parent, layoutparams.wrap_content); Layout.addview ( TextView, params); return layout;}}
After the fragment is ready, the next step is to create the tab instance, and then call the AddTab () method to add to the Actionbar, which is usually done in the activity's OnCreate () method, as follows:
@Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Settitle ("Weather"); ActionBar ActionBar = Getactionbar (); actionbar.setdisplayhomeasupenabled (true); Setoverflowshowingalways (); Actionbar.setnavigationmode (Actionbar.navigation_mode_tabs); tab tab = Actionbar.newtab (). SetText (R.string.artist). Settablistener (New tablistener<artistfragment> (This, " Artist ", Artistfragment.class)); Actionbar.addtab (tab); tab = Actionbar.newtab (). SetText (R.string.album). Settablistener (New tablistener<albumfragment> (This, "album", Albumfragment.class)); Actionbar.addtab (tab);}
As you can see, this is the use of concatenating to create tab. First Call Actionbar's Newtab () method to create a tab instance, then call the SetText () method to set the caption, and then call the Settablistener () method to set the event listener, and then call Actionbar's AddTab () method to add the tab to the Actionbar.
OK, so the code is written, rerun the program, the effect is as shown:
Custom Actionbar Styles
Although Actionbar provides users with a holistic and unified interface style and operation, this does not mean that all applications must be actionbar in exactly the same way. If you need to modify the Actionbar style to better fit your app, you can do it very simply with Android styles and themes.
In fact, several of the activity topics built into Android already contain actionbar styles such as "dark" or "light", and you can also inherit these themes and make further customizations.
1. Use the theme Android has two most basic activity themes can be used to specify the color of the Actionbar, respectively:
- Theme.holo, this is the theme of a dark system.
- Theme.Holo.Light, this is the theme of a light-coloured system.
The effect of the dark theme style is as follows:
The effect of the light-colored theme style is as follows:
You can apply these themes to your entire application or only to an activity. You can do this by assigning the Android:theme attribute to the <application> or <activity> tag in the Androidmanifest.xml file. Like what:
<application android:theme= "@android: Style/theme.holo.light" .../>
If you just want Actionbar to use a dark-colored theme, and the content part of the activity still uses a light-colored theme, you can do so by declaring the Theme.Holo.Light.DarkActionBar theme, which looks like this:
2. Customizing the background If you want to modify the background of the Actionbar, we can do so by creating a custom theme and overriding the Actionbarstyle property. This property can point to a different style, and then we can override the background property in this style to specify a drawable resource or color to implement the function of customizing the background. Edit the Styles.xml file and add a custom theme to it, as follows:
<resources> <style name= "Customactionbartheme" parent= "@android: Style/theme.holo.light" > <item name= "Android:actionbarstyle" > @style/myactionbar</item> </style> <style name= "Myactionbar" parent= "@android: Style/widget.holo.light.actionbar" > <item name= "Android:background" > #f4842d </item> </style></resources>
As you can see, here we define a customactionbartheme theme and let it inherit from Theme.Holo.Light. It then overrides the Actionbarstyle property in its interior, and then points this property to the Myactionbar style, where we override the Background property and assign it a background color. Now run the program again, as shown in the results:
This allows us to successfully modify the background color of the actionbar. But now looks a bit strange, because just actionbar background color changes, tabs background color is the original appearance, so it feels not very coordinated. So here we go. To modify the background color of tabs, edit the Styles.xml file as follows:
<resources> <style name= "Customactionbartheme" parent= "@android: Style/theme.holo.light" > <item name= "Android:actionbarstyle" > @style/myactionbar</item> </style> <style name= "Myactionbar" parent= "@android: Style/widget.holo.light.actionbar" > <item name= "Android:background" > #f4842d </item> <item name= "android:backgroundstacked" > #d27026 </item> </style> </resources>
As you can see, this again overrides the Backgroundstacked property, which is used to specify the tabs background color. Then rerun the program again, as shown in the effect:
3. Custom text color Now the whole actionbar color belongs to the dark system, and actionbar the color of the text is black, so it does not look comfortable, then we will learn if the custom text color, the text color to white. Modify the Styles.xml file as follows:
<resources> ... <style name= "Myactionbar" parent= "@android: Style/widget.holo.light.actionbar" > ... <item name= "Android:titletextstyle" > @style/myactionbartitletext</item> </style> < Style name= "Myactionbartitletext" parent= "@android: Style/textappearance.holo.widget.actionbar.title" > <item name= "Android:textcolor" > #fff </item> </style></resources>
As you can see, this overrides the TitleTextStyle property in the Myactionbar style and points it to another custom style myactionbartitletext, and then we specify in this style that the textcolor color is #fff, That's white. Now rerun the program and the results are as follows:
Ok,actionbar title text color has been successfully changed to white, the tab title of the text and how to modify it? Continue editing the Styles.xml file as follows:
<resources> <style name= "Customactionbartheme" parent= "@android: Style/theme.holo.light" > <item name= "Android:actionbarstyle" > @style/myactionbar</item> <item name= "Android: Actionbartabtextstyle "> @style/myactionbartabtext</item> </style> <style name=" Myactionbartabtext " parent=" @android: Style/widget.holo.actionbar.tabtext "> <item name=" Android: TextColor "> #fff </item> </style></resources>
Here we override the Actionbartabtextstyle property in the Customactionbartheme theme and point it to a new myactionbartabtext style, and then override the TextColor property in this style. Specify the color as white. Rerun the program and the results are as follows:
4. Custom tab Indicator in order to be able to clearly distinguish which tab item we are currently selecting, we usually add a horizontal line underneath the tab to mark it, which is called Tab Indicator. Then the tab Indicator is blue, obviously not consistent with the overall style, so let's learn how to customize tab Indicator. First we need to rewrite the Actionbartabstyle property, then point it to a new tab style and rewrite the Background property. It is important to note that background must specify a state-list drawable file so that different effects can be displayed in various states. So before we get started, we need to first prepare four images, respectively, for the four states of the tab, as shown below:
These four images indicate that tab check is not pressed, checked and pressed, unchecked, unchecked, and four states are pressed, then create a new Res/drawable/actionbar_tab_indicator.xml file, as shown in the code below:
<?xml version= "1.0" encoding= "Utf-8"? ><selector xmlns:android= "http://schemas.android.com/apk/res/ Android "> <item android:state_selected=" false " android:state_pressed=" false " Android: drawable= "@drawable/tab_unselected"/> <item android:state_selected= "true" android:state_pressed= " False " android:drawable=" @drawable/tab_selected "/> <item android:state_selected=" false " Android:state_pressed= "true" android:drawable= "@drawable/tab_unselected_pressed"/> <item Android : State_selected= "true" android:state_pressed= "true" android:drawable= "@drawable/tab_selected_pressed "/></selector>
The four states cited four images, so that the state-list drawable files were written. Then modify the Style.xml file, as shown in the following code:
<resources> <style name= "Customactionbartheme" parent= "@android: Style/theme.holo.light" > ...... <item name= "Android:actionbartabstyle" > @style/myactionbartabs</item> </style> < Style name= "Myactionbartabs" parent= "@android: Style/widget.holo.actionbar.tabview" > <item name= "Android : Background "> @drawable/actionbar_tab_indicator</item> </style></resources>
This first overrides the Actionbartabstyle attribute and points it to another custom style myactionbartabs, then overrides the Background property in this style and points to the actionbar_tab_ we just created Indicator can be. Now run the program again with the following effect:
As you can see, the color of the TAB indicator has become white, so it looks much more coordinated. In addition, there are many properties that can be customized for Action bar, which we cannot cover in this article, and more custom properties refer to the official documentation for learning. Well, the explanation of this article is here, combined up and down two, we have actionbar the most commonly used functions have learned, the next article I will lead you to the actual action bar usage, please look forward to.