Android uses property animations to customize the gradient background of a view

Source: Internet
Author: User
Tags gety

Customize the view gradient background while listening gestures automatically generate small spheres.

The host activity is as follows:

Package Com.edaixi.tempbak;import Java.util.arraylist;import Android.animation.animator;import Android.animation.animatorlisteneradapter;import Android.animation.animatorset;import Android.animation.argbevaluator;import Android.animation.objectanimator;import Android.animation.ValueAnimator; Import Android.annotation.suppresslint;import Android.app.activity;import Android.content.context;import Android.graphics.canvas;import Android.graphics.paint;import Android.graphics.radialgradient;import Android.graphics.shader;import Android.graphics.drawable.shapedrawable;import Android.graphics.drawable.shapes.ovalshape;import Android.os.bundle;import Android.view.motionevent;import Android.view.view;import Android.view.window;import Android.view.animation.accelerateinterpolator;import Android.view.animation.decelerateinterpolator;import android.widget.LinearLayout; @SuppressLint ("Newapi") public Class Mainactivity extends activity {/** Called when the activity is first created. */@Overridepublicvoid OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Requestwindowfeature (window.feature_ No_title); Setcontentview (R.layout.activity_main); LinearLayout container = (linearlayout) Findviewbyid (R.id.container); Container.addview (new Myanimationview (This));} public class Myanimationview extends View {private static final int RED = 0xffff8080;private static final int BLUE = 0XFF8 080ff;private static final int CYAN = 0xff80ffff;private static final int GREEN = 0xff80ff80;public final Arraylist<sha peholder> balls = new arraylist<shapeholder> (); Animatorset animation = Null;public Myanimationview (context context) {super (context);/****************************** * * Set the background of the custom view, is a gradual process, with valueanimator implementation, Valueanimator is the core class of the property * Animation system, which contains most of the methods for configuring the properties Animation attribute, which requires a direct or indirectly using the Valueanimator class, the steps to use Valueanimator are as follows: * 1. Call Ofint in the Valueanimation class (int ... Values), OFfloat (String * propertyname,float...values) and other static party * methods instantiate the Valueanimator object, and set the property name, initial value or end value equivalent of the target attribute; * 2. Call the Addupdatelistener (Animatorupdatelistener * Mlistener) method to set the listener for the property change for the Valueanimator object * 3. Create a custom Interpolator, Call Setinterpolator (Timeinterpolator * value) to set the custom interpolator for valueaniamtor; (optional, do not set default defaults) * 4. Create a custom Typeevaluator , Call Setevaluator (Typeevaluator * value) to set the custom typeevaluator for valueanimator; (optional, do not set default defaults) * 5. In Animatorupdatelistener The implementation method in the target object sets the calculated property value for the property. * 6. Set the duration of the animation, whether repeat and repeat the number of properties; 7. Set the target object for Valueanimator and start the animation. * * ***************************************************************** */valueanimator ColorAnim = Objectanimator.ofint (This, "BackgroundColor", RED, BLUE); coloranim.setduration; Coloranim.setevaluator (new Argbevaluator ()); Coloranim.setrepeatcount (valueanimator.infinite); Coloranim.setrepeatmode ( Valueanimator.reverse); Coloranim.start ();} @SuppressLint ("Newapi") @Overridepublic boolean ontouchevent (Motionevent event) {if (event.getaction ()! = motionevent.action_down&& Event.getaction ()! = Motionevent.action_move) {return false;}  Shapeholder Newball = Addball (Event.getx (), Event.gety ())/** bouncing animation with squash and stretch **/float starty = Newball.gety (); Float EndY = GetHeight ()-50f;float h = (float) getheight (); Float eventy = Event.gety (); int duration = (i NT) ($ * ((H-eventy)/h)); Valueanimator Bounceanim = objectanimator.offloat (Newball, "Y", Starty, EndY); bounceanim.setduration (duration); Bounceanim.setinterpolator (New Accelerateinterpolator ()); Valueanimator squashAnim1 = objectanimator.offloat (Newball, "X", Newball.getx (), Newball.getx ()-25f); Squashanim1.setduration (DURATION/4); Squashanim1.setrepeatcount (1); Squashanim1.setrepeatmode ( Valueanimator.reverse); Squashanim1.setinterpolator (new Decelerateinterpolator ()); Valueanimator squashAnim2 = objectanimator.offloat (Newball, "width", newball.getwidth (), newball.getwidth () + 50); Squashanim2.setduration (DURATION/4); Squashanim2.setrepeatcount (1); Squashanim2.setrepeatmode (ValueAnimatoR.reverse); Squashanim2.setinterpolator (new Decelerateinterpolator ()); Valueanimator stretchAnim1 = objectanimator.offloat (Newball, "Y", EndY, EndY + 25f); Stretchanim1.setduration (Duration/ 4); Stretchanim1.setrepeatcount (1); Stretchanim1.setinterpolator (new Decelerateinterpolator ()); Stretchanim1.setrepeatmode (Valueanimator.reverse); Valueanimator stretchAnim2 = objectanimator.offloat (Newball, "height", newball.getheight (), Newball.getheight ()-25); Stretchanim2.setduration (DURATION/4); Stretchanim2.setrepeatcount (1); Stretchanim2.setinterpolator (new Decelerateinterpolator ()); Stretchanim2.setrepeatmode (Valueanimator.reverse); Valueanimator Bouncebackanim = objectanimator.offloat (Newball, "Y", EndY, Starty); Bouncebackanim.setduration ( Duration); Bouncebackanim.setinterpolator (new Decelerateinterpolator ());//Sequence the Down/squash&stretch/up Animationsanimatorset bouncer = new Animatorset (); Bouncer.play (Bounceanim). before (SQUASHANIM1); Bouncer.play ( SQUASHANIM1). with (SQUASHANIM2); bouncer.play(SQUASHANIM1). with (STRETCHANIM1), Bouncer.play (SQUASHANIM1). with (STRETCHANIM2); Bouncer.play (Bouncebackanim). After (stretchAnim2);//Fading animation-remove the ball when the animation is donevalueanimator Fadeanim = Objectanimato R.offloat (Newball, "Alpha", 1f, 0f); fadeanim.setduration (+); Fadeanim.addlistener (new Animatorlisteneradapter () {@ overridepublic void Onanimationend (Animator animation) {Balls.remove (((objectanimator) animation). Gettarget ());}}); /Sequence The animations to play one after the otheranimatorset animatorset = new Animatorset (); Animatorset.play (Boun CER). before (Fadeanim);//Start the Animationanimatorset.start (); return true;} Private Shapeholder Addball (float x, float y) {OvalShape circle = new OvalShape (); Circle.resize (50f, 50f); Shapedrawable drawable = new shapedrawable (circle); Shapeholder Shapeholder = new Shapeholder (drawable); Shapeholder.setx (x-25f); shapeholder.sety (y-25f); int red = (int) (M Ath.random () * 255); int green = (int) (Math.random () * 255); int blue = (int) (Math.random () * 255); int color = 0xff000000 | Red << 16 | Green << 8 | Blue Paint paint = drawable.getpaint (); new//Paint (paint.anti_alias_flag); int darkcolor = 0xff000000 | RED/4 << 16 | GREEN/4 << 8 | BLUE/4; Radialgradient gradient = new Radialgradient (37.5f, 12.5f, 50f,color, Darkcolor, Shader.TileMode.CLAMP); Paint.setshader (gradient); Shapeholder.setpaint (paint); Balls.add (Shapeholder); return shapeholder;} @Overrideprotected void OnDraw (canvas canvas) {for (int i = 0; i < balls.size (); ++i) {Shapeholder Shapeholder = balls. Get (i); Canvas.save (); Canvas.translate (Shapeholder.getx (), Shapeholder.gety ()), Shapeholder.getshape (). Draw ( Canvas); Canvas.restore ();}}}

  

Custom

As follows:

/* Copyright (C) The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License") ; * You are not a use this file except in compliance with the License. * Obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * unless required by appli Cable law or agreed into writing, software * Distributed under the License is distributed on a "as is" BASIS, * without Warranties or CONDITIONS of any KIND, either express OR implied. * See the License for the specific language governing permissions and * limitations under the License. */package Com.edaixi.tempbak;import Android.graphics.paint;import Android.graphics.radialgradient;import Android.graphics.drawable.shapedrawable;import android.graphics.drawable.shapes.shape;/** * A data structure that Holds a shape and various properties that can being used to define * how the shape is drawn.    */public class Shapeholder {private float x = 0, y = 0; Private Shapedrawable ShaPe    private int color;    Private radialgradient gradient;    Private float alpha = 1f;    private paint paint;    public void Setpaint (paint value) {paint = value;    } Public Paint Getpaint () {return paint;    } public void SetX (float value) {x = value;    } public float GetX () {return x;    } public void Sety (float value) {y = value;    } public float GetY () {return y;    } public void Setshape (shapedrawable value) {shape = value;    } public shapedrawable Getshape () {return shape;    } public int GetColor () {return color;        } public void SetColor (int value) {shape.getpaint (). SetColor (value);    color = value;    } public void Setgradient (radialgradient value) {gradient = value;    } public radialgradient Getgradient () {return gradient;        } public void Setalpha (float alpha) {this.alpha = Alpha; Shape.setalpha ((int) ((Alpha * 255f) +. 5f));    } public float getwidth () {return Shape.getshape (). GetWidth ();        } public void SetWidth (float width) {Shape s = shape.getshape ();    S.resize (width, s.getheight ());    } public float GetHeight () {return Shape.getshape (). GetHeight ();        } public void SetHeight (float height) {Shape s = shape.getshape ();    S.resize (S.getwidth (), height);    } public Shapeholder (shapedrawable s) {shape = s; }}

  

The custom layout layout gradient background is as follows:

Package Com.edaixi.tempbak;import Android.animation.argbevaluator;import Android.animation.objectanimator;import Android.animation.valueanimator;import Android.annotation.suppresslint;import Android.content.Context;import Android.util.attributeset;import android.widget.RelativeLayout; @SuppressLint ("Newapi") public class Customerrelativelayout extends Relativelayout {private static final int RED = 0xffff8080;private static final int BLUE = 0 Xff8080ff;public Customerrelativelayout (Context context) {super (context); SETBG ();} Public Customerrelativelayout (context context, AttributeSet attrs,int defstyleattr, int defstyleres) {Super (context, Attrs, Defstyleattr, defstyleres); SETBG ();} Public Customerrelativelayout (context context, AttributeSet Attrs,int defstyleattr) {Super (context, attrs, DEFSTYLEATTR); SETBG ();} Public Customerrelativelayout (context context, AttributeSet Attrs) {Super (context, attrs); SETBG ();} public void Setbg () {Valueanimator Coloranim = Objectanimator.ofint (This, "BACKGROUNDCOlor ", RED, BLUE); coloranim.setduration (+); Coloranim.setevaluator (new Argbevaluator ()); Coloranim.setrepeatcount (Valueanimator.infinite); Coloranim.setrepeatmode (Valueanimator.reverse); Coloranim.start ();}}

  

A reference in the layout can "

<?xml version= "1.0" encoding= "Utf-8"? ><com.edaixi.tempbak.customerrelativelayout xmlns:android= "/http Schemas.android.com/apk/res/android "    android:id=" @+id/rl_container "    android:layout_width=" match_parent "    android:layout_height=" match_parent "    android:orientation=" vertical "></ Com.edaixi.tempbak.customerrelativelayout>

  

Android uses property animations to customize the gradient background of a view

Related Article

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.