Android: Simple bullet screen effect achieved

Source: Internet
Author: User

First of all. Similar to the 360 Detected harassment phone page:


The layout is very easy, the above is a relativelayout, the following a button.

Function:

(1) After the barrage has been generated, he actively scrolls from the right side toward the left side (translateanimation). When the barrage disappears, it is removed immediately.

(2) The position of the projectile screen appears randomly. And do not repeat (prevent the text from overlapping).

(3) The font size changes randomly within a certain range. Font color can also be set.

(4) Self-defined deceleration, after the acceleration of the interpolator, the barrage to accelerate the entry, deceleration stay, and then accelerate out.

1.Activity Code:

/** * Simple bullet screen effect implementation * Created by admin on 15-6-4.    */public class Mainactivity extends Actionbaractivity {private MyHandler handler;    The content of the barrage is private tanmubean tanmubean;    The parent component that placed the content of the bullet screen private relativelayout containervg;    The height of the parent component, private int validheightspace;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        CONTAINERVG = (relativelayout) Findviewbyid (R.id.tanmu_container);        Tanmubean = new Tanmubean (); Tanmubean.setitems (New string[]{"Test", "bomb screen this thing really bad do ah", "always come up with various problems ~ ~", "Do not know why?" Trouble! "And who is the great God who can help me?" "I need your help.", "Test it," "It's a bad thing to do," "always come up with all kinds of problems ~", "Do not know why?" Trouble!

"And who is the great God who can help me?" "I need your help.", "Test it," "It's a bad thing to do," "always come up with all kinds of problems ~", "Do not know why?" Trouble!

"And who is the great God who can help me?" "," I need your Help. "}); Handler = new MyHandler (this); Start the barrage View Starttanmuview = Findviewbyid (R.ID.STARTTANMU); Starttanmuview.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {if (Containervg.getchildcount () > 0) {return; } existmarginvalues.clear (); New Thread (New Createtanmuthread ()). Start (); } }); }//each 2s itself actively joins a pop-up screen private class Createtanmuthread implements Runnable {@Override public void run () { int N = Tanmubean.getitems (). length; for (int i = 0; i < N; i++) {handler.obtainmessage (1, I, 0). Sendtotarget (); Systemclock.sleep (2000); }}}//need to add components to the main city private static class MyHandler extends Handler {private Weakreference<maina Ctivity> ref; MyHandler (MaInactivity ac) {ref = new weakreference<> (AC); } @Override public void Handlemessage (Message msg) {super.handlemessage (msg); if (msg.what = = 1) {mainactivity AC = Ref.get (); if (AC! = NULL && Ac.tanmubean! = null) {int index = MSG.ARG1; String content = Ac.tanmuBean.getItems () [index]; float textSize = (float) (Ac.tanmuBean.getMinTextSize () * (1 + math.random () * Ac.tanmuBean.getRange ())); int textcolor = Ac.tanmuBean.getColor (); Ac.showtanmu (content, textSize, textcolor); }}}} private void Showtanmu (String content, float textSize, int textcolor) {final TEXTV Iew TextView = new TextView (this); Textview.settextsize (textSize); Textview.settext (content);//Textview.setsingleline (); Textview.settextcolor (TextColor); int leftMargin = Containervg.getright ()-Containervg.getleft ()-Containervg.getpaddingleft (); Calculates the topmargin (random value, but not the one already in the screen) int verticalmargin = Getrandomtopmargin () of the bullet screen; Textview.settag (VerticalMargin); Layoutparams params = new Layoutparams (layoutparams.wrap_content, layoutparams.wrap_content); Params.addrule (Relativelayout.align_parent_top); Params.topmargin = VerticalMargin; Textview.setlayoutparams (params); Animation Anim = Animationhelper.createtranslateanim (this, LeftMargin,-screenutils.getscreenw (this)); Anim.setanimationlistener (New Animation.animationlistener () {@Override public void Onanimationstart (Animation Animation) {} @Override public void Onanimationend (Animation Animation) {//Remove the component Containervg.removeview (TextView); Remove the placeholder int verticalmargin = (int) textview.gettag ();Existmarginvalues.remove (VerticalMargin); } @Override public void Onanimationrepeat (Animation Animation) {}}); Textview.startanimation (ANIM); Containervg.addview (TextView); }//Record the position of the barrage that is still showing state (avoid repeating) private set<integer> existmarginvalues = new hashset<> (); private int linescount; private int Getrandomtopmargin () {//calculates the space height to be used for the barrage display if (Validheightspace = = 0) {Validheightspace = Containervg.getbottom ()-Containervg.gettop ()-Containervg.getpaddingtop ()-containervg.getpadding Bottom (); }//Calculates the number of available rows if (Linescount = = 0) {Linescount = validheightspace/screenutils.dp2px (This, tanmub Ean.getmintextsize () * (1 + tanmubean.getrange ())); if (Linescount = = 0) {throw new RuntimeException ("Not enough space to show text."); }}//check overlap while (true) {int RandoMindex = (int) (Math.random () * linescount); int marginvalue = Randomindex * (validheightspace/linescount); if (!existmarginvalues.contains (Marginvalue)) {Existmarginvalues.add (marginvalue); return marginvalue; } } }}

2. Pan The animation Generation tool:

public class Animationhelper {    /**     * Creates a translation animation *    /public static Animation Createtranslateanim (Context context, int fromX, int toX) {        translateanimation Tlanim = new Translateanimation (FromX, ToX, 0, 0);        Take the initiative to calculate the time        long Duration = (long) (Math.Abs (TOX-FROMX) * 1.0F/SCREENUTILS.GETSCREENW (context) * 4000);        Tlanim.setduration (duration);        Tlanim.setinterpolator (New Decelerateaccelerateinterpolator ());        Tlanim.setfillafter (true);        return Tlanim;}    }
The Screenutils is the tool class used to get the screen width high, the DP and PX.

3. Self-defined interpolator. In fact there's just one line of code

The public class Decelerateaccelerateinterpolator implements Interpolator {    //input from 0~1, and the return value is also from 0~1. Curve characterization of return values speed plus minus trend    @Override public    float getinterpolation (float input) {        return (float) (Math.tan (Input * 2-1)/4 * Math.PI )/2.0f + 0.5f;}    }
4.TanmuBean is an entity class

public class Tanmubean {    private string[] items;    private int color;    private int mintextsize;    private float range;    Public Tanmubean () {        //init default value        color = Color.parsecolor ("#eeeeee");        Mintextsize = +;        range = 0.5f;    }    Public string[] GetItems () {        return items;    }    public void Setitems (string[] items) {        this.items = items;    }    public int GetColor () {        return color;    }    public void SetColor (int color) {        This.color = color;    }    /**     * min textSize, in DP.     *    /public int getmintextsize () {        return mintextsize;    }    public void setmintextsize (int mintextsize) {        this.mintextsize = mintextsize;    }    public float GetRange () {        return range;    }    public void SetRange (float range) {        this.range = range;    }}

==========

Source code Download: http://download.csdn.net/detail/books1958/9005279






Copyright notice: This article Bo Master original articles, blogs, without consent may not be reproduced.

Android: Simple bullet screen effect achieved

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.