Custom Actionprovider ToolBar custom menu Little Red dot
Copyright NOTICE: Reprint must indicate this article transferred from Zhangjie's blog: http://blog.csdn.net/yanzhenjie1003
Several goals for today:
1. Custom Actionprovider
2. Toolbar Actionbar custom Menu
3. Toolbar ActionBar Right Menu Add a corner label (Toolbar ActionBar menu add Little red dot)
The source code is at the end of the article.
Effect Preview
Customizing the menu does not affect any effects of the native Md. You can control properties such as text and colors displayed externally.
Requirements Description and Analysis
Usually we customize it to Titlebar
achieve many custom effects. But then Toolbar
it was really good to come out, so we all used it, Toolbar
but what do we do to the right side of the Menu Button
implementation similar to BadgeView
this effect (such as the Little Red dot)?
The students who have not played after seeing this request ActionProvider
may panic, but please follow me to analyze the composition of this Menu
: a ImageView
display icon, a TextView
display number, and a TextView
circular background (can be any shape or color). Then you can not use the system menu.xml this to do, so to customize the menu, someone might think of custom view,but do not need.
We usually write the menu when the Menu.xml is probably the following:
<?xml version= "1.0" encoding= "Utf-8"? <menu xmlns:android = "Http://schemas.android.com/apk/res /android " xmlns:app =" HTTP +/ Schemas.android.com/apk/res-auto "; <item android:id = "@+id/menu_pic" android:title = "Zhangjie Blog" app:showasaction =/> </< Span class= "Hljs-title" >menu ;
In fact, this menu item has a android:actionProviderClass
property, this property can be used to customize the content shown here (View), the value of this property is a complete class name, such as this com.yanzhenjie.XXOOProvider
, and this XXOOProvider
need to inherit ActionProvider
, the specific operation is all in ActionProvider
the Completed in.
First inherit
ActionProvider
Here to sit down special instructions, because it Toolbar
is support
under the package, so we want to use the support
following ActionProvider
class, this class is support.v4
under, it is compatible Toolbar
and ActionBar
, so we customize this ActionProvider
class can be in Toolbar
and ActionBar
used freely in the.
Because we want to achieve the angle mark, for the moment, the name of the class BadgeActionProvider
, inheritance ActionProvider
needs to implement the onCreateActionView()
method:
publicclass BadgeActionProvider extends ActionProvider { publicBadgeActionProvider(Context context) { super(context); } @Override publiconCreateActionView() { return view; }}
Custom layouts: Badgeview to display
We see the onCreateActionView()
class needs return
one View
, this View
is what we want to customize the view, so we then define the display View
, very simple is the article at the beginning of the analysis of one ImageView
and one TextView
:
<?xml version= "1.0" encoding= "Utf-8"?><relativelayout xmlns:android="Http://schemas.android.com/apk/res/android" android:layout_width="Wrap_content"android:layout_height="Match_parent" android:background="Actionbaritembackground"> <ImageViewandroid:id= "@+id/iv_icon"android:layout_width="Wrap_ Content "android:layout_height=" Match_parent "android:layout_centerinparent= "True"android:scaletype="center" /> <TextView Android:id="@+id/tv_badge" Android:layout_width="Wrap_content" Android:layout_height="Wrap_content" Android:layout_alignparentend="true" Android:layout_alignparentright="true" Android:layout_margin="2DP" Android:background="@drawable/circle_red" android:gravity="Center" Android:text="0" Android:textcolor="@android: Color/white" android:textsize="12SP"/></relativelayout>
The above code must be interpreted only by referring to the android:background="?actionBarItemBackground"
system default Toolbar
/ ActionBar
the Menu
click Effect. TextView
android:background="@drawable/circle_red"
is the red background of the circle.
Combination of Actionprovider and custom layouts
The above inheritance is also finished, the custom layout is also written, followed by the combination of the two:
Public class badgeactionprovider extends actionprovider { PrivateImageView Mivicon;PrivateTextView Mtvbadge;//To record which view is clicked, so that the external can use a listener to accept multiple menu clicks. Private intClickwhat;PrivateOnclicklistener Onclicklistener; Public Badgeactionprovider(Context context) {Super(context); }@Override PublicViewOncreateactionview() {intSize = GetContext (). Getresources (). Getdimensionpixelsize (Android.support.design.r.dimen.abc_action_bar_default_ Height_material); Viewgroup.layoutparams Layoutparams =NewViewgroup.layoutparams (size, size); View view = Layoutinflater.from (GetContext ()). Inflate (R.layout.menu_badge_provider,NULL,false); View.setlayoutparams (Layoutparams); Mivicon = (ImageView) View.findviewbyid (R.id.iv_icon); Mtvbadge = (TextView) View.findviewbyid (R.id.tv_badge); View.setonclicklistener (Onviewclicklistener);returnView }//Click to process. PrivateView.onclicklistener Onviewclicklistener =NewView.onclicklistener () {@Override Public void OnClick(View v) {if(Onclicklistener! =NULL) Onclicklistener.onclick (clickwhat); } };//External settings monitoring. Public void Setonclicklistener(intWhat, Onclicklistener Onclicklistener) { This. Clickwhat = what; This. Onclicklistener = Onclicklistener; } Public interface onclicklistener { voidOnClick (intwhat); }}
The above code is the only one with doubts:
int size = getContext().getResources().getDimensionPixelSize( android.support.design.R.dimen.abc_action_bar_default_height_material);
This sentence is read support
down Toolbar
/ ActionBar
the height, in order to let the menu high and wide system to menu
achieve consistency.
All right, the ActionProvider
customization is basically over, add a few more custom methods:
//settings icon. public void SetIcon (@DrawableRes int icon) {mivicon.setimageresource (icon);} //set the number displayed. public void Setbadge (int i) {Mtvbadge.settext (integer.tostring (i));} //set the text. public void Settextint (@StringRes int i) {mtvbadge.settext (i);} //set the displayed text. public void SetText (charsequence i) {mtvbadge.settext (i);}
How to use a custom
ActionProvider
Now it's time to go back to the beginning of the article, android:actionProviderClass
fill in the full custom class name for the attribute, ActionProvider
and say this is supprt
the class, so here's a little bit of a change:
<?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/menu_pic" android:title="严振杰的博客" app:actionProviderClass="com.yanzhenjie.BadgeActionProvider" app:showAsAction="always" /></menu>
We have noticed that this has become the app:actionProviderClass
result of the introduction of the XML Header xmlnamespace
.
Java Code Control custom menu
The above Menu.xml preparation work is done, the next is to use Java code to load the XML into our Activity
or Fragment
in, here we take Activity
for example, we inherit AppCompatActivity
.
First, when loading the menu, record what we just customized ActionProvider
:
private BadgeActionProvider mActionProvider;@OverridepublicbooleanonCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); MenuItem menuItem = menu.findItem(R.id.menu_delete); mActionProvider = (BadgeActionProvider) MenuItemCompat.getActionProvider(menuItem); mActionProvider.setOnClickListener(0, onClickListener);// 设置点击监听。 returntrue;}
Special note: A lot of classmates here Setonclicklistener when there is a null pointer exception, because the app:actionProviderClass="com.yanzhenjie.BadgeActionProvider"
code refers to the custom class name error, you have to fill in your package name, do not copy the blog here.
Here set click to listen in the above also stressed, here is a pit to talk about, we just did not provide a few methods to set the icon and text, cannot be onCreateOptionsMenu()
called directly, because Actionprovider has not loaded initialization completed , So if we initialize the icon and text dynamically, it needs to be in onWindowFocusChanged()
:
@OverridepublicvoidonWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); mActionProvider.setIcon(R.mipmap.ic_action_delete_small); mActionProvider.setIcon(R.mipmap.ic_action_picture);}
here also to illustrate, just onCreateOptionsMenu()
can not be directly initialized, and so on after the onCreateOptionsMenu()
execution of the method is free to call .
So now you can set the display of text and icons, then our article at the beginning of a number of targets are also completed, go to sleep, everyone goodnight.
This tutorial source code portal
Copyright statement: Reprint must indicate this article transferred from Zhangjie's blog: http://blog.csdn.net/yanzhenjie1003
Custom Actionprovider ToolBar custom menu Little Red dot