Android: simple bullet screen effect implementation, android bullet Screen

Source: Internet
Author: User
Tags float range getcolor

Android: simple bullet screen effect implementation, android bullet Screen

First, it is similar to the page where 360 detects harassing calls:


The layout is very simple. The above is a RelativeLayout, and the following Button.

Function:

(1) After the bullet screen is generated, it will automatically scroll from the right side to the left side (TranslateAnimation). The bullet screen will be removed immediately after it disappears.

(2) The Bullet screens appear randomly and are not repeated (preventing text overlapping ).

(3) The font size is changed randomly within a certain range, and the font color can also be set.

(4) the User-Defined Interpolator that first slows down and then accelerates the entry, stop, and then accelerates the exit of the bullet screen.

1. Activity Code:

/*** Simple bullet screen effect ** Created by admin on 15-6-4. */public class MainActivity extends ActionBarActivity {private MyHandler handler; // the pop-up content private TanmuBean tanmuBean; // The parent component private RelativeLayout containerVG that contains the pop-up content; // The height of the parent component is private int validHeightSpace; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); containerV G = (RelativeLayout) findViewById (R. id. tanmu_container); tanmuBean = new TanmuBean (); tanmuBean. setItems (new String [] {"test", "Bullet screen is really hard to do", "There are always various problems ~~ "," I don't know why? Trouble! "," Which of the following experts can help me? "," I need your help. "," test "," Bullet screen is really hard to do. "," There are always various problems ~~ "," I don't know why? Trouble! "," Which of the following experts can help me? "," I need your help. "," test "," Bullet screen is really hard to do. "," There are always various problems ~~ "," I don't know why? Trouble! "," Which of the following experts can help me? "," I need your help. "}); handler = new MyHandler (this); // start the bullet screen 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 () ;}}) ;}// automatically add a bullet screen private class CreateTanmuThread implem every 2 seconds Ents 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) ;}}// you need to add the private static class MyHandler extends Handler {private WeakReference <MainActivity> ref; MyHandler (MainActivity ac) component to the main city) {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 TextView textView = new TextView (this); tex TView. setTextSize (textSize); textView. setText (content); // textView. setSingleLine (); textView. setTextColor (textColor); int leftMargin = containerVG. getRight ()-containerVG. getLeft ()-containerVG. getPaddingLeft (); // calculate the topMargin (random value, but not repeated with the existing one in the screen) int verticalMargin = getRandomTopMargin (); textView. setTag (verticalMargin); LayoutParams params = new LayoutParams (LayoutParams. WRAP_CONTENT, LayoutP Arams. 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 onAnimatio NEnd (Animation animation) {// remove the containerVG component. 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 bullet screen that is currently in the display status (avoid duplication) private Set <Integer> existMarginValues = new HashSet <> (); private int lines Count; private int getRandomTopMargin () {// calculate the space height of the bullet screen display if (validHeightSpace = 0) {validHeightSpace = containerVG. getBottom ()-containerVG. getTop ()-containerVG. getPaddingTop ()-containerVG. getPaddingBottom ();} // calculate the number of available rows if (linesCount = 0) {linesCount = validHeightSpace/ScreenUtils. dp2px (this, tanmuBean. getMinTextSize () * (1 + tanmuBean. getRange (); if (linesCount = 0) {throw new R UntimeException ("Not enough space to show text. ") ;}}// check the overlapping while (true) {int randomIndex = (int) (Math. random () * linesCount); int marginValue = randomIndex * (validHeightSpace/linesCount); if (! ExistMarginValues. contains (marginValue) {existMarginValues. add (marginValue); return marginValue ;}}}}
2. Translation Animation Generation Tool:

Public class AnimationHelper {/*** create a translation Animation */public static Animation createTranslateAnim (Context context, int fromX, int toX) {TranslateAnimation tlAnim = new TranslateAnimation (fromX, toX, 0, 0); // Automatic calculation 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 ;}}
ScreenUtils is a tool class used to obtain screen width and height, and convert between dp and px.

3. The custom Interpolator has only one line of code.

Public class DecelerateAccelerateInterpolator implements Interpolator {// The input value ranges from 0 ~ 1. the return value also ranges from 0 ~ 1. the returned value curve represents the trend of speed addition and subtraction @ 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 = 16;        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;    }}







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.