Android Custom view article data scrolling display values

Source: Internet
Author: User

本文已经在公众号【Android群英传】独家发表。

This article GitHub code links
Https://github.com/AndroidMsky/RandomTextView

First look at the effect of the X-gold app:

Our own implementation of the effect:

Next, let's introduce the usage and principles of my custom view Randomtextview

Usage

Test entry

Randomtextview.java

Only 200 lines are absolutely lightweight and convenient.

The XML defines:

<com  .example  .liangmutian  .randomtextview  .view   android:id= "@+id/rtv"  Android:layout_width= "wrap_content"  android:layout_height= "wrap_content"  Android:layout_centerhorizontal= "true"  Android:layout_centervertical= "true"  android:padding= "0px"  Android:text= "123456"  android:textsize= "28SP" />  

Very happy thing, Randomtextview inherited from TextView so you can use all the methods of TextView. Color,size and so on directly to define just OK.

Scroll all digits at the same speed:

mRandomTextView.setText("876543");mRandomTextView.setPianyilian(RandomTextView.ALL);mRandomTextView.start();

From left to right from fast to slow scrolling:

mRandomTextView.setText("12313288");mRandomTextView.setPianyilian(RandomTextView.FIRSTF_FIRST);mRandomTextView.start();

From left to right from slow to fast scrolling:

mRandomTextView.setText("9078111123");mRandomTextView.setPianyilian(RandomTextView.FIRSTF_LAST);mRandomTextView.start();

Customize the speed scrolling per digit (the pixels scrolled per frame):

Mrandomtextview. SetText("909878");pianyiliang[0] =7;pianyiliang[1] =6;pianyiliang[2] = A;pianyiliang[3] =8;pianyiliang[4] = -;pianyiliang[5] =Ten;Mrandomtextview. Setpianyilian(Pianyiliang);Mrandomtextview. Start();

Custom scrolling lines (default 10 rows):

mRandomTextView.setMaxLine(20);
Principle

Using TextView to draw ten (Maxline can be set) line text, call Canvas.drawtext to draw out, in the drawing of the Y coordinate constantly increase the amount of cheap, to change the height of the drawing, through the handler.postdelayed (this, 20); To keep increasing the offset, and to constantly judge all digits when the last line is drawn, end the handler loop call.

Required variables:

//high-speed     Public Static Final intFirstf_first =0;//high-slow     Public Static Final intFirstf_last =1;//Speed same     Public Static Final intall =2;//user-defined speed     Public Static Final intUSER =3;//Offset speed type    Private intPianyiliangtpye;//Rolling total number of rows can be set    Private intMaxLine =Ten;//Current string length    Private intNumlength =0;//Current text    PrivateString text;//scroll speed array    Private int[] pianyilianglist;//Total scrolling distance array    Private int[] pianyiliangsum;//scrolling complete judgment    Private int[] overline;PrivatePaint p;//First time drawing    Private BooleanFirstin =true;//Scroll in    Private BooleanAuto =true;//text int Value List    PrivateArraylist<integer> Arraylisttext;//font width    Private floatF0;//Baseline    Private intBaseline

OnDraw method:

@Override    protected void OnDraw(Canvas canvas) {if(Firstin) {Firstin =false;Super. OnDraw (canvas);            p = getpaint ();            Paint.fontmetricsint FontMetrics = P.getfontmetricsint (); Baseline = (Getmeasuredheight ()-Fontmetrics.bottom + fontmetrics.top)/2-Fontmetrics.top;float[] widths =New float[4]; P.gettextwidths ("9999", widths); F0 = widths[0];        Invalidate (); } drawnumber (canvas);

The first time you enter the OnDraw method, there are a few things to do:
1. go to get the current correct brush p = getpaint (), so that the size and color configured in the XML are valid.
2. use the current brush to calculate the correct DrawText baseline.
Baseline = (Getmeasuredheight ()-Fontmetrics.bottom + fontmetrics.top)/2-fontmetrics.top;
3. wait until the width of the number. Easy to draw horizontally.
P.gettextwidths ("9999", widths); F0 = Widths[0];
4. directly notify view redraw.
Invalidate ();

Our own method of drawing Drawnumber:

Private void Drawnumber(Canvas canvas) { for(intj =0; J < Numlength; J + +) { for(inti =1; i < MaxLine; i++) {if(i = = MaxLine-1&& i * baseline + pianyiliangsum[j] <= baseline) {Pianyilianglist[j] =0; OVERLINE[J] =1;intAuto =0; for(intK =0; K < Numlength;                    k++) {auto + = Overline[k]; }if(Auto = = Numlength *2-1) { This. Auto =false;                        Handler.removecallbacks (Task);                    Invalidate (); }                }if(Overline[j] = =0) Canvas.drawtext (Setback (Arraylisttext.Get(j), Maxline-i-1) +"",0+ F0 * J, I * baseline + pianyiliangsum[j], p);Else{//position and draw once.                    if(Overline[j] = =1) {overline[j]++; Canvas.drawtext (Arraylisttext.Get(j) +"",0+ F0 * j, Baseline, p); }//break;}}            }}

The logic here is to achieve O (number of rows * strings) for complex time complexity, which is a double-loop drawing.
The first layer we call the J Loop, and the content of each loop of J loops is to draw a column.
The second loop is called the I loop, and the I loop is responsible for drawing each character of each line.

Each time I loop in the first thing is to check the current character bit, is not the last

if (i1i * baseline + pianyiliangSum[j] <= baseline)

If yes, then zero low, modify flag bit

pianyilianglist[j] = 0;overLine[j] = 1;

Then go to the end of the sentence. All character bits are drawn to the last:

intauto0;for (int0; k < numLength; k++) {auto += overLine[k];}if (auto21) {this.autofalse;handler.removeCallbacks(task);invalidate();}

If so, the method of automatic cyclic refresh is canceled, and the view is notified to make the last location drawing.
The above is to enter I cycle first to whether to draw the end of the judgment.

If there is no end then continue drawing:

if0)                    canvas.drawText(setBack(arrayListText.get1""0 + f0 * j,i * baseline +pianyiliangSum[j], p);else {if1) {//定位后画一次就好啦overLine[j]++;canvas.drawText(arrayListText.get""0 + f0 * j,baseline, p);}                }

The value in Overline[j] means: 0 indicates that the last row has not been drawn, 1 means that the last row is not drawn for drawing to the last line, and 2 indicates that the location is drawn.

Perhaps the most difficult for beginners is the DrawText coordinate problem, the x-coordinate is relatively simple
Is the width of the character and changes with the loop:

0j

The y-coordinate is the current line's base value + the current cheap amount:

ibaseline + pianyiliangSum[j]

Every 20 milliseconds to calculate the current low volume and notify Refresh view:

privatefinalnew Runnable() {        publicvoidrun() {            // TODO Auto-generated method stub            if (auto) {                handler.postDelayed(this20);                for (int0; j < numLength; j++) {                    pianyiliangSum[j] -= pianyilianglist[j];                }                invalidate();            }        }    };

Help calculates 9 above is a few. 8 above is a few

//设置上方数字0-9递减    privateintsetBack(intint back) {        if0return c;        10;        int re = c - back;        if010;        return re;    }

To convert a string to an int array:

 PrivateArrayList<Integer>GetList (Strings) {ArrayList<Integer>ArrayList= NewArrayList<Integer>(); for (int i= 0; I<S.Length (); I++) {StringSs=S.SUBSTRING (i, I+ 1); int a= Integer.parseint (ss); ArrayList.Add (a); }returnArrayList; }
Review

In custom view, if your view is like this article, loop to draw constantly refresh, it means that the OnDraw method will be called with your view frame number of times, a second may be executed dozens of time, so write here method, must be careful for the wonderful, For example, some variables do not need to be initialized every time to remember that can not be defined in the OnDraw method, such as the GetText () of this article, method to get the current TextView content, it will be written on the outside. But there may be some way you have to Super.ondraw (canvas), then you can get the Getpaint (), then we can add a Boolean value Firstin to control only the first time to enter the OnDraw method to execute, Or anything else that can only be done once is controlled in this way.

Looping animation effects We must clear two lines, one is what each frame draws, the other is the end of the animation you have drawn what.

The first line should be aware that you are drawing just an instant, a line that repeats itself.

The second line is the countless first lines plus time points together, mainly control each time the difference, such as the increase in the offset in this article, is the data (the coordinates of each character in this article) changes, to affect the OnDraw method, drawing out of the object rendered on the screen. The second line also controls when the end of all the first line, that is the condition of the end of the whole animation, the example in this article is that once all the last line of characters is more than or equal to the textview of the baseline, then the entire animation ends.

The logic of drawing principle is finished, Randomtextview can be put into use, custom view is not difficult, as long as you know the Android API can let you do what you want to do, you may immediately know what you should do.

Please pay attention to the author. Comments and discussions are welcome. Welcome to shoot Bricks.

If you feel that this article is helpful to you, welcome to the prize,

Welcome to star,fork my GitHub.

Like the author can also be follow. is also a kind of support for the author.
This article GitHub code links
Https://github.com/AndroidMsky/RandomTextView

Welcome to add the author of the self-development of the Android Exchange Group: 308372687

Bo Master original without permission to reprint.

Android Custom view article data scrolling display values

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.