Custom Viewpager navigation Indecator (very practical and mainstream)

Source: Internet
Author: User
Tags getcolor gety

Custom Viewpager navigation Indecator (very practical and mainstream) now there are indicator in many app's welcome pages or on the home page (that is, the small dots that scroll with viewpager scrolling); and then a lot of the display effect is basically a selection Picture and an image that has not been selected, so that the two images are constantly rotated, this effect is rotten street. And there is a kind of effect is that the selected small dot is with viewpager sliding and sliding has the obvious animation effect, I think how to do such an effect, the fruit does not have, Kung fu not bear, finally out, the effect is as follows:

First make a draft diagram as follows:
technical points to consider: 1, the number of small dots how to determine; 2, the background color of small dots, the radius of the circle and their spacing between the margin can be customized; 3, the placement of small dots; 4, the creation of small dot object; 5, the selected small origin is how to slide on the layer above the display;
think of the problem, then start to find a solution to see if there is no, we need to check the information. There is always a way to think, here are some of the individual solutions:          1, the number of small dots and viewpager the same number of content, with Viewpager.getadapter (). GetCount () to obtain the number; 2, the background color of small dots, and the radius, margin can be set using custom attributes; 3, the location of small dots can use the layout method in the custom view to get the parent container width-the total width of the small dots, this is the horizontal center, and then take the container height of half-radius is the small dot y start position; 4, small dots to dynamically save its width, draw background color, x, y coordinates and other information, this time will start to select the object, the use of shapedrawable; 5, the most important point is that the small dot to move with the Viewpager, it is drawn on the layer above, it is necessary to set the properties of the paint, very key, as follows:
//To draw the source image at the top of the target image, it can be seen from the name to draw the source image above, the selected small Origin is drawn on the top Paint.setxfermode (porterduffxfermode (porterduff.mode. Src_over ));

when the above analysis is complete, then we start to do it:
1. Create a custom attribute:
<?xml version= "1.0" encoding= "Utf-8"?><resources> <declare-styleable    name= "Circleindicator" >        <attr name= "Indicator_radio" format= "Dimension"/>        <attr name= "Indicator_margin" format= " Dimension "/>        <attr name=" Indicator_background "format=" Color|integer "/>        <attr name=" indicator _selected_background "format=" Color|integer "/>    </declare-styleable></resources>

2. Using a custom view in Main_activity.xml
<?xml version= "1.0" encoding= "Utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk/res/ Android "xmlns:indicator=" Http://schemas.android.com/apk/res-auto "xmlns:tools=" Http://schemas.android.com/tools "Android:layout_width=" match_parent "android:layout_height=" match_parent "tools:context=" Com.world.hello.circlei Ndicator. Mainactivity "> <android.support.v4.view.viewpager android:id=" @+id/view_pager "android:layout_width        = "Match_parent" android:layout_height= "match_parent"/> <com.world.hello.circleindicator.circleindicator        Android:id= "@+id/pager_indicator" android:layout_width= "match_parent" android:layout_height= "40DP" Android:layout_alignparentbottom= "true" android:layout_marginbottom= "40DP" Indicator:indicator_backgroun D= "@android: Color/white" indicator:indicator_margin= "20DP" indicator:indicator_radio= "10DP" indicator : Indicator_selected_backgrouNd= "@android: Color/holo_red_light"/></relativelayout> 

3, Mainactivity.class, configure several pictures for Viewpager
Package Com.world.hello.circleindicator;import Android.os.bundle;import Android.support.v4.view.PagerAdapter; Import Android.support.v4.view.viewpager;import Android.support.v7.app.appcompatactivity;import Android.view.View ; Import Android.view.viewgroup;import Android.widget.imageview;import Java.util.arraylist;public class MainActivity    Extends Appcompatactivity {private Viewpager mviewpager;            Here for Viewpager simulation 5 photos Private int[] Mimags = new int[]{r.drawable.img1, R.drawable.img2,    R.DRAWABLE.IMG3, R.DRAWABLE.IMG4, r.drawable.img5};    Private arraylist<imageview> mimageviews = new arraylist<imageview> ();    Viewpager Small dot navigation private circleindicator mindicator;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Mviewpager = (Viewpager) Findviewbyid (R.id.view_pager); for (int i = 0; i < MIMags.length;            i++) {ImageView ImageView = new ImageView (mainactivity.this);            Imageview.setimageresource (Mimags[i]);            Imageview.setscaletype (ImageView.ScaleType.FIT_XY);        Mimageviews.add (ImageView);        } mviewpager.setadapter (Pageradapter);        Mindicator = (circleindicator) Findviewbyid (r.id.pager_indicator);    The indicator and Viewpager are bound together to achieve the linkage effect Mindicator.setviewpager (Mviewpager); } pageradapter Pageradapter = new Pageradapter () {@Override public int getcount () {return MI        Mags.length;        } @Override Public Boolean isviewfromobject (view view, Object object) {return view = = Object; } @Override public void Destroyitem (ViewGroup container, int position, object object) {Con        Tainer.removeview (Mimageviews.get (position));        } @Override public charsequence getpagetitle (int position) {return ' null ';} @Override Public Object instantiateitem (viewgroup container, int position) {Container.addview (            Mimageviews.get (position));        return Mimageviews.get (position); }    };}

4. Create a small Origin custom object CircleShape
Package Com.world.hello.circleindicator;import Android.graphics.paint;import Android.graphics.drawable.shapedrawable;import android.graphics.drawable.shapes.shape;/** * Small Dot class * Created by Chengguo on 2016/6/1.    */public class CircleShape {//Set default value private float x = 0;    Private float y = 0;    Private shapedrawable shape;    private paint paint;    Public CircleShape (shapedrawable shape) {this.shape = shape;    public void Setpaint (paint value) {paint = value;    } Public Paint Getpaint () {return paint;    } public void SetX (float value) {x = value;    } public float GetX () {return x;    } public void Sety (float value) {y = value;    } public float GetY () {return y;    } public void Setshape (shapedrawable value) {shape = value;    } public shapedrawable Getshape () {return shape;    } public float getwidth () {return Shape.getshape (). GetWidth (); } public void SetWidth (fLoat width) {Shape s = shape.getshape ();    S.resize (width, s.getheight ());    } public float GetHeight () {return Shape.getshape (). GetHeight ();        } public void SetHeight (float height) {Shape s = shape.getshape ();    S.resize (S.getwidth (), height);    public void Resizeshape (final float width, final float height) {shape.getshape (). Resize (width, height); }}
5. Custom Circleindicator Implementation class
Package Com.world.hello.circleindicator;import Android.content.context;import Android.content.res.TypedArray; Import Android.graphics.canvas;import Android.graphics.color;import Android.graphics.paint;import Android.graphics.porterduff;import Android.graphics.porterduffxfermode;import Android.graphics.drawable.shapedrawable;import Android.graphics.drawable.shapes.ovalshape;import Android.support.v4.view.viewpager;import Android.util.attributeset;import Android.view.view;import Java.util.arraylist;import java.util.list;/** * Custom indicator class * Created by Chengguo on 2016/6/1.    */public class Circleindicator extends View {//Receive Viewpager from activity, realize linkage private viewpager mviewpager;    The object of the current small dot private circleshape mselectindicator;    All small Origin objects collection private list<circleshape> mindicatorlists = new arraylist<circleshape> ();    The circle radius of the small dot is private float mindicatorradius;    The interval between small dots is private float mindicatormargin;    Small dot background private int mindicatorbackground;Select the background of the small dot private int mindicatorselectedbackground;  Viewpager current position private int mcurrentposition = 0;//default is 0//viewpager offset of current position private float Mcurrentpositionoffset    = 0;        Here are some of the default values for custom properties private final int default_radius = 10;  Default RADIUS private final int default_margin = 50;    Default spacing private final int default_background = Color.White;   Default color private final int default_selected_background = Color.yellow;    Default selected Color public circleindicator (context context) {Super (context, NULL);        } public Circleindicator (context context, AttributeSet Attrs) {Super (context, attrs);    Init (context, attrs); } public Circleindicator (context context, AttributeSet attrs, int defstyleattr) {Super (context, Attrs, Defstyle        ATTR);    Init (context, attrs); }/** * Initialize Properties * * @param context * @param attrs */private void init (context context, AttributeS ET attrs) {if (attrs = = null) {return;        } TypedArray ta = context.obtainstyledattributes (attrs, r.styleable.circleindicator);        Mindicatorradius = Ta.getdimensionpixelsize (R.styleable.circleindicator_indicator_radio, DEFAULT_RADIUS);        Mindicatormargin = Ta.getdimensionpixelsize (R.styleable.circleindicator_indicator_margin, DEFAULT_MARGIN);        Mindicatorbackground = Ta.getcolor (R.styleable.circleindicator_indicator_background, DEFAULT_BACKGROUND); Mindicatorselectedbackground = Ta.getcolor (R.styleable.circleindicator_indicator_selected_background, DEFAULT_        Selected_background);    Recycling resources ta.recycle (); }/** * Transfer viewpager from activity to achieve viewpager and indicator linkage * * @param viewpager */public void SETVIEWP        Ager (final Viewpager viewpager) {mviewpager = Viewpager;        Createindicators ();        Createselectindicator ();    Setupdatechangelistener (); }/** * Monitor Viewpager changes, realize small dots and viewpager linkage */private void Setupdatechangelistener () {        Mviewpager.addonpagechangelistener (New Viewpager.simpleonpagechangelistener () {@Override PU Blic void onpagescrolled (int position, float positionoffset, int positionoffsetpixels) {Super.onpagescroll                Ed (position, Positionoffset, positionoffsetpixels);                Mcurrentposition = position;                Mcurrentpositionoffset = Positionoffset;                Force the new layout requestlayout ();            Redraw invalidate ();    }        }); /** * Creates the selected small origin, which is the small dot that moves with Viewpager */private void Createselectindicator () {OvalShape circle =        New OvalShape ();        Shapedrawable drawable = new shapedrawable (circle);        Mselectindicator = new CircleShape (drawable);        Paint paint = drawable.getpaint ();        Paint.setcolor (Mindicatorselectedbackground);        Paint.setantialias (TRUE); Drawing the source image at the top of the target image, it can be seen from the name that the source image is drawn above, the selected small Origin is plotted on the top Paint.setxfermode (new PorteRduffxfermode (PorterDuff.Mode.SRC_OVER));    Mselectindicator.setpaint (paint); /** * Create the same navigation dot as the number of Viewpager */private void createindicators () {for (int i = 0; i < Mviewpager . Getadapter (). GetCount ();            i++) {//Create small Dot object with circular shape ovalshape circle = new OvalShape ();            Shapedrawable drawable = new shapedrawable (circle);            CircleShape circleshape = new CircleShape (drawable);            Paint paint = drawable.getpaint ();            Paint.setcolor (Mindicatorbackground);            Paint.setantialias (TRUE);            Circleshape.setpaint (paint);        Mindicatorlists.add (CircleShape); }} @Override protected void OnLayout (Boolean changed, int left, int top, int. right, int bottom) {SUPER.O        Nlayout (changed, left, top, right, bottom);        Layoutindicatorlists (GetWidth (), getheight ());    Layoutselectindicator (Mcurrentposition, Mcurrentpositionoffset); }/** * Place small dots * * @parAm Containerwidth * @param containerheight */private void layoutindicatorlists (int containerwidth, int contain        Erheight) {if (mindicatorlists = = null) {return;        }//container horizontal middle line float ycoordinate = containerheight * 0.5f;        float startposition = startdrawposition (containerwidth);            for (int i = 0; i < mindicatorlists.size (); i++) {CircleShape item = mindicatorlists.get (i);            Item.resizeshape (2 * mindicatorradius, 2 * mindicatorradius);            The y position of the upper left corner of each small Origin item.sety (Ycoordinate-mindicatorradius);            Each small dot x starts at a position of float x = startposition + (mindicatormargin + Mindicatorradius * 2) * I;        Item.setx (x); }}/** * Gets the starting position of the overall small origin * * @param containerwidth * @return */private float startdrawposition (int containerwidth) {Float tabitemslength = mindicatorlists.size () * (Mindicatormargin + 2 * mindicatorradius)-MindicatormargiN        if (Containerwidth < tabitemslength) {return 0;    }//Horizontal center display return (CONTAINERWIDTH-TABITEMSLENGTH)/2; /** * Place a rolling small origin * * @param position * @param positionoffset * */private void Layoutselectindicat        or (int position, float positionoffset) {if (Mselectindicator = = null) {return;        } if (mindicatorlists.size () = = 0) {return;        } CircleShape item = mindicatorlists.get (position);        Mselectindicator.resizeshape (Item.getwidth (), Item.getheight ());        Sets the X-position offset of the small circular dot that is scrolled by float x = Item.getx () + (Mindicatormargin + Mindicatorradius * 2) * POSITIONOFFSET;        Mselectindicator.setx (x);    Mselectindicator.sety (Item.gety ());        } @Override protected void OnDraw (canvas canvas) {super.ondraw (canvas);        if (mindicatorlists.size () = = 0 | | mselectindicator = = NULL) {return; } int sc = canvas.savelayer (0, 0, GetWidth (), getheight (), NULL, Canvas.matrix_save_flag |                        Canvas.clip_save_flag |                        Canvas.has_alpha_layer_save_flag |                        Canvas.full_color_layer_save_flag |        Canvas.clip_to_layer_save_flag);        for (CircleShape item:mindicatorlists) {drawItem (canvas, item);        } drawItem (canvas, mselectindicator);    Canvas.restoretocount (SC); /** * Draw Small dots * * @param canvas * @param indicator */private void DrawItem (canvas canvas, CIRCL        Eshape indicator) {canvas.save ();        Canvas.translate (Indicator.getx (), indicator.gety ());        Indicator.getshape (). Draw (canvas);    Canvas.restore (); }}

The comments on the above code are very clear, you can learn the next. The following gives the source code demo, we can download to use their own projects, very practical:
Click the open link to download the demo

   








Custom Viewpager navigation Indecator (very practical and mainstream)

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.