Android Development: The simplest and most convenient way to Viewpager and indicator

Source: Internet
Author: User

When developing Android apps, do you feel powerless every time you add indicator to Viewpager, look at the Jakewharton GitHub, or apply the library, or add code to your project, Also add attrs, add a variety of value, such as colors,strings, in fact, more than 90% of the time, our needs are actually very simple, just in the middle of the bottom with the indicator dot, and Jakewharton the default of the great God is the hollow circle, Also in the OnDraw to change Narimi heart circle, is not bored, every time so troublesome, good, the ultimate simple solution came out, want to see the effect:


Of course, this effect to copy other people's diagram, but to achieve this effect, I used a super simple method, once and for all:


Just three steps, copy and paste, copy and paste, then write a few lines of code in the activity.


    • First step, copy, paste
Create a new class called Circleindicatorhelper, and then copy the following code in:
public class Circleindicatorhelper {private Circlepageindicator mcircleindicator;private Context mcontext;public Circleindicatorhelper (Context context) {Mcircleindicator = new Circlepageindicator (context); mcontext = context;} public void Setviewpager (Viewpager viewpager) {ViewGroup Parentview = (viewgroup) viewpager.getparent (); Layoutparams LP = new Layoutparams (layoutparams.match_parent, layoutparams.wrap_content, Gravity.bottom); Lp.setmargins (0, 0, 0, DPTOPX (8)), MCIRCLEINDICATOR.SETLAYOUTPARAMS (LP);p Arentview.addview (mcircleindicator); Mcircleindicator.setviewpager (Viewpager);} public void Setfillcolor (String colorstring) {int color = Color.parsecolor (colorstring); Mcircleindicator.setfillcolor (color);} public void Setdefaultcolor (String colorstring) {int color = Color.parsecolor (colorstring); Mcircleindicator.setdefaultcolor (color);} public void Setradius (int radius) {Mcircleindicator.setradius (dptopx (RADIUS));} private int dptopx (int dp) {displaymetrics RESOUREC = Mcontext.getresources (). gEtdisplaymetrics (); return (int) typedvalue.applydimension (Typedvalue.complex_unit_dip, DP, RESOUREC);}} 

    • Second, create a new class, called Copy, paste
public class Circlepageindicator extends view{private static final int invalid_pointer =-1;    Private float mradius;//Private final paint Mpaintpagefill = new paint (Anti_alias_flag);    Private final paint Mpaintstroke = new paint (Anti_alias_flag);    Private final paint Mpaintfill = new paint (Anti_alias_flag);    Private Viewpager Mviewpager;    Private Viewpager.onpagechangelistener Mlistener;    private int mcurrentpage;    private int msnappage;    private float Mpageoffset;    private int mscrollstate;    private int morientation;    Private Boolean mcentered;        Private Boolean Msnap;    private float Ciclespace;    Public Circlepageindicator (Context context) {This (context, NULL);    } public Circlepageindicator (context context, AttributeSet Attrs) {This (context, attrs, 0); } public Circlepageindicator (context context, AttributeSet attrs, int defstyle) {Super (context, Attrs, Defstyle        );        if (Isineditmode ()) return; FinalResources res = getresources ();        Final int defaultfillcolor = Color.parsecolor ("#7F7F7F");        Final int defaultstrokecolor = Color.parsecolor ("#D0D0D0");        Final float Defaultradius = typedvalue.applydimension (Typedvalue.complex_unit_dip, 3, Res.getdisplaymetrics ());        Mcentered = true;        Mpaintstroke.setstyle (Style.fill);        Mpaintstroke.setcolor (Defaultstrokecolor);        Mpaintfill.setstyle (Style.fill);        Mpaintfill.setcolor (Defaultfillcolor);                Mradius = Defaultradius;    Ciclespace = mradius*3;        The public void setcentered (Boolean centered) {mcentered = centered;    Invalidate ();    } public boolean iscentered () {return mcentered;        } public void Setdefaultcolor (int strokecolor) {mpaintstroke.setcolor (strokecolor);    Invalidate ();    } public void Setfillcolor (int fillcolor) {mpaintfill.setcolor (FillColor);    Invalidate ();        } public void Setradius (float radius) {Mradius = radius;        Ciclespace = radius*3;    Invalidate ();        } @Override protected void OnDraw (canvas canvas) {super.ondraw (canvas);        if (Mviewpager = = null) {return;        } final int count = Mviewpager.getadapter (). GetCount ();        if (count = = 0) {return;            } if (Mcurrentpage >= count) {Setcurrentitem (count-1);        Return        } int longsize;        int Longpaddingbefore;        int longpaddingafter;        int Shortpaddingbefore;            if (morientation = = Horizontal) {longsize = GetWidth ();            Longpaddingbefore = Getpaddingleft ();            Longpaddingafter = Getpaddingright ();        Shortpaddingbefore = Getpaddingtop ();            } else {longsize = GetHeight ();            Longpaddingbefore = Getpaddingtop ();            Longpaddingafter = Getpaddingbottom ();        Shortpaddingbefore = Getpaddingleft (); } Final Float SHOrtoffset = Shortpaddingbefore + Mradius;        Float Longoffset = Longpaddingbefore + Mradius; if (mcentered) {Longoffset + = ((longsize-longpaddingbefore-longpaddingafter)/2.0f)-((Count * Ciclespac        e)/2.0f);        } float DX;        float DY;        float Pagefillradius = Mradius; Draw stroked circles for (int iLoop = 0; iLoop < count; iloop++) {Float Drawlong = Longoffset + (i            Loop * ciclespace);                if (morientation = = Horizontal) {DX = Drawlong;            DY = Shortoffset;                } else {DX = Shortoffset;            DY = Drawlong; }//Only paint fill if not completely transparent canvas.drawcircle (DX, DY, Mradius, Mpaintstro        KE); }//draw the filled circle according to the current scroll float cx = (msnap? msnappage:mcurrentpage) * C        Iclespace; if (!MSNAP) {cx + = Mpageoffset * Ciclespace;            } if (morientation = = Horizontal) {DX = Longoffset + cx;        DY = Shortoffset;            } else {DX = Shortoffset;        DY = Longoffset + cx;    } canvas.drawcircle (DX, DY, Mradius, Mpaintfill);        public void Setviewpager (Viewpager view) {if (Mviewpager = = view) {return;        } if (Mviewpager! = null) {Mviewpager.setonpagechangelistener (null); } if (view.getadapter () = = null) {throw new IllegalStateException ("Viewpager does not has adapter inst        ance. ");        Mviewpager = view;        Mviewpager.setonpagechangelistener (New Onpagechangelistener () {@Overridepublic void onpageselected (int position) {            if (Msnap | | mscrollstate = = viewpager.scroll_state_idle) {mcurrentpage = position;            Msnappage = position;        Invalidate ();   } if (Mlistener! = null) {mlistener.onpageselected (position);     }} @Overridepublic void onpagescrolled (int position, float positionoffset, int positionoffsetpixels) {Mcurrentpage        = position;        Mpageoffset = Positionoffset;        Invalidate ();        if (Mlistener! = null) {mlistener.onpagescrolled (position, Positionoffset, positionoffsetpixels);        }} @Overridepublic void onpagescrollstatechanged (int state) {mscrollstate = state;        if (Mlistener! = null) {mlistener.onpagescrollstatechanged (state);        }}});    Invalidate ();        } public void Setviewpager (Viewpager view, int initialposition) {Setviewpager (view);    Setcurrentitem (initialposition); } public void Setcurrentitem (int item) {if (Mviewpager = = null) {throw new IllegalStateException ("V        Iewpager have not been bound. ");        Mviewpager.setcurrentitem (item);        Mcurrentpage = Item;    Invalidate (); } @Override protected void onmeasure (int widthmeasurespec, int heightmeasuresPEC) {if (morientation = = horizontal) {setmeasureddimension (Measurelong (widthmeasurespec), Measureshor        T (Heightmeasurespec));        } else {setmeasureddimension (Measureshort (Widthmeasurespec), Measurelong (Heightmeasurespec));  }}/** * Determines the width of this view * * @param measurespec * A Measurespec Packed into a int * @return The width of the view, honoring constraints from MEASURESPEC */private int Measurelong (        int measurespec) {int result;        int specmode = Measurespec.getmode (Measurespec);        int specsize = measurespec.getsize (Measurespec); if ((Specmode = = measurespec.exactly) | | (Mviewpager = = null))        {//we were told how big to be result = specsize; } else {//calculate The width according the views count final int count = Mviewpager.getadapter (). g            Etcount (); result = (int) (Getpaddingleft () + GetpaddingrighT () + (count * 2 * Mradius) + (count-1) * Mradius + 1);                Respect At_most value if that's what's called for by Measurespec if (Specmode = = Measurespec.at_most) {            result = Math.min (result, specsize);    }} return result; }/** * Determines the height of this view * * @param measurespec * A measurespec packed int O an int. * @return the height of the view, honoring constraints from MEASURESPEC */private int measureshort (in        T measurespec) {int result;        int specmode = Measurespec.getmode (Measurespec);        int specsize = measurespec.getsize (Measurespec);        if (Specmode = = measurespec.exactly) {//we were told how big to be result = specsize; } else {//measure the height result = (int) (2 * Mradius + getpaddingtop () + getpaddingbottom () + 1)            ; Respect At_most value if is Called for by Measurespec if (Specmode = = measurespec.at_most) {result = Math.min (result, spec            Size);    }} return result;         } @Override public void Onrestoreinstancestate (parcelable state) {savedstate savedstate = (savedstate) state;        Super.onrestoreinstancestate (Savedstate.getsuperstate ());        Mcurrentpage = Savedstate.currentpage;        Msnappage = Savedstate.currentpage;    Requestlayout ();        } @Override Public parcelable onsaveinstancestate () {parcelable superstate = super.onsaveinstancestate ();        savedstate savedstate = new savedstate (superstate);        Savedstate.currentpage = Mcurrentpage;    return savedstate;        } static class Savedstate extends basesavedstate {int currentpage;        Public savedstate (Parcelable superstate) {super (superstate);            } private Savedstate (Parcel in) {super (in); CurrentPage = In.readint ();        } @Override public void Writetoparcel (Parcel dest, int flags) {Super.writetoparcel (dest,            Flags);        Dest.writeint (currentpage); } @SuppressWarnings ("Unuseddeclaration") public static final parcelable.creator<savedstate> Creator =  New Parcelable.creator<savedstate> () {@Override public savedstate createfromparcel (Parcel in)            {return new savedstate (in);            } @Override Public savedstate[] NewArray (int size) {return new savedstate[size];    }        }; }    }

The code is a bit long, but just copy and paste, there should be no problem.
    • The third part, in the activity containing Viewpager, quote the following code, you can add Viewpagerindicator
Private Circleindicatorhelper Mindicatorhelper = new Circleindicatorhelper (this); Mindicatorhelper.setviewpager ( Mviewpager);

Well, it is so simple, so wayward, and never worry about adding small circles, but the question came, how to customize it, I want the color of the circle, size, spacing, OK, these are a code to fix;
Mindicatorhelper.setfillcolor ("#651717"); Mindicatorhelper.setdefaultcolor ("#00A2E8"); Mindicatorhelper.setradius (8);

Set the fill color, set the default color, set the size, simple and convenient, and finally, don't forget to set Viewpager's parent view to Framelayout OH


Android Development: The simplest and most convenient way to Viewpager and 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.