Android custom controls Play turn font color create cool Viewpager indicator

Source: Internet
Author: User
Tags drawtext

Reprint please indicate the source: http://blog.csdn.net/lmj623565791/article/details/44098729, this article from: "Zhang Hongyang Blog" 1, overview

The creation of this blog, is because, the group of friends to send me a warm, and then asked me how to achieve the top of the Viewpager indicator font discoloration, this is:


Probably the app of the headlines today, the magical place is that when switching Viewpager page, the top indicator changed to the font color changes, personally feel good.

So the core of the place is to do a support font so gradually dyeing can be, I probably think of 32s, scanned some possible implementation of the scheme, the final positioning of a reliable, the following I will bring you to realize the journey.

Implementation before pasting our:

2, 1, easy to use


Effect as, about the change of color I added two directions, one is the left direction, the other is a direction.

Simple to use, may feel no meaning, see below a combination of viewpager use an example.

2, combined with Viewpager use


You can see the effect of the above indicator when we switch the page, the bar ~ ~ ~

Of course, learned the principle, you can expand, you can do the personality of the progress bar, you can change the font color to the background color change, you can change the direction to the top and bottom, too much, their own to pull the foot.

3. Principle

Read, there is no idea of wood ~ ~ ~ Spend a few minutes to think, because the principle is very simple ~ ~

I think about the next, visually draw half a word estimate no, then on the drawing range of effort, you can draw all, but I control the display of the range, so the above effect:

In fact, it is drawn two times the font, but, respectively, control the display range of the drawing, to achieve the effect of gradual discoloration, then for the scope of control, what is the convenient API, obviously there is

Canvas has a Cliprect method ~~~ok, the principle analysis is complete ~ ~

4. Realize

When it comes to implementation, the first step is definitely a custom attribute, we have the properties here, need to text,textsize,textorigincolor,textchangecolor,progress, a general look, should be able to see the role of it, do not see it okay, Combine the following code. Tip: Our view is called Colortrackview, thanks to the name of Little seven.

1. Custom Attributes and get

Attr.xml

<?xml version= "1.0" encoding= "Utf-8"?><resources>    <attr name= "text" format= "string"/>    <attr name= "Text_size" format= "Dimension"/>    <attr name= "Text_origin_color" format= "color|reference"/ >    <attr name= "Text_change_color" format= "color|reference"/>    <attr name= "Progress" format= " Float "/>    <attr name=" direction ">        <enum name=" left "value=" 0 "/>        <enum name=" right " value= "1"/>    </attr>    <declare-styleable name= "Colortrackview" >        <attr name= "text"/ >        <attr name= "text_size"/>        <attr name= "Text_origin_color"/> <attr        name= "Text_ Change_color "/>        <attr name=" Progress "/> <attr name=        " direction "/>    </ Declare-styleable></resources>

These slag properties are then obtained in the construction method of our Colortrackview:

/** * * @author Zhy * */public class Colortrackview extends view{private int mtextstartx;public enum Direction{left, RIG HT;} private int mdirection = Direction_left; private static final int direction_left = 0; private static final int direction_right= 1;p ublic void setdirection (int DIRECTION) {mdirection = DIRECTION;} Private String MText = "Zhang Hongyang";p rivate Paint mpaint;private int mtextsize = sp2px (+);p rivate int mtextorigincolor = 0xff000 000;private int mtextchangecolor = 0xffff0000;private rect mtextbound = new Rect ();p rivate int mtextwidth;private int MRea lwidth;private Float Mprogress;public Colortrackview (context context) {Super (context, NULL);} Public Colortrackview (context context, AttributeSet Attrs) {Super (context, attrs); mpaint = new Paint (paint.anti_alias_ FLAG); TypedArray ta = context.obtainstyledattributes (attrs,r.styleable.colortrackview); mText = Ta.getstring ( R.styleable.colortrackview_text); mtextsize = Ta.getdimensionpixelsize (R.styleable.colortrackview_text_size, Mtextsize); Mtextorigincolor = Ta.getcolor (R.styleable.colortrackview_text_origin_color,mtextorigincolor); Mtextchangecolor = Ta.getcolor (r.styleable.colortrackview_text_change_color,mtextchangecolor); mProgress = Ta.getfloat (r.styleable.colortrackview_progress, 0); mdirection = Ta.getint (R.styleable.colortrackview_direction, mdirection); ta.recycle (); mpaint.settextsize (mtextsize); Measuretext ();}

private void Measuretext () {mtextwidth = (int) mpaint.measuretext (mText); Mpaint.gettextbounds (mText, 0, Mtext.length () , mtextbound);}

You can see that I posted a member variable at the same time, we simply look down on the line, are relatively simple.

Gets the property, initializes the completion of some member variables, then should go to our measure Tour ~ ~

2, Onmeasure

@Overrideprotected void onmeasure (int widthmeasurespec, int heightmeasurespec) {int width = measurewidth ( WIDTHMEASURESPEC); int height = measureheight (heightmeasurespec); setmeasureddimension (width, height); mrealwidth = Getmeasuredwidth ()-Getpaddingleft ()-getpaddingright (); mtextstartx = Mrealwidth/2-MTEXTWIDTH/2;} private int measureheight (int measurespec) {int mode = Measurespec.getmode (measurespec); int val = Measurespec.getsize ( MEASURESPEC); int result = 0;switch (mode) {case MeasureSpec.EXACTLY:result = val;break;case MeasureSpec.AT_MOST:case MeasureSpec.UNSPECIFIED:result = Mtextbound.height (); break;} result = Mode = = Measurespec.at_most? Math.min (Result, Val): Result;return result + getpaddingtop () + Getpaddingbottom ();} private int measurewidth (int measurespec) {int mode = Measurespec.getmode (measurespec); int val = Measurespec.getsize ( MEASURESPEC); int result = 0;switch (mode) {case MeasureSpec.EXACTLY:result = val;break;case MeasureSpec.AT_MOST:case measurespec.unspecified://RESult = Mtextbound.width (); result = Mtextwidth;break;} result = Mode = = Measurespec.at_most? Math.min (Result, Val): Result;return result + getpaddingleft () + Getpaddingright ();}

About the measurement, is also a more traditional way of writing, according to the incoming Widthmeasurespec, heightmeasurespec, using Measurespec respectively to obtain the mode and value, how is exactly everything, if it is at_most, Unspecified then it's up to you to measure the space you need, and of course, it's best to note that At_most should not be greater than the parent class's incoming value.

Mention here, if lazy, you can choose to inherit TextView, and then the measurement will not need to write, textview default to help you achieve, but also to take advantage of some of the TextView properties, but we are relatively simple example, I finally chose to inherit the view, Inherit view a everything under control feeling.

After the measurement is complete, it goes without saying that it is drawn.

3, OnDraw

@Overrideprotected void OnDraw (canvas canvas) {super.ondraw (canvas); int r = (int) (mprogress* mtextwidth +mtextstartx); if (mdirection = = Direction_left) {drawchangeleft (canvas, R);d raworiginleft (canvas, R);} else{draworiginright (canvas, R); Drawchangeright (canvas, R);}} private void Drawchangeright (canvas canvas, int r) {drawText (canvas, Mtextchangecolor, (int) (Mtextstartx + (1-mprogress) *mtextwidth), mtextstartx+mtextwidth);} private void Draworiginright (canvas canvas, int r) {drawText (canvas, Mtextorigincolor, MTEXTSTARTX, (int) (Mtextstartx + ( 1-mprogress) (*mtextwidth));} private void Drawchangeleft (canvas canvas, int r) {drawText (canvas, Mtextchangecolor, MTEXTSTARTX, (int) (MTEXTSTARTX + MP) Rogress * mtextwidth));} private void Draworiginleft (canvas canvas, int r) {drawText (canvas, Mtextorigincolor, (int) (MTEXTSTARTX + mprogress * Mtex Twidth), Mtextstartx +mtextwidth);} private void DrawText (canvas canvas, int color, int startX, int endx) {mpaint.setcolor (color); Canvas.save (canvas.clip_sAve_flag); Canvas.cliprect (StartX, 0, EndX, Getmeasuredheight ()); Canvas.drawtext (MText, Mtextstartx, Getmeasuredheight ()/Mtextbound.height ()/2, mpaint); Canvas.restore ();

The core of the drawing is to use mprogress and direction to calculate the scope of the clip, the specific reference code, no difficulty. After the range, nothing is drawtext~~~.

The full code for the view: Colortrackview

The main method is complete, we should test it.

5. Testing
1. Simple test

Layout file

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "xmlns:zhy=" Http://schemas.android.com/apk/res-auto "android:layout_width=" Match_ Parent "android:layout_height=" match_parent "> <com.zhy.view.colortrackview android:id=" @+id/id_changeT Extcolorview "android:layout_width=" match_parent "android:layout_height=" Wrap_content "android:layout        _centerinparent= "true" android:background= "#44ff0000" android:padding= "10DP" zhy:progress= "0" zhy:text= "Zhang Hongyang" zhy:text_change_color= "#ffff0000" zhy:text_origin_color= "#ff000000" zhy:text_size= "60s        P "/> <linearlayout android:layout_width=" match_parent "android:layout_height=" Wrap_content "        Android:layout_alignparentbottom= "true" android:gravity= "center" android:orientation= "Horizontal" >    <button android:id= "@+id/id_left"        Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:onclick= "St            Artleftchange "android:text=" Startleft "/> <button android:layout_width=" Wrap_content " android:layout_height= "Wrap_content" android:layout_torightof= "@id/id_left" android:oncli ck= "Startrightchange" android:text= "Startright"/> </LinearLayout></RelativeLayout>

Note the namespace of our custom attribute, the layout is a colortrackview, and then two buttons to control the progress.

Simpleuseactivity:

Package Com.zhy.viewpagerindicator;import Android.animation.objectanimator;import Android.annotation.SuppressLint ; Import Android.app.activity;import android.os.bundle;import android.view.view;import Com.zhy.view.ColorTrackView; public class Simpleuseactivity extends Activity{colortrackview mView; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_simple_main); MView = ( Colortrackview) Findviewbyid (R.id.id_changetextcolorview);} @SuppressLint ("Newapi") public void Startleftchange (view view) {mview.setdirection (0); Objectanimator.offloat (MView, "Progress", 0, 1). Setduration (+). Start (); @SuppressLint ("Newapi") public void Startrightchange (view view) {mview.setdirection (1); Objectanimator.offloat (MView , "Progress", 0, 1). Setduration (). Start ();}}

Here take the property animation test, do not import the following 3.0 compatibility package, there is a need to import themselves.

, see above 1.

2, combined with Viewpager

Layout file:

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:zhy= "http// Schemas.android.com/apk/res-auto "xmlns:tools=" Http://schemas.android.com/tools "android:layout_width=" Match_ Parent "android:layout_height=" match_parent "android:orientation=" vertical "> <linearlayout android: Layout_width= "Match_parent" android:layout_height= "50DP" android:orientation= "Horizontal" > <co M.zhy.view.colortrackview android:id= "@+id/id_tab_01" android:layout_width= "0DP" Android:            layout_height= "Match_parent" android:layout_weight= "1" zhy:progress= "1" zhy:text= "Introduction" Zhy:text_change_color= "#ffff0000" zhy:text_origin_color= "#ff000000" zhy:text_size= "18SP"/&G        T <com.zhy.view.colortrackview android:id= "@+id/id_tab_02" android:layout_width= "0DP" an            droid:layout_height= "Match_parent"android:layout_weight= "1" zhy:text= "Evaluation" zhy:text_change_color= "#ffff0000" Zhy:text_origin _color= "#ff000000" zhy:text_size= "18sp"/> <com.zhy.view.colortrackview android:id= "@+i D/id_tab_03 "android:layout_width=" 0DP "android:layout_height=" Match_parent "Android:layo ut_weight= "1" zhy:text= "related" zhy:text_change_color= "#ffff0000" zhy:text_origin_color= "#ff0        00000 "zhy:text_size=" 18sp "/> </LinearLayout> <android.support.v4.view.viewpager Android:id= "@+id/id_viewpager" android:layout_width= "match_parent" android:layout_height= "0DP" an droid:layout_weight= "1" > </android.support.v4.view.ViewPager></LinearLayout>

3 Colortrackview for tab, below is Viewpager

Viewpageruseactivity:

Package Com.zhy.viewpagerindicator;import Java.util.arraylist;import Java.util.list;import android.os.Bundle; Import Android.support.v4.app.fragment;import Android.support.v4.app.fragmentactivity;import Android.support.v4.app.fragmentpageradapter;import Android.support.v4.view.viewpager;import Android.support.v4.view.viewpager.onpagechangelistener;import Android.util.log;import Com.zhy.view.colortrackview;public class Viewpageruseactivity extends Fragmentactivity{private String[] MTitles = new String[] {"Introduction", "Evaluation", "related"};p rivate viewpager mviewpager;private fragmentpageradapter madapter;private TabFragment[] MF ragments = new Tabfragment[mtitles.length];p rivate list<colortrackview> mtabs = new Arraylist<colortrackview > (); @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_vp_main); Initviews (); Initdatas (); initevents ();} private void Initevents () {Mviewpager.setonpagechangelistener (new OnpagechangelisteNER () {@Overridepublic void onpageselected (int position) {} @Overridepublic void onpagescrolled (int position, float   Positionoffset,int positionoffsetpixels) {if (Positionoffset > 0) {Colortrackview left = Mtabs.get (position);  Colortrackview right = Mtabs.get (position + 1); Left.setdirection (1); right.setdirection (0);            LOG.E ("TAG", positionoffset+ "");              Left.setprogress (1-positionoffset);          Right.setprogress (Positionoffset); }} @Overridepublic void onpagescrollstatechanged (int state) {}});} private void Initdatas () {for (int i = 0; i < mtitles.length; i++) {mfragments[i] = (tabfragment) tabfragment.newinstance (Mtitles[i]);} Madapter = new Fragmentpageradapter (Getsupportfragmentmanager ()) {@Overridepublic int getcount () {return Mtitles.length;} @Overridepublic Fragment getItem (int position) {return mfragments[position];}}; Mviewpager.setadapter (Madapter); Mviewpager.setcurrentitem (0);} private void Initviews () {Mviewpager = (Viewpager) Findviewbyid (r.id.id_vIewpager); Mtabs.add ((Colortrackview) Findviewbyid (r.id.id_tab_01)); Mtabs.add ((Colortrackview) findViewById ( r.id.id_tab_02)); Mtabs.add ((Colortrackview) Findviewbyid (r.id.id_tab_03));}}

Tabfragment

Package Com.zhy.viewpagerindicator;import Java.util.random;import Android.graphics.color;import android.os.Bundle; Import Android.support.v4.app.fragment;import Android.view.gravity;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;import Android.widget.textview;public class TabFragment extends Fragment{public static final String title = "title";p rivate String mtitle = "Defaut Value"; @Overridepublic void OnCreate (B Undle savedinstancestate) {super.oncreate (savedinstancestate); if (getarguments ()! = null) {Mtitle = Getarguments (). GetString (TITLE);}} @Overridepublic View Oncreateview (layoutinflater inflater, ViewGroup container,bundle savedinstancestate) {TextView TV = New TextView (getactivity ()); Tv.settextsize (60); Random r = new Random (), Tv.setbackgroundcolor (Color.argb (R.nextint), R.nextint (255), R.nextint (255), R.nextint ( 255)); Tv.settext (Mtitle); tv.setgravity (Gravity.center); return TV;} public static tabfragment newinstance (String title) {Tabfragment Tabfragment = new Tabfragment (); Bundle bundle = new bundle (); bundle.putstring (title, title); Tabfragment.setarguments (bundle); return tabfragment;}}

See above 2.


Source Address: Colortrackview, welcome star or Fork.

Group number: 429757068

Public Number please scan (First time notice blog, video, etc.):














Android custom controls Play turn font color create cool Viewpager indicator

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.