The indicator of ViewPager slides with ViewPager, while viewpager slides.
1. Implementation results:
In general, the effect is as above. Because it is a part of the project, only part of it is intercepted.
2. Ideas
In fact, at the very beginning, I wanted to implement it through dynamic movement of a control. But I tried scrollBy and scrollTo, and it seemed like there was nothing to use. So I am sad. How can Nima implement it?
At first, I didn't want to use an animation to implement the movement, and there was a ready-made code on the Internet for the effect of the animation, so it's boring to write it again.
I have an article devoted to several methods in OnPageChangeListener. You can go and see them. In fact, this is nothing very mysterious today. After I figured it out, I thought it was too simple. If I write a blog, in front of the technical experts, it is estimated that wool is not worth mentioning, but I still want to write...
Well, I have been so arrogant. In fact, my implementation method is implemented through custom View, and the code is very simple.
Import android. content. context; import android. graphics. canvas; import android. graphics. color; import android. graphics. paint; import android. util. attributeSet; import android. view. view; public class RedCursorView extends View {private int cursorColor = Color. RED; // The line color private int counts = 2; // It is divided into several private float posX = 0f; // the position of the current X coordinate private Paint; public RedCursorView (Context context, AttributeSet attrs, int defStyleAttr) {super (context, attrs, defStyleAttr); init ();} public RedCursorView (Context context, AttributeSet attrs) {super (context, attrs); init ();} public RedCursorView (Context context) {super (context); init ();} private void init () {// initialize paint = new Paint (); paint. setAntiAlias (true); paint. setDither (true); paint. setColor (cursorColor);}/*** sets the number of ViewPager items * @ param counts */public void setCounts (int counts) {this. counts = counts;}/*** set coordinate * @ param pos current item * @ param rate change */public void setXY (int pos, float rate) {int single = getMeasuredWidth ()/counts; posX = pos * single + single * rate; invalidate () ;}@ Overrideprotected void onDraw (Canvas canvas) {super. onDraw (canvas); paint. setStrokeWidth (getMeasuredHeight (); int width = getMeasuredWidth ()/counts-2; canvas. drawLine (posX, 0, posX + width, 0, paint );}}
You can understand it at a Glance. You only need to call it when calling:
@Overridepublic void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {cursor.setXY(position, positionOffset);}
That's all. It's really easy to think about. I still felt very difficult before, and I was really drunk...