OSDN Git Service

Repackaged com.andrew.apollo to com.cyngn.eleven
[android-x86/packages-apps-Eleven.git] / src / com / viewpagerindicator / CirclePageIndicator.java
1 /*
2  * Copyright (C) 2011 Patrik Akerfeldt
3  * Copyright (C) 2011 Jake Wharton
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 package com.viewpagerindicator;
18
19 import android.content.Context;
20 import android.content.res.Resources;
21 import android.content.res.TypedArray;
22 import android.graphics.Canvas;
23 import android.graphics.Paint;
24 import android.graphics.Paint.Style;
25 import android.graphics.drawable.Drawable;
26 import android.os.Parcel;
27 import android.os.Parcelable;
28 import android.support.v4.view.MotionEventCompat;
29 import android.support.v4.view.ViewConfigurationCompat;
30 import android.support.v4.view.ViewPager;
31 import android.util.AttributeSet;
32 import android.view.MotionEvent;
33 import android.view.View;
34 import android.view.ViewConfiguration;
35
36 import static android.graphics.Paint.ANTI_ALIAS_FLAG;
37 import static android.widget.LinearLayout.HORIZONTAL;
38 import static android.widget.LinearLayout.VERTICAL;
39
40 import com.cyngn.eleven.R;
41
42 /**
43  * Draws circles (one for each view). The current view position is filled and
44  * others are only stroked.
45  */
46 public class CirclePageIndicator extends View implements PageIndicator {
47     private static final int INVALID_POINTER = -1;
48
49     private float mRadius;
50     private final Paint mPaintPageFill = new Paint(ANTI_ALIAS_FLAG);
51     private final Paint mPaintStroke = new Paint(ANTI_ALIAS_FLAG);
52     private final Paint mPaintFill = new Paint(ANTI_ALIAS_FLAG);
53     private ViewPager mViewPager;
54     private ViewPager.OnPageChangeListener mListener;
55     private int mCurrentPage;
56     private int mSnapPage;
57     private float mPageOffset;
58     private int mScrollState;
59     private int mOrientation;
60     private boolean mCentered;
61     private boolean mSnap;
62
63     private int mTouchSlop;
64     private float mLastMotionX = -1;
65     private int mActivePointerId = INVALID_POINTER;
66     private boolean mIsDragging;
67
68
69     public CirclePageIndicator(Context context) {
70         this(context, null);
71     }
72
73     public CirclePageIndicator(Context context, AttributeSet attrs) {
74         this(context, attrs, R.attr.vpiCirclePageIndicatorStyle);
75     }
76
77     public CirclePageIndicator(Context context, AttributeSet attrs, int defStyle) {
78         super(context, attrs, defStyle);
79         if (isInEditMode()) return;
80
81         //Load defaults from resources
82         final Resources res = getResources();
83         final int defaultPageColor = res.getColor(R.color.default_circle_indicator_page_color);
84         final int defaultFillColor = res.getColor(R.color.default_circle_indicator_fill_color);
85         final int defaultOrientation = res.getInteger(R.integer.default_circle_indicator_orientation);
86         final int defaultStrokeColor = res.getColor(R.color.default_circle_indicator_stroke_color);
87         final float defaultStrokeWidth = res.getDimension(R.dimen.default_circle_indicator_stroke_width);
88         final float defaultRadius = res.getDimension(R.dimen.default_circle_indicator_radius);
89         final boolean defaultCentered = res.getBoolean(R.bool.default_circle_indicator_centered);
90         final boolean defaultSnap = res.getBoolean(R.bool.default_circle_indicator_snap);
91
92         //Retrieve styles attributes
93         TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CirclePageIndicator, defStyle, 0);
94
95         mCentered = a.getBoolean(R.styleable.CirclePageIndicator_centered, defaultCentered);
96         mOrientation = a.getInt(R.styleable.CirclePageIndicator_android_orientation, defaultOrientation);
97         mPaintPageFill.setStyle(Style.FILL);
98         mPaintPageFill.setColor(a.getColor(R.styleable.CirclePageIndicator_pageColor, defaultPageColor));
99         mPaintStroke.setStyle(Style.STROKE);
100         mPaintStroke.setColor(a.getColor(R.styleable.CirclePageIndicator_strokeColor, defaultStrokeColor));
101         mPaintStroke.setStrokeWidth(a.getDimension(R.styleable.CirclePageIndicator_strokeWidth, defaultStrokeWidth));
102         mPaintFill.setStyle(Style.FILL);
103         mPaintFill.setColor(a.getColor(R.styleable.CirclePageIndicator_fillColor, defaultFillColor));
104         mRadius = a.getDimension(R.styleable.CirclePageIndicator_radius, defaultRadius);
105         mSnap = a.getBoolean(R.styleable.CirclePageIndicator_snap, defaultSnap);
106
107         Drawable background = a.getDrawable(R.styleable.CirclePageIndicator_android_background);
108         if (background != null) {
109           setBackgroundDrawable(background);
110         }
111
112         a.recycle();
113
114         final ViewConfiguration configuration = ViewConfiguration.get(context);
115         mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration);
116     }
117
118
119     public void setCentered(boolean centered) {
120         mCentered = centered;
121         invalidate();
122     }
123
124     public boolean isCentered() {
125         return mCentered;
126     }
127
128     public void setPageColor(int pageColor) {
129         mPaintPageFill.setColor(pageColor);
130         invalidate();
131     }
132
133     public int getPageColor() {
134         return mPaintPageFill.getColor();
135     }
136
137     public void setFillColor(int fillColor) {
138         mPaintFill.setColor(fillColor);
139         invalidate();
140     }
141
142     public int getFillColor() {
143         return mPaintFill.getColor();
144     }
145
146     public void setOrientation(int orientation) {
147         switch (orientation) {
148             case HORIZONTAL:
149             case VERTICAL:
150                 mOrientation = orientation;
151                 requestLayout();
152                 break;
153
154             default:
155                 throw new IllegalArgumentException("Orientation must be either HORIZONTAL or VERTICAL.");
156         }
157     }
158
159     public int getOrientation() {
160         return mOrientation;
161     }
162
163     public void setStrokeColor(int strokeColor) {
164         mPaintStroke.setColor(strokeColor);
165         invalidate();
166     }
167
168     public int getStrokeColor() {
169         return mPaintStroke.getColor();
170     }
171
172     public void setStrokeWidth(float strokeWidth) {
173         mPaintStroke.setStrokeWidth(strokeWidth);
174         invalidate();
175     }
176
177     public float getStrokeWidth() {
178         return mPaintStroke.getStrokeWidth();
179     }
180
181     public void setRadius(float radius) {
182         mRadius = radius;
183         invalidate();
184     }
185
186     public float getRadius() {
187         return mRadius;
188     }
189
190     public void setSnap(boolean snap) {
191         mSnap = snap;
192         invalidate();
193     }
194
195     public boolean isSnap() {
196         return mSnap;
197     }
198
199     @Override
200     protected void onDraw(Canvas canvas) {
201         super.onDraw(canvas);
202
203         if (mViewPager == null) {
204             return;
205         }
206         final int count = mViewPager.getAdapter().getCount();
207         if (count == 0) {
208             return;
209         }
210
211         if (mCurrentPage >= count) {
212             setCurrentItem(count - 1);
213             return;
214         }
215
216         int longSize;
217         int longPaddingBefore;
218         int longPaddingAfter;
219         int shortPaddingBefore;
220         if (mOrientation == HORIZONTAL) {
221             longSize = getWidth();
222             longPaddingBefore = getPaddingLeft();
223             longPaddingAfter = getPaddingRight();
224             shortPaddingBefore = getPaddingTop();
225         } else {
226             longSize = getHeight();
227             longPaddingBefore = getPaddingTop();
228             longPaddingAfter = getPaddingBottom();
229             shortPaddingBefore = getPaddingLeft();
230         }
231
232         final float threeRadius = mRadius * 3;
233         final float shortOffset = shortPaddingBefore + mRadius;
234         float longOffset = longPaddingBefore + mRadius;
235         if (mCentered) {
236             longOffset += ((longSize - longPaddingBefore - longPaddingAfter) / 2.0f) - ((count * threeRadius) / 2.0f);
237         }
238
239         float dX;
240         float dY;
241
242         float pageFillRadius = mRadius;
243         if (mPaintStroke.getStrokeWidth() > 0) {
244             pageFillRadius -= mPaintStroke.getStrokeWidth() / 2.0f;
245         }
246
247         //Draw stroked circles
248         for (int iLoop = 0; iLoop < count; iLoop++) {
249             float drawLong = longOffset + (iLoop * threeRadius);
250             if (mOrientation == HORIZONTAL) {
251                 dX = drawLong;
252                 dY = shortOffset;
253             } else {
254                 dX = shortOffset;
255                 dY = drawLong;
256             }
257             // Only paint fill if not completely transparent
258             if (mPaintPageFill.getAlpha() > 0) {
259                 canvas.drawCircle(dX, dY, pageFillRadius, mPaintPageFill);
260             }
261
262             // Only paint stroke if a stroke width was non-zero
263             if (pageFillRadius != mRadius) {
264                 canvas.drawCircle(dX, dY, mRadius, mPaintStroke);
265             }
266         }
267
268         //Draw the filled circle according to the current scroll
269         float cx = (mSnap ? mSnapPage : mCurrentPage) * threeRadius;
270         if (!mSnap) {
271             cx += mPageOffset * threeRadius;
272         }
273         if (mOrientation == HORIZONTAL) {
274             dX = longOffset + cx;
275             dY = shortOffset;
276         } else {
277             dX = shortOffset;
278             dY = longOffset + cx;
279         }
280         canvas.drawCircle(dX, dY, mRadius, mPaintFill);
281     }
282
283     public boolean onTouchEvent(android.view.MotionEvent ev) {
284         if (super.onTouchEvent(ev)) {
285             return true;
286         }
287         if ((mViewPager == null) || (mViewPager.getAdapter().getCount() == 0)) {
288             return false;
289         }
290
291         final int action = ev.getAction() & MotionEventCompat.ACTION_MASK;
292         switch (action) {
293             case MotionEvent.ACTION_DOWN:
294                 mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
295                 mLastMotionX = ev.getX();
296                 break;
297
298             case MotionEvent.ACTION_MOVE: {
299                 final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
300                 final float x = MotionEventCompat.getX(ev, activePointerIndex);
301                 final float deltaX = x - mLastMotionX;
302
303                 if (!mIsDragging) {
304                     if (Math.abs(deltaX) > mTouchSlop) {
305                         mIsDragging = true;
306                     }
307                 }
308
309                 if (mIsDragging) {
310                     mLastMotionX = x;
311                     if (mViewPager.isFakeDragging() || mViewPager.beginFakeDrag()) {
312                         mViewPager.fakeDragBy(deltaX);
313                     }
314                 }
315
316                 break;
317             }
318
319             case MotionEvent.ACTION_CANCEL:
320             case MotionEvent.ACTION_UP:
321                 if (!mIsDragging) {
322                     final int count = mViewPager.getAdapter().getCount();
323                     final int width = getWidth();
324                     final float halfWidth = width / 2f;
325                     final float sixthWidth = width / 6f;
326
327                     if ((mCurrentPage > 0) && (ev.getX() < halfWidth - sixthWidth)) {
328                         if (action != MotionEvent.ACTION_CANCEL) {
329                             mViewPager.setCurrentItem(mCurrentPage - 1);
330                         }
331                         return true;
332                     } else if ((mCurrentPage < count - 1) && (ev.getX() > halfWidth + sixthWidth)) {
333                         if (action != MotionEvent.ACTION_CANCEL) {
334                             mViewPager.setCurrentItem(mCurrentPage + 1);
335                         }
336                         return true;
337                     }
338                 }
339
340                 mIsDragging = false;
341                 mActivePointerId = INVALID_POINTER;
342                 if (mViewPager.isFakeDragging()) mViewPager.endFakeDrag();
343                 break;
344
345             case MotionEventCompat.ACTION_POINTER_DOWN: {
346                 final int index = MotionEventCompat.getActionIndex(ev);
347                 mLastMotionX = MotionEventCompat.getX(ev, index);
348                 mActivePointerId = MotionEventCompat.getPointerId(ev, index);
349                 break;
350             }
351
352             case MotionEventCompat.ACTION_POINTER_UP:
353                 final int pointerIndex = MotionEventCompat.getActionIndex(ev);
354                 final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex);
355                 if (pointerId == mActivePointerId) {
356                     final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
357                     mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex);
358                 }
359                 mLastMotionX = MotionEventCompat.getX(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId));
360                 break;
361         }
362
363         return true;
364     }
365
366     @Override
367     public void setViewPager(ViewPager view) {
368         if (mViewPager == view) {
369             return;
370         }
371         if (mViewPager != null) {
372             mViewPager.setOnPageChangeListener(null);
373         }
374         if (view.getAdapter() == null) {
375             throw new IllegalStateException("ViewPager does not have adapter instance.");
376         }
377         mViewPager = view;
378         mViewPager.setOnPageChangeListener(this);
379         invalidate();
380     }
381
382     @Override
383     public void setViewPager(ViewPager view, int initialPosition) {
384         setViewPager(view);
385         setCurrentItem(initialPosition);
386     }
387
388     @Override
389     public void setCurrentItem(int item) {
390         if (mViewPager == null) {
391             throw new IllegalStateException("ViewPager has not been bound.");
392         }
393         mViewPager.setCurrentItem(item);
394         mCurrentPage = item;
395         invalidate();
396     }
397
398     @Override
399     public void notifyDataSetChanged() {
400         invalidate();
401     }
402
403     @Override
404     public void onPageScrollStateChanged(int state) {
405         mScrollState = state;
406
407         if (mListener != null) {
408             mListener.onPageScrollStateChanged(state);
409         }
410     }
411
412     @Override
413     public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
414         mCurrentPage = position;
415         mPageOffset = positionOffset;
416         invalidate();
417
418         if (mListener != null) {
419             mListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
420         }
421     }
422
423     @Override
424     public void onPageSelected(int position) {
425         if (mSnap || mScrollState == ViewPager.SCROLL_STATE_IDLE) {
426             mCurrentPage = position;
427             mSnapPage = position;
428             invalidate();
429         }
430
431         if (mListener != null) {
432             mListener.onPageSelected(position);
433         }
434     }
435
436     @Override
437     public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
438         mListener = listener;
439     }
440
441     /*
442      * (non-Javadoc)
443      *
444      * @see android.view.View#onMeasure(int, int)
445      */
446     @Override
447     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
448         if (mOrientation == HORIZONTAL) {
449             setMeasuredDimension(measureLong(widthMeasureSpec), measureShort(heightMeasureSpec));
450         } else {
451             setMeasuredDimension(measureShort(widthMeasureSpec), measureLong(heightMeasureSpec));
452         }
453     }
454
455     /**
456      * Determines the width of this view
457      *
458      * @param measureSpec
459      *            A measureSpec packed into an int
460      * @return The width of the view, honoring constraints from measureSpec
461      */
462     private int measureLong(int measureSpec) {
463         int result;
464         int specMode = MeasureSpec.getMode(measureSpec);
465         int specSize = MeasureSpec.getSize(measureSpec);
466
467         if ((specMode == MeasureSpec.EXACTLY) || (mViewPager == null)) {
468             //We were told how big to be
469             result = specSize;
470         } else {
471             //Calculate the width according the views count
472             final int count = mViewPager.getAdapter().getCount();
473             result = (int)(getPaddingLeft() + getPaddingRight()
474                     + (count * 2 * mRadius) + (count - 1) * mRadius + 1);
475             //Respect AT_MOST value if that was what is called for by measureSpec
476             if (specMode == MeasureSpec.AT_MOST) {
477                 result = Math.min(result, specSize);
478             }
479         }
480         return result;
481     }
482
483     /**
484      * Determines the height of this view
485      *
486      * @param measureSpec
487      *            A measureSpec packed into an int
488      * @return The height of the view, honoring constraints from measureSpec
489      */
490     private int measureShort(int measureSpec) {
491         int result;
492         int specMode = MeasureSpec.getMode(measureSpec);
493         int specSize = MeasureSpec.getSize(measureSpec);
494
495         if (specMode == MeasureSpec.EXACTLY) {
496             //We were told how big to be
497             result = specSize;
498         } else {
499             //Measure the height
500             result = (int)(2 * mRadius + getPaddingTop() + getPaddingBottom() + 1);
501             //Respect AT_MOST value if that was what is called for by measureSpec
502             if (specMode == MeasureSpec.AT_MOST) {
503                 result = Math.min(result, specSize);
504             }
505         }
506         return result;
507     }
508
509     @Override
510     public void onRestoreInstanceState(Parcelable state) {
511         SavedState savedState = (SavedState)state;
512         super.onRestoreInstanceState(savedState.getSuperState());
513         mCurrentPage = savedState.currentPage;
514         mSnapPage = savedState.currentPage;
515         requestLayout();
516     }
517
518     @Override
519     public Parcelable onSaveInstanceState() {
520         Parcelable superState = super.onSaveInstanceState();
521         SavedState savedState = new SavedState(superState);
522         savedState.currentPage = mCurrentPage;
523         return savedState;
524     }
525
526     static class SavedState extends BaseSavedState {
527         int currentPage;
528
529         public SavedState(Parcelable superState) {
530             super(superState);
531         }
532
533         private SavedState(Parcel in) {
534             super(in);
535             currentPage = in.readInt();
536         }
537
538         @Override
539         public void writeToParcel(Parcel dest, int flags) {
540             super.writeToParcel(dest, flags);
541             dest.writeInt(currentPage);
542         }
543
544         @SuppressWarnings("UnusedDeclaration")
545         public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() {
546             @Override
547             public SavedState createFromParcel(Parcel in) {
548                 return new SavedState(in);
549             }
550
551             @Override
552             public SavedState[] newArray(int size) {
553                 return new SavedState[size];
554             }
555         };
556     }
557 }