The realization of the click effect of water ripple in Android l

Source: Internet
Author: User

Bo Master participated in the CSDN blog star selection, help me vote it.

Click to vote for me


Objective

Some time ago Android L (Android 5.0) came out, the interface made some changes, mainly to add a number of animations and some new controls, I believe you have a view of the click Effect-Water ripple is very impressive, click on a view, then a ripple of water will spread from the point of click, This article is to analyze the implementation of this effect. First of all, the implementation of the L on the first, this ripple effect, L provides an animation, called the reveal effect, the bottom is through the view of the canvas and then constantly refresh the view to complete, this effect requires view support, and in the lower version of the view is not supported, so, The reveal effect cannot be run directly in the lower version. However, we understand its effect, its principle, or can be simulated to achieve this effect, in all fairness, write a ripple effect of the custom view is not difficult, or very simple, but the view of a lot of sub-class, if you want to implement button, edit and other controls, this is more cumbersome , so, do we think there is a simpler way? In fact, we can write a custom layout, and then let all the clickable elements in layout have a ripple effect, which greatly simplifies the whole process. This article will then analyze the implementation of this layout, before we look at the effect.


Realize the idea

First we customize a layout, here we select LinearLayout, as for the reasons, the article will be analyzed below. When the user clicks on a clickable element, such as button, we need to get the information of the element that the user clicked on, including: which element the user clicked, the width, height, position information of the element that the user clicked on. After getting the button information, I can determine the range of the water ripple, and then redraw through layout to draw the ripples, so that the water ripple effect is achieved, of course, this is just the approximate steps, there are some details need to be dealt with in the middle.

Selection of layout

Now that we're going to implement a custom layout, then we're going to choose that layout, LinearLayout, Relativelayout, framelayout? I choose LinearLayout here. Why is it? Perhaps some people will ask, should not use Relativelayout? Because Relativelayout is more powerful, it can implement complex layouts, but LinearLayout and framelayout are not. Yes, Relativelayout is powerful, but considering the effect of water waves is achieved by frequent refresh of layout, because of frequent repainting, we have to consider performance issues, relativelayout performance is the worst (because there are many things to do), because, for performance, We choose LinearLayout, as for framelayout, it is too simple to use. When the complex layout is implemented, we can wrap the linearlayout outside the element with the ripple effect so that it does not have too heavy a task to redraw.

Based on the above analysis, we define the following layout:

public class Reveallayout extends LinearLayout implements Runnable

Implementation process

The implementation process is mainly to solve the following problems:

1. How to know which element the user clicked on

2. How to get the information of the clicked element

3. How to redraw and draw water ripple through layout

4. If you delay the distribution of the UP event

The following analysis

How to know which element the user clicked on

This problem is good, in order to know which element the user clicked (this element is generally clickable, otherwise it is meaningless), we have to intercept all the click events in advance, so we should rewrite the layout of the Dispatchtouchevent method, note that It is not recommended to use Onintercepttouchevent, because onintercepttouchevent is not always callback, for specific reasons please refer to the View System parsing series I wrote earlier. Then when the user clicks, there will be a series of down, move, up events, we want to be down to determine which element the event falls on, the element is the user click on the element, of course, in order to be rigorous, we also have to determine whether the up time also falls on the same element above, because, The rule of the system click event is that both down and up fall on the same clickable element.

    @Override public boolean dispatchtouchevent (Motionevent event) {int x = (int) event.getrawx ();        int y = (int) Event.getrawy ();        int action = Event.getaction ();            if (action = = motionevent.action_down) {View Touchtarget = Gettouchtarget (this, x, y);                if (touchtarget.isclickable () && touchtarget.isenabled ()) {mtouchtarget = Touchtarget;                Initparametersforchild (event, Touchtarget);            Postinvalidatedelayed (invalidate_duration);            }} else if (action = = motionevent.action_up) {mispressed = false;            Postinvalidatedelayed (invalidate_duration);            Mdispatchuptoucheventrunnable.event = event;            Postdelayed (mdispatchuptoucheventrunnable, 400);        return true;            } else if (action = = motionevent.action_cancel) {mispressed = false;        Postinvalidatedelayed (invalidate_duration); } return Super.disPatchtouchevent (event); }
Through the above code, we can know that when down, we take out the screen coordinates of the Click event, and then go through the view tree to find the user clicked on the view, the code is as follows, is to determine whether the coordinates of the event fall in the scope of the view, this is no longer said, more good understanding. Note that the coordinates of the event can not be used getx and gety, but with Getrawx and Getrawy, the difference is that the former is relative to the coordinates of the clicked view, the latter is relative to the screen coordinates, Our goal view is specific to which layer of layout we cannot know, so we have to use the absolute coordinates of the screen to calculate it. With the coordinates of the event, and then according to the absolute coordinates of the view in the screen, as long as the event's XY is determined to fall in the upper and lower four corners of the view, you can know whether the event falls on the view, so that the user clicked on the view.

    Private View Gettouchtarget (view view, int x, int y) {        view target = null;        arraylist<view> touchableviews = View.gettouchables ();        for (View child:touchableviews) {            if (Istouchpointinview (child, X, y)) {                target = child;                break;            }        }        return target;    }    Private Boolean Istouchpointinview (view view, int x, int y) {        int[] location = new Int[2];        View.getlocationonscreen (location);        int left = location[0];        int top = location[1];        int right = left + view.getmeasuredwidth ();        int bottom = top + view.getmeasuredheight ();        if (view.isclickable () && y >= top && y <= bottom                && x >= left && x <= ri ght) {            return true;        }        return false;    }
How to get the information of the clicked element this is relatively simple, the information of the clicked element is: wide, high, left, top, right, bottom, get their code as follows:

        int[] location = new Int[2];        Mtouchtarget.getlocationonscreen (location);        int left = location[0]-mlocationinscreen[0];        int top = location[1]-mlocationinscreen[1];        int right = left + mtouchtarget.getmeasuredwidth ();        int bottom = top + mtouchtarget.getmeasuredheight ();
Description: Mtouchtarget refers to the view that the user clicked.

How to redraw a water ripple with layout

This feasted ripple is relatively simple, just use drawcircle to draw a translucent ring, here is the main time to draw. In general, we will choose to draw in the OnDraw, which is true, but for the effect in L is not appropriate, to see the view of the drawing process, we will understand that the view is drawn in general follows the following process: First draw the background, then draw their own (OnDraw), Then draw the child elements (Dispatchdraw), and finally draw some decorations such as scrollbars (ondrawscrollbars), so if we draw ripples in OnDraw, then because the child elements are drawn after OnDraw, Causes the child element to cover the circle we draw, so that the ring may not be visible, because it is important to draw my time. According to the drawing process of view, we choose Dispatchdraw more suitable, when all the child elements are drawn, then the ripple is drawn. Reading this, we will be more aware of why we choose LinearLayout and why we do not recommend that the view's nesting level be too deep, because if the view itself is heavier or the nesting level too deep, it will lead to a time-consuming increase in dispatchdraw execution. This way the water waves are drawn with a slight effect. Therefore, the smoothness of performance is also important in the code and needs to be considered. Also, in order not to let the drawn ring exceed the range of the clicked element, we need to clip the canvas. To have a ripple effect, we need to redraw the layout frequently and change the radius of the ring during redrawing, so that a dynamic ripple of water comes out. Still, I come to the performance considerations, we chose to use postinvalidatedelayed (long delaymilliseconds, int left, int top, int right, int bottom) to perform a partial redraw of the view, because, Other areas do not need to be redrawn, just the area where the clicked element needs to be redrawn. The reason why we should adopt the delayed method is that we can't keep on refreshing, there must be a little time interval, the advantage is: Avoid view redraw to preempt excessive time slices and thus cause potential indirect stack overflow, because invalidate will directly lead to draw call.

The specific code is as follows:

    protected void Dispatchdraw (canvas canvas) {super.dispatchdraw (canvas);        if (!mshoulddoanimation | | mtargetwidth <= 0 | | mtouchtarget = = NULL) {return;        } if (Mrevealradius > Mminbetweenwidthandheight/2) {mrevealradius + = Mrevealradiusgap * 4;        } else {Mrevealradius + = Mrevealradiusgap;        } int[] location = new INT[2];        Mtouchtarget.getlocationonscreen (location);        int left = location[0]-mlocationinscreen[0];        int top = location[1]-mlocationinscreen[1];        int right = left + mtouchtarget.getmeasuredwidth ();        int bottom = top + mtouchtarget.getmeasuredheight ();        Canvas.save ();        Canvas.cliprect (left, top, right, bottom);        Canvas.drawcircle (Mcenterx, Mcentery, Mrevealradius, Mpaint);        Canvas.restore (); if (Mrevealradius <= Mmaxrevealradius) {postinvalidatedelayed (invalidate_duration, left, top, right, bottom        ); } ElSe if (!mispressed) {mshoulddoanimation = false;        Postinvalidatedelayed (Invalidate_duration, left, top, right, bottom); }    }
So far, this layout we have achieved, but careful you, will certainly find that there is nothing wrong with the place. For example, you can add a click event to a button, and when the button is clicked, an activity will soon find the problem: The water wave has not finished, the activity is up, causing the water wave effect is greatly discounted, and carefully observe the effect of Android L, We find that l always wait until the water wave effect is finished before the next action is performed. So, the last problem to be solved, please look at the following analysis

How to delay the distribution of up events

In response to the above question, if we can delay the distribution of up time, such as 400ms delay, so that the water waves have enough time to play, and then distribute the up event, so that the problem can be resolved. In the beginning, I did this, first look at the following code:

else if (action = = motionevent.action_up) {            mispressed = false;            Postinvalidatedelayed (invalidate_duration);            Mdispatchuptoucheventrunnable.event = event;            Postdelayed (mdispatchuptoucheventrunnable, n);            return true;        
It can be found that when up, I did not go directly to the system distribution process, just forcibly consume the point up event and then delay distribution, see the code:

    Private class Dispatchuptoucheventrunnable implements Runnable {public        motionevent event;        @Override public        Void Run () {            if (Mtouchtarget = = NULL | |!mtouchtarget.isenabled ()) {                return;            }            if (Istouchpointinview (mtouchtarget, (int) event.getrawx (), (int) Event.getrawy ())) {                Mtouchtarget.dispatchtouchevent (event);}}    ;

So far, the above problems have been analyzed, we can easily achieve the effect of water ripple click.

SOURCE download

The demo source in this article is temporarily not open to the Internet, please dabigatran 215680213 , download the source code in the group share.

The realization of the click effect of water ripple in Android l

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.