Android teaches you to create cool bullet-screen effects

Source: Internet
Author: User

The company's new product on-line needs to add the barrage function, so spent a day to write a demo.

The effect is achieved as follows:

The first idea was:

1, the first implementation of a custom layout, in which to obtain the need to display an array of bullets, each of the array of bullet-screen items including the bullet screen text and image URL address.

2. Use handler or timed thread to circulate the barrage inside layout.

3, the missile screen implementation of the use of custom bullet screen view, with the animation to achieve the roll screen rendering.

After summing up the main difficulty is the selection of the appearance of the screen and how to ensure the timely destruction of the bomb screen (I would say that the first time the commissioning of the full screen of the scene of the gorgeous scenes?). ), and how to reuse components and maximize performance. Also pay attention to some functional points that need to be implemented: obtaining pictures via URLs (which can be implemented and replaced by the picture cache loading framework), and preventing pop-up stacking (this algorithm is easier to implement).

Later found to write a custom pop-up view (the left side of a circle avatar on the right, the outer border oval background transparent) a little trouble, so the use of the ListView item reuse ideas, using an item layout easy to achieve spicy ~

Fortunately, recently has been writing the company's new project interface, a variety of skills to use more skilled, the script screen demo of the whole process did not encounter any pressure, but finally forgot to add network permissions led to debugging a half-day ... (crying).

Implementation steps:

1. Implement the main layout:

The position of the projectile area can be adjusted on its own, in theory it can be placed in any position on the screen.

Barrageview_test.xml

<?xml version= "1.0" encoding= "Utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk/res/ Android "              android:orientation=" vertical "              android:layout_width=" match_parent "              android:layout_height= "Match_parent" >    <com.whale.nangua.toquan.view.barrageview        android:id= "@+id/barrageview"        android:background= "@drawable/testbackground"        android:layout_centerhorizontal= "true"        android:layout_ Centervertical= "true"        android:layout_width= "match_parent"        android:layout_height= "200DP"/></ Relativelayout>

2, the implementation of the bullet screen item layout:

The use of a custom circle class to achieve the effect of a round head, a search on the internet a lot of or comment message here does not fill the source space.

Barrageview_item.xml

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/              Android "android:orientation=" horizontal "android:background=" @drawable/barrage_shape " Android:layout_width= "Wrap_content" android:layout_height= "50DP" > <com.whale.nangua.toquan.view. Ngnormalcircleimageview android:src= "@drawable/pumpkin" android:id= "@+id/barrageview_item_img" Androi D:layout_width= "50DP" android:layout_height= "match_parent"/> <textview android:maxems= "Ten" a        Ndroid:textcolor= "@android: Color/white" android:layout_marginleft= "10DP" android:layout_marginright= "10DP" android:gravity= "center" android:text= "Test Barrage" android:singleline= "true" android:id= "@+id/barrage View_item_tv "android:layout_width=" wrap_content "android:layout_height=" Match_parent "/></LinearLayout >
3, the implementation of testing activity

Package Com.whale.nangua.toquan;import Android.app.activity;import Android.os.bundle;import android.util.Log; Import Com.whale.nangua.toquan.bean.barrage;import Com.whale.nangua.toquan.view.barrageview;import java.util.arraylist;/** * Created by Nangua on 2016/7/18.    */public class Testaty extends Activity {Barrageview barrageview;    Arraylist<barrage> date;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (r.layout.barrageview_test);    Initview ();        } private void Initview () {date = new arraylist<> (); for (int i = 0; i < i++) {Date.add (New barrage ("test barrage" + I, "http://pic.818today.co        M/imgsy/image/2016/0215/6359114592207963687677523.jpg "));        } Barrageview = (Barrageview) Findviewbyid (R.id.barrageview);        LOG.D ("Xiaojingyu", date.size () + "");    Barrageview.setsentencelist (date); }}

4, Bomb screen class Barrageview.java

Package Com.whale.nangua.toquan.view;import Android.animation.animator;import Android.animation.ObjectAnimator; Import Android.content.context;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.graphics.canvas;import Android.os.bundle;import Android.os.handler;import Android.os.Message;import Android.util.attributeset;import Android.util.log;import Android.view.layoutinflater;import Android.widget.framelayout;import Android.widget.linearlayout;import Android.widget.textview;import Com.whale.nangua.toquan.r;import Com.whale.nangua.toquan.bean.barrage;import Java.io.InputStream;import Java.net.httpurlconnection;import Java.net.url;import java.util.arraylist;/** * 2 seconds One * 5 on screen * Created by Nangua on 20 16/7/28. */public class Barrageview extends Framelayout {private static arraylist<barrage> date = new Arraylist<> () ; Data private int nowindex = 0; The subscript of date is private Bitmap nowbitmap;    Current picture int width;  control width int height; ControlHigh float scale;    Pixel density framelayout framelayout;    Framelayout.layoutparams Tvparams;    static Boolean Is_start = false; Determine whether to start long alltime; Total video length long starttime;    Start time//LinearLayout layout; Handler Handler = new Handler () {@Override public void Handlemessage (Message msg) {barrage Barr            Age = (barrage) Msg.getdata (). Getserializable ("barrage"); Final LinearLayout layout = (linearlayout) layoutinflater.from (GetContext ()). Inflate (R.layout.barrageview_item, NULL            );            Layout.setlayoutparams (Tvparams);            Randomly obtained Y value layout.sety (getramdomy ());            Layout.setx (width + layout.getwidth ());            Set text TextView TextView = (TextView) Layout.findviewbyid (R.ID.BARRAGEVIEW_ITEM_TV);            Textview.settext (Barrage.getbarrageinfo ()); Set Picture Ngnormalcircleimageview Ngnormalcircleimageview = (ngnormalcircleimageview) Layout.findviewbyid (R.id.bar Rageview_item_iMG);            if (nowbitmap! = null) {Ngnormalcircleimageview.setimagebitmap (NOWBITMAP);            } framelayout.addview (layout);            Final Objectanimator anim = objectanimator.offloat (Layout, "Translationx",-width);            Anim.setduration (10000); Release Resource Anim.addlistener (new Animator.animatorlistener () {@Override public void O Nanimationstart (Animator animation) {} @Override public void Onanimationend (                    Animator animation) {anim.cancel ();                    Layout.clearanimation ();                Framelayout.removeview (layout);                } @Override public void Onanimationcancel (Animator animation) {}            @Override public void Onanimationrepeat (Animator animation) {}});        Anim.start ();    }    }; /**     *Use Httprulconnection to send a network request path to get BITMAP * @param path * @return * */public static Bitmap Getbitmapfromurl (St            Ring path) {try {//get URL url url = new URL (path);            Open Httprulconnection Get instance httpurlconnection conn = (httpurlconnection) url.openconnection ();            Set timeout time conn.setconnecttimeout (5000);            Set get Conn.setrequestmethod ("get"); Successful connection if (conn.getresponsecode () = = 200) {//Get input stream inputstream InputStream = con                N.getinputstream ();                Get Bitmap Bitmap Bitmap = Bitmapfactory.decodestream (InputStream);            if (bitmap = = null) {}//returns return bitmap;        }//Error information Processing} catch (Exception e) {//Print error message e.printstacktrace ();    } return null;    } int lasty;//The last occurrence of the Y-value/** * Gets the value of the random y-axis * * @return */private float getramdomy () {int tempy;        int RY;        int result = 0;        Height * 2/4-25//First randomly select a road int nowy = (int) (Math.random () * 3);                Switch (Nowy) {Case 0:nowy = Avoidthesamey (nowy,lasty);                The first tempy = HEIGHT/4-25;                RY = (int) (Math.random () * HEIGHT/4);                if (RY >= height/8) {result = Tempy + RY;                } else {result = Tempy-ry + 50;                } lasty = Nowy;            Break                Case 1:nowy = Avoidthesamey (nowy,lasty);                The second tempy = HEIGHT/2-25;                RY = (int) (Math.random () * HEIGHT/4);                if (RY >= height/8) {result = Tempy + RY;                } else {result = Tempy-ry; } lasty =Nowy;            Break                Case 2:nowy = Avoidthesamey (nowy,lasty);                Third Tempy = height * 3/4-25;                RY = (int) (Math.random () * HEIGHT/4);                if (RY >= height/8) {result = Tempy + rY-50;                } else {result = Tempy-ry;                } lasty = Nowy;        Break    } return result;        }/** * Avoid y coincident method * @param lasty * @return */private int Avoidthesamey (int nowy,int lasty) {        if (nowy = = lasty) {nowy + +;        } if (Nowy = = 4) {nowy = 0;    } return Nowy;    } public Barrageview (context context, AttributeSet Attrs) {Super (context, attrs); } @Override protected void OnLayout (Boolean changed, int left, int top, int. right, int bottom) {Super.onlayo        UT (changed, left, top, right, bottom); width = getwidth ();   Width height = getheight ();    Height init ();    } private void Init () {settime (600000);        Set the initial length, and then remember to delete starttime = System.currenttimemillis ();        Scale = This.getresources (). Getdisplaymetrics (). density;        Obtain Self Instance framelayout = (framelayout) Findviewbyid (R.id.barrageview);        Tvparams = new Framelayout.layoutparams (FrameLayout.LayoutParams.WRAP_CONTENT, 50);            if (Is_start) {//Start animation thread Startbarrageview ();        Is_start = false; }} public void Startbarrageview () {//Open thread to send bullet screen new thread () {@Override public  void Run () {while ((System.currenttimemillis ()-StartTime < Alltime) && (Nowindex <= date.size ()-1))                        {try {nowbitmap = Getbitmapfromurl (Date.get (Nowindex). Getbarrageurl ());  Message message = new Message ();                      Bundle bundle = new bundle ();                        Bundle.putserializable ("Barrage", Date.get (Nowindex));                        Nowindex + +;                        Message.setdata (bundle);                        Handler.sendmessage (message);                    Thread.Sleep ((Long) (Math.random () * 3000) + 1000);                    } catch (Interruptedexception e) {e.printstacktrace ();            }} return;    }}.start ();    } @Override protected void OnDraw (canvas canvas) {super.ondraw (canvas);        }//Set data public void Setsentencelist (arraylist<barrage> date1) {date = Date1;    Is_start = true;    }//Get video total duration public void settime (long) {alltime = time; }}
The implementation of the idea is probably the same as the beginning of the description, but this is still a relatively rudimentary prototype, there are a large number of modular function points to expand,

such as the length of the video can be set, the speed of the barrage , the screen font color, the arrangement of bullets and so on can be customized,

Code comments Detailed thinking clear, do not know how to comment @ me.

But tomorrow has to work, the day after tomorrow's holiday, good night ~



Android teaches you to create cool bullet-screen effects

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.