Android Custom ViewGroup (i)--rounded rectangular menu with arrows

Source: Internet
Author: User

Today, we're going to make a rounded rectangular menu with arrows that looks like this:


The top arrow is required to align the menu anchor point, the menu item is pressed against the color, the background color and the press color can be configured.

The simplest way to do this is to let the UX give a picture of the triangle to the top, but on second thought this is not too low point, and different resolutions are not very good fit, simply customize a ViewGroup It!

The custom ViewGroup is actually very simple, basically is according to certain routine.

First, define a attrs.xml

is to make a statement about the configurable properties of your custom View , which you can configure in the future when you use it. 7 properties are declared here: Arrow width, arrowhead height, arrow horizontal offset, fillet radius, menu background color, shadow color, shadow thickness.

<resources>    <declare-styleable name= "Arrowrectangleview" >        <attr name= "Arrow_width" format= "Dimension"/>        <attr name= "Arrow_height" format= "Dimension"/>        <attr name= "Arrow_offset" format= "Dimension"/>        <attr name= "radius" format= "Dimension"/>        <attr name= "Background_color" format= " Color "/>        <attr name=" shadow_color "format=" color "/>        <attr name=" shadow_thickness "format=" Dimension "/>    </declare-styleable></resources>

Second, write a class that inherits ViewGroup , initialize these properties in the constructor

The

needs a obtainstyledattributes () typedarray recycle ()

public class Arrowrectangleview extends ViewGroup {... public arrowrectangleview (context context, AttributeSet        attrs, int defstyleattr) {Super (context, attrs, defstyleattr); TypedArray a = Context.gettheme (). Obtainstyledattributes (Attrs, R.styleable.arrowrectangleview, Defstyleatt        R, 0);            for (int i = 0; i < A.getindexcount (); i++) {int attr = A.getindex (i); Switch (attr) {Case r.styleable.arrowrectangleview_arrow_width:marrowwidth = A.getdime                    Nsionpixelsize (attr, marrowwidth);                Break Case r.styleable.arrowrectangleview_arrow_height:marrowheight = a.getdimensionpixelsize (attr, MArrowHe                    ight);                Break                    Case R.styleable.arrowrectangleview_radius:mradius = a.getdimensionpixelsize (attr, Mradius);                Break Case R.styleable.arrowrectangleview_backgrounD_color:mbackgroundcolor = A.getcolor (attr, Mbackgroundcolor);                Break Case r.styleable.arrowrectangleview_arrow_offset:marrowoffset = a.getdimensionpixelsize (attr, mArrowOf                    Fset);                Break                    Case R.styleable.arrowrectangleview_shadow_color:mshadowcolor = A.getcolor (attr, Mshadowcolor);                Break Case r.styleable.arrowrectangleview_shadow_thickness:mshadowthickness = a.getdimensionpixelsize (attr,                    mshadowthickness);            Break    }} a.recycle (); }

Third, rewrite the onmeasure () method

The Onmeasure () method, as the name implies, is used to measure the width and height of your viewgroup .

Let's consider the height first:

    • The first is to reserve the height for the arrows and rounded corners,maxheight To add these two
    • Then it is the measurement of all visible child,viewgroup has provided a ready-made measurechild () method
    • The next step is to add the height of the acquired child to the maxheight and, of course, to consider the upper and lower margin configuration
    • In addition, you need to take into account the upper and lower padding, as well as the height of shadows
    • Finally through the setmeasureddimension () setting takes effect

Consider the width:

    • The first is also to measure all visible child through the Measurechild () method
    • Then compare the width of these child with the margin configuration of the left and right , select the maximum value
    • And then there's the paddingof the left and right, and the shadow width
    • Finally through the setmeasureddimension () setting takes effect

    @Override protected void onmeasure (int widthmeasurespec, int heightmeasurespec) {int count = Getchildcount (        );        int maxWidth = 0;        Reserve space for the arrow and round corners int maxheight = marrowheight + Mradius;            for (int i = 0; i < count; i++) {final View child = Getchildat (i);            Final Marginlayoutparams LP = (marginlayoutparams) child.getlayoutparams ();                if (child.getvisibility ()! = GONE) {measurechild (Child, Widthmeasurespec, Heightmeasurespec);                MaxWidth = Math.max (MaxWidth, child.getmeasuredwidth () + Lp.leftmargin + lp.rightmargin);            MaxHeight = MaxHeight + child.getmeasuredheight () + Lp.topmargin + lp.bottommargin;        }} maxWidth = MaxWidth + getpaddingleft () + getpaddingright () + mshadowthickness;        MaxHeight = MaxHeight + getpaddingtop () + getpaddingbottom () + mshadowthickness; Setmeasureddimension (MaxWidth, maxheight);   } 

Does it look like it's easy? There are, of course, two minor problems:

1. When the height of the fillet is reserved for size, why only one radius is left, not the upper and lower two radii?

In fact, this is from the display effect to consider, if the upper and lower left a radius, will cause the menu border is very thick not good-looking, behind the implementation of OnLayout () when you will find that we layout the menu item will move up half a radius, so that the border looks much more beautiful.

2. Why can the child's layout parameters be strongly turned into marginlayoutparams?

Here you actually need to rewrite another method generatelayoutparams (), which returns the type of layout parameter you want. Generally , you can use Marginlayoutparams, but you may also use other types or custom types.

    @Override public    viewgroup.layoutparams generatelayoutparams (AttributeSet attrs) {        return new Marginlayoutparams (GetContext (), attrs);    }

Iv. overriding the onlayout () method

The OnLayout () method, as the name implies, is used to lay out all the sub - View in this viewgroup .

Actually each View has a layout () method, and all we need to do is put the right left/top/right/bottom The coordinates are passed in to this method.

As you can see here, we put a half radius on the menu item, so the topoffset only adds half a radius, and the coordinate on the right side is reduced by half the radius.

    @Override    protected void OnLayout (Boolean changed, int l, int t, int r, int b) {        int count = Getchildcount ();        int topoffset = t + marrowheight + MRADIUS/2;        int top = 0;        int bottom = 0;        for (int i = 0; i < count; i++) {            final View child = Getchildat (i);            top = topoffset + i * child.getmeasuredheight ();            Bottom = top + child.getmeasuredheight ();            Child.layout (L, Top, R-MRADIUS/2-mshadowthickness, bottom);        }    }

V. Overriding the Dispatchdraw () method

This is because we are writing a viewgroup container that does not need to be drawn, so we need to rewrite its dispatchdraw () method. If you are rewriting a specific View, you can also rewrite its onDraw () method.

The drawing process is divided into three steps:

1. Draw rounded rectangles

This step is relatively straightforward, and the direct call to Canvas 's drawroundrect () is complete.

2. Draw a triangular arrow

This requires setting a path based on the configured properties, and then calling the Canvas 's DrawPath () to finish drawing.

3. Draw the Menu Shadow

This is to change a color and then draw a rounded rectangle, the position is slightly offset, of course, there should be a blur effect.

To get a blur effect, you need to configure it through the setmaskfilter () of Paint , and you need to turn off hardware acceleration for that layer in the API is clearly stated.

In addition, you need to set the source image and the target image overlap mode, the shadow is clearly stacked to the back of the menu, according to know, we need to choose dst_over mode.

The other details look at the code as clear:

@Override protected void Dispatchdraw (canvas canvas) {//Disable h/w acceleration for blur mask filter s        Etlayertype (view.layer_type_software, NULL);        Paint paint = new paint ();        Paint.setantialias (TRUE);        Paint.setcolor (Mbackgroundcolor);        Paint.setstyle (Paint.Style.FILL);        Set Xfermode for source and shadow overlap Paint.setxfermode (new Porterduffxfermode (PorterDuff.Mode.DST_OVER));        Draw Round Corner Rectangle Paint.setcolor (mbackgroundcolor); Canvas.drawroundrect (New RECTF (0, Marrowheight, Getmeasuredwidth ()-Mshadowthickness, Getmeasuredheight ()-        mshadowthickness), Mradius, Mradius, paint);        Draw Arrow Path PATH = new Path ();        int startPoint = Getmeasuredwidth ()-marrowoffset;        Path.moveto (StartPoint, marrowheight);        Path.lineto (StartPoint + marrowwidth, marrowheight);        Path.lineto (startPoint + MARROWWIDTH/2, 0);        Path.close (); Canvas.drawpath (PAth, paint); Draw Shadow if (Mshadowthickness > 0) {paint.setmaskfilter (new Blurmaskfilter (Mshadowthickness, B            LurMaskFilter.Blur.OUTER));            Paint.setcolor (Mshadowcolor); Canvas.drawroundrect (New RECTF (mshadowthickness, Marrowheight + mshadowthickness, getmeasuredwidth ()-        Mshadowthickness, Getmeasuredheight ()-mshadowthickness), Mradius, Mradius, paint);    } super.dispatchdraw (canvas); }

Vi. referencing the custom viewgroup in the layout XML

So far, the implementation of the custom ViewGroup has been completed, so let's use it in the project! There are two small differences between using custom viewgroup and using System viewgroup components:

One is to specify the full package name, otherwise the component will not be found when it is run.

Second, you need to specify a namespace when configuring custom attributes to avoid confusion with the default Android namespace . For example, a new app namespace is specified to refer to custom attributes.

<?xml version= "1.0" encoding= "Utf-8"? ><com.xinxin.arrowrectanglemenu.widget.arrowrectangleview xmlns: Android= "Http://schemas.android.com/apk/res/android" xmlns:app= "Http://schemas.android.com/apk/res-auto" and        Roid:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:orientation= "vertical"        Android:background= "@android: Color/transparent" android:paddingleft= "3DP" android:paddingright= "3DP" Android:splitmotionevents= "false" app:arrow_offset= "31DP" app:arrow_width= "16DP" app:arrow_height= "8d P "app:radius=" 5DP "app:background_color=" #ffb1df83 "app:shadow_color=" #66000000 "app:shadow_t hickness= "5DP" > <linearlayout android:id= "@+id/cmx_toolbar_menu_turn_off" android:layout_width= "Wra            P_content "android:layout_height=" 42DP "> <textview android:layout_width=" wrap_content " android:layout_height="Wrap_content" android:layout_gravity= "center_vertical" android:textsize= "16SP" android:t Extcolor= "#FF393F4A" android:paddingleft= "16DP" android:paddingright= "32DP" Android:click Able= "false" android:text= "menu Item #1"/> </LinearLayout> <linearlayout android:id= "@ +id/cmx_toolbar_menu_feedback "android:layout_width=" wrap_content "android:layout_height=" 42DP "> & Lt TextView android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android : layout_gravity= "center_vertical" android:textsize= "16sp" android:textcolor= "#FF393F4A" a ndroid:paddingleft= "16DP" android:paddingright= "32DP" android:clickable= "false" Android:t Ext= "menu Item #2"/> </LinearLayout></com.xinxin.arrowrectanglemenu.widget.ArrowRectangleView>

Refer to the layout XML in the code

This is not the same as referencing the normal layout xml , this is mainly in the creation of the pop-up menu when the layoutof the XML is specified, specifically, the sample code is clear.

At this point, a complete custom viewgroup process is gone, and there is time to write some more complex custom components, but original aim, the basic principle is the same as the steps. This article is to offer, hope can give the need to customize ViewGroup Friends some help.

Sample code Download (CSDN)

Https://github.com/qianxin2016/ArrowRectangleMenu

Android Custom ViewGroup (i)--rounded rectangular menu with arrows

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.