Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
14792 manas 1
/*
2
 * Copyright (C) 2011 Jake Wharton
3
 * Copyright (C) 2011 Patrik Akerfeldt
4
 * Copyright (C) 2011 Francisco Figueiredo Jr.
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 *      http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 */
18
package com.viewpagerindicator;
19
 
20
import android.content.Context;
21
import android.content.res.Resources;
22
import android.content.res.TypedArray;
23
import android.graphics.Canvas;
24
import android.graphics.Paint;
25
import android.graphics.Path;
26
import android.graphics.Rect;
27
import android.graphics.Typeface;
28
import android.graphics.drawable.Drawable;
29
import android.os.Parcel;
30
import android.os.Parcelable;
31
import android.support.v4.view.MotionEventCompat;
32
import android.support.v4.view.ViewConfigurationCompat;
33
import android.support.v4.view.ViewPager;
34
import android.util.AttributeSet;
35
import android.view.MotionEvent;
36
import android.view.View;
37
import android.view.ViewConfiguration;
38
 
39
import java.util.ArrayList;
40
 
41
/**
42
 * A TitlePageIndicator is a PageIndicator which displays the title of left view
43
 * (if exist), the title of the current select view (centered) and the title of
44
 * the right view (if exist). When the user scrolls the ViewPager then titles are
45
 * also scrolled.
46
 */
47
public class TitlePageIndicator extends View implements PageIndicator {
48
    /**
49
     * Percentage indicating what percentage of the screen width away from
50
     * center should the underline be fully faded. A value of 0.25 means that
51
     * halfway between the center of the screen and an edge.
52
     */
53
    private static final float SELECTION_FADE_PERCENTAGE = 0.25f;
54
 
55
    /**
56
     * Percentage indicating what percentage of the screen width away from
57
     * center should the selected text bold turn off. A value of 0.05 means
58
     * that 10% between the center and an edge.
59
     */
60
    private static final float BOLD_FADE_PERCENTAGE = 0.05f;
61
 
62
    /**
63
     * Title text used when no title is provided by the adapter.
64
     */
65
    private static final String EMPTY_TITLE = "";
66
 
67
    /**
68
     * Interface for a callback when the center item has been clicked.
69
     */
70
    public interface OnCenterItemClickListener {
71
        /**
72
         * Callback when the center item has been clicked.
73
         *
74
         * @param position Position of the current center item.
75
         */
76
        void onCenterItemClick(int position);
77
    }
78
 
79
    public enum IndicatorStyle {
80
        None(0), Triangle(1), Underline(2);
81
 
82
        public final int value;
83
 
84
        private IndicatorStyle(int value) {
85
            this.value = value;
86
        }
87
 
88
        public static IndicatorStyle fromValue(int value) {
89
            for (IndicatorStyle style : IndicatorStyle.values()) {
90
                if (style.value == value) {
91
                    return style;
92
                }
93
            }
94
            return null;
95
        }
96
    }
97
 
98
    public enum LinePosition {
99
        Bottom(0), Top(1);
100
 
101
        public final int value;
102
 
103
        private LinePosition(int value) {
104
            this.value = value;
105
        }
106
 
107
        public static LinePosition fromValue(int value) {
108
            for (LinePosition position : LinePosition.values()) {
109
                if (position.value == value) {
110
                    return position;
111
                }
112
            }
113
            return null;
114
        }
115
    }
116
 
117
    private ViewPager mViewPager;
118
    private ViewPager.OnPageChangeListener mListener;
119
    private int mCurrentPage = -1;
120
    private float mPageOffset;
121
    private int mScrollState;
122
    private final Paint mPaintText = new Paint();
123
    private boolean mBoldText;
124
    private int mColorText;
125
    private int mColorSelected;
126
    private Path mPath = new Path();
127
    private final Rect mBounds = new Rect();
128
    private final Paint mPaintFooterLine = new Paint();
129
    private IndicatorStyle mFooterIndicatorStyle;
130
    private LinePosition mLinePosition;
131
    private final Paint mPaintFooterIndicator = new Paint();
132
    private float mFooterIndicatorHeight;
133
    private float mFooterIndicatorUnderlinePadding;
134
    private float mFooterPadding;
135
    private float mTitlePadding;
136
    private float mTopPadding;
137
    /** Left and right side padding for not active view titles. */
138
    private float mClipPadding;
139
    private float mFooterLineHeight;
140
 
141
    private static final int INVALID_POINTER = -1;
142
 
143
    private int mTouchSlop;
144
    private float mLastMotionX = -1;
145
    private int mActivePointerId = INVALID_POINTER;
146
    private boolean mIsDragging;
147
 
148
    private OnCenterItemClickListener mCenterItemClickListener;
149
 
150
 
151
    public TitlePageIndicator(Context context) {
152
        this(context, null);
153
    }
154
 
155
    public TitlePageIndicator(Context context, AttributeSet attrs) {
156
        this(context, attrs, R.attr.vpiTitlePageIndicatorStyle);
157
    }
158
 
159
    public TitlePageIndicator(Context context, AttributeSet attrs, int defStyle) {
160
        super(context, attrs, defStyle);
161
        if (isInEditMode()) return;
162
 
163
        //Load defaults from resources
164
        final Resources res = getResources();
165
        final int defaultFooterColor = res.getColor(R.color.default_title_indicator_footer_color);
166
        final float defaultFooterLineHeight = res.getDimension(R.dimen.default_title_indicator_footer_line_height);
167
        final int defaultFooterIndicatorStyle = res.getInteger(R.integer.default_title_indicator_footer_indicator_style);
168
        final float defaultFooterIndicatorHeight = res.getDimension(R.dimen.default_title_indicator_footer_indicator_height);
169
        final float defaultFooterIndicatorUnderlinePadding = res.getDimension(R.dimen.default_title_indicator_footer_indicator_underline_padding);
170
        final float defaultFooterPadding = res.getDimension(R.dimen.default_title_indicator_footer_padding);
171
        final int defaultLinePosition = res.getInteger(R.integer.default_title_indicator_line_position);
172
        final int defaultSelectedColor = res.getColor(R.color.default_title_indicator_selected_color);
173
        final boolean defaultSelectedBold = res.getBoolean(R.bool.default_title_indicator_selected_bold);
174
        final int defaultTextColor = res.getColor(R.color.default_title_indicator_text_color);
175
        final float defaultTextSize = res.getDimension(R.dimen.default_title_indicator_text_size);
176
        final float defaultTitlePadding = res.getDimension(R.dimen.default_title_indicator_title_padding);
177
        final float defaultClipPadding = res.getDimension(R.dimen.default_title_indicator_clip_padding);
178
        final float defaultTopPadding = res.getDimension(R.dimen.default_title_indicator_top_padding);
179
 
180
        //Retrieve styles attributes
181
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TitlePageIndicator, defStyle, 0);
182
 
183
        //Retrieve the colors to be used for this view and apply them.
184
        mFooterLineHeight = a.getDimension(R.styleable.TitlePageIndicator_footerLineHeight, defaultFooterLineHeight);
185
        mFooterIndicatorStyle = IndicatorStyle.fromValue(a.getInteger(R.styleable.TitlePageIndicator_footerIndicatorStyle, defaultFooterIndicatorStyle));
186
        mFooterIndicatorHeight = a.getDimension(R.styleable.TitlePageIndicator_footerIndicatorHeight, defaultFooterIndicatorHeight);
187
        mFooterIndicatorUnderlinePadding = a.getDimension(R.styleable.TitlePageIndicator_footerIndicatorUnderlinePadding, defaultFooterIndicatorUnderlinePadding);
188
        mFooterPadding = a.getDimension(R.styleable.TitlePageIndicator_footerPadding, defaultFooterPadding);
189
        mLinePosition = LinePosition.fromValue(a.getInteger(R.styleable.TitlePageIndicator_linePosition, defaultLinePosition));
190
        mTopPadding = a.getDimension(R.styleable.TitlePageIndicator_topPadding, defaultTopPadding);
191
        mTitlePadding = a.getDimension(R.styleable.TitlePageIndicator_titlePadding, defaultTitlePadding);
192
        mClipPadding = a.getDimension(R.styleable.TitlePageIndicator_clipPadding, defaultClipPadding);
193
        mColorSelected = a.getColor(R.styleable.TitlePageIndicator_selectedColor, defaultSelectedColor);
194
        mColorText = a.getColor(R.styleable.TitlePageIndicator_android_textColor, defaultTextColor);
195
        mBoldText = a.getBoolean(R.styleable.TitlePageIndicator_selectedBold, defaultSelectedBold);
196
 
197
        final float textSize = a.getDimension(R.styleable.TitlePageIndicator_android_textSize, defaultTextSize);
198
        final int footerColor = a.getColor(R.styleable.TitlePageIndicator_footerColor, defaultFooterColor);
199
        mPaintText.setTextSize(textSize);
200
        mPaintText.setAntiAlias(true);
201
        mPaintFooterLine.setStyle(Paint.Style.FILL_AND_STROKE);
202
        mPaintFooterLine.setStrokeWidth(mFooterLineHeight);
203
        mPaintFooterLine.setColor(footerColor);
204
        mPaintFooterIndicator.setStyle(Paint.Style.FILL_AND_STROKE);
205
        mPaintFooterIndicator.setColor(footerColor);
206
 
207
        Drawable background = a.getDrawable(R.styleable.TitlePageIndicator_android_background);
208
        if (background != null) {
209
          setBackgroundDrawable(background);
210
        }
211
 
212
        a.recycle();
213
 
214
        final ViewConfiguration configuration = ViewConfiguration.get(context);
215
        mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration);
216
    }
217
 
218
 
219
    public int getFooterColor() {
220
        return mPaintFooterLine.getColor();
221
    }
222
 
223
    public void setFooterColor(int footerColor) {
224
        mPaintFooterLine.setColor(footerColor);
225
        mPaintFooterIndicator.setColor(footerColor);
226
        invalidate();
227
    }
228
 
229
    public float getFooterLineHeight() {
230
        return mFooterLineHeight;
231
    }
232
 
233
    public void setFooterLineHeight(float footerLineHeight) {
234
        mFooterLineHeight = footerLineHeight;
235
        mPaintFooterLine.setStrokeWidth(mFooterLineHeight);
236
        invalidate();
237
    }
238
 
239
    public float getFooterIndicatorHeight() {
240
        return mFooterIndicatorHeight;
241
    }
242
 
243
    public void setFooterIndicatorHeight(float footerTriangleHeight) {
244
        mFooterIndicatorHeight = footerTriangleHeight;
245
        invalidate();
246
    }
247
 
248
    public float getFooterIndicatorPadding() {
249
        return mFooterPadding;
250
    }
251
 
252
    public void setFooterIndicatorPadding(float footerIndicatorPadding) {
253
        mFooterPadding = footerIndicatorPadding;
254
        invalidate();
255
    }
256
 
257
    public IndicatorStyle getFooterIndicatorStyle() {
258
        return mFooterIndicatorStyle;
259
    }
260
 
261
    public void setFooterIndicatorStyle(IndicatorStyle indicatorStyle) {
262
        mFooterIndicatorStyle = indicatorStyle;
263
        invalidate();
264
    }
265
 
266
    public LinePosition getLinePosition() {
267
        return mLinePosition;
268
    }
269
 
270
    public void setLinePosition(LinePosition linePosition) {
271
        mLinePosition = linePosition;
272
        invalidate();
273
    }
274
 
275
    public int getSelectedColor() {
276
        return mColorSelected;
277
    }
278
 
279
    public void setSelectedColor(int selectedColor) {
280
        mColorSelected = selectedColor;
281
        invalidate();
282
    }
283
 
284
    public boolean isSelectedBold() {
285
        return mBoldText;
286
    }
287
 
288
    public void setSelectedBold(boolean selectedBold) {
289
        mBoldText = selectedBold;
290
        invalidate();
291
    }
292
 
293
    public int getTextColor() {
294
        return mColorText;
295
    }
296
 
297
    public void setTextColor(int textColor) {
298
        mPaintText.setColor(textColor);
299
        mColorText = textColor;
300
        invalidate();
301
    }
302
 
303
    public float getTextSize() {
304
        return mPaintText.getTextSize();
305
    }
306
 
307
    public void setTextSize(float textSize) {
308
        mPaintText.setTextSize(textSize);
309
        invalidate();
310
    }
311
 
312
    public float getTitlePadding() {
313
        return this.mTitlePadding;
314
    }
315
 
316
    public void setTitlePadding(float titlePadding) {
317
        mTitlePadding = titlePadding;
318
        invalidate();
319
    }
320
 
321
    public float getTopPadding() {
322
        return this.mTopPadding;
323
    }
324
 
325
    public void setTopPadding(float topPadding) {
326
        mTopPadding = topPadding;
327
        invalidate();
328
    }
329
 
330
    public float getClipPadding() {
331
        return this.mClipPadding;
332
    }
333
 
334
    public void setClipPadding(float clipPadding) {
335
        mClipPadding = clipPadding;
336
        invalidate();
337
    }
338
 
339
    public void setTypeface(Typeface typeface) {
340
        mPaintText.setTypeface(typeface);
341
        invalidate();
342
    }
343
 
344
    public Typeface getTypeface() {
345
        return mPaintText.getTypeface();
346
    }
347
 
348
    /*
349
     * (non-Javadoc)
350
     *
351
     * @see android.view.View#onDraw(android.graphics.Canvas)
352
     */
353
    @Override
354
    protected void onDraw(Canvas canvas) {
355
        super.onDraw(canvas);
356
 
357
        if (mViewPager == null) {
358
            return;
359
        }
360
        final int count = mViewPager.getAdapter().getCount();
361
        if (count == 0) {
362
            return;
363
        }
364
 
365
        // mCurrentPage is -1 on first start and after orientation changed. If so, retrieve the correct index from viewpager.
366
        if (mCurrentPage == -1 && mViewPager != null) {
367
            mCurrentPage = mViewPager.getCurrentItem();
368
        }
369
 
370
        //Calculate views bounds
371
        ArrayList<Rect> bounds = calculateAllBounds(mPaintText);
372
        final int boundsSize = bounds.size();
373
 
374
        //Make sure we're on a page that still exists
375
        if (mCurrentPage >= boundsSize) {
376
            setCurrentItem(boundsSize - 1);
377
            return;
378
        }
379
 
380
        final int countMinusOne = count - 1;
381
        final float halfWidth = getWidth() / 2f;
382
        final int left = getLeft();
383
        final float leftClip = left + mClipPadding;
384
        final int width = getWidth();
385
        int height = getHeight();
386
        final int right = left + width;
387
        final float rightClip = right - mClipPadding;
388
 
389
        int page = mCurrentPage;
390
        float offsetPercent;
391
        if (mPageOffset <= 0.5) {
392
            offsetPercent = mPageOffset;
393
        } else {
394
            page += 1;
395
            offsetPercent = 1 - mPageOffset;
396
        }
397
        final boolean currentSelected = (offsetPercent <= SELECTION_FADE_PERCENTAGE);
398
        final boolean currentBold = (offsetPercent <= BOLD_FADE_PERCENTAGE);
399
        final float selectedPercent = (SELECTION_FADE_PERCENTAGE - offsetPercent) / SELECTION_FADE_PERCENTAGE;
400
 
401
        //Verify if the current view must be clipped to the screen
402
        Rect curPageBound = bounds.get(mCurrentPage);
403
        float curPageWidth = curPageBound.right - curPageBound.left;
404
        if (curPageBound.left < leftClip) {
405
            //Try to clip to the screen (left side)
406
            clipViewOnTheLeft(curPageBound, curPageWidth, left);
407
        }
408
        if (curPageBound.right > rightClip) {
409
            //Try to clip to the screen (right side)
410
            clipViewOnTheRight(curPageBound, curPageWidth, right);
411
        }
412
 
413
        //Left views starting from the current position
414
        if (mCurrentPage > 0) {
415
            for (int i = mCurrentPage - 1; i >= 0; i--) {
416
                Rect bound = bounds.get(i);
417
                //Is left side is outside the screen
418
                if (bound.left < leftClip) {
419
                    int w = bound.right - bound.left;
420
                    //Try to clip to the screen (left side)
421
                    clipViewOnTheLeft(bound, w, left);
422
                    //Except if there's an intersection with the right view
423
                    Rect rightBound = bounds.get(i + 1);
424
                    //Intersection
425
                    if (bound.right + mTitlePadding > rightBound.left) {
426
                        bound.left = (int) (rightBound.left - w - mTitlePadding);
427
                        bound.right = bound.left + w;
428
                    }
429
                }
430
            }
431
        }
432
        //Right views starting from the current position
433
        if (mCurrentPage < countMinusOne) {
434
            for (int i = mCurrentPage + 1 ; i < count; i++) {
435
                Rect bound = bounds.get(i);
436
                //If right side is outside the screen
437
                if (bound.right > rightClip) {
438
                    int w = bound.right - bound.left;
439
                    //Try to clip to the screen (right side)
440
                    clipViewOnTheRight(bound, w, right);
441
                    //Except if there's an intersection with the left view
442
                    Rect leftBound = bounds.get(i - 1);
443
                    //Intersection
444
                    if (bound.left - mTitlePadding < leftBound.right) {
445
                        bound.left = (int) (leftBound.right + mTitlePadding);
446
                        bound.right = bound.left + w;
447
                    }
448
                }
449
            }
450
        }
451
 
452
        //Now draw views
453
        int colorTextAlpha = mColorText >>> 24;
454
        for (int i = 0; i < count; i++) {
455
            //Get the title
456
            Rect bound = bounds.get(i);
457
            //Only if one side is visible
458
            if ((bound.left > left && bound.left < right) || (bound.right > left && bound.right < right)) {
459
                final boolean currentPage = (i == page);
460
                final CharSequence pageTitle = getTitle(i);
461
 
462
                //Only set bold if we are within bounds
463
                mPaintText.setFakeBoldText(currentPage && currentBold && mBoldText);
464
 
465
                //Draw text as unselected
466
                mPaintText.setColor(mColorText);
467
                if(currentPage && currentSelected) {
468
                    //Fade out/in unselected text as the selected text fades in/out
469
                    mPaintText.setAlpha(colorTextAlpha - (int)(colorTextAlpha * selectedPercent));
470
                }
471
 
472
                //Except if there's an intersection with the right view
473
                if (i < boundsSize - 1)  {
474
                    Rect rightBound = bounds.get(i + 1);
475
                    //Intersection
476
                    if (bound.right + mTitlePadding > rightBound.left) {
477
                        int w = bound.right - bound.left;
478
                        bound.left = (int) (rightBound.left - w - mTitlePadding);
479
                        bound.right = bound.left + w;
480
                    }
481
                }
482
                canvas.drawText(pageTitle, 0, pageTitle.length(), bound.left, bound.bottom + mTopPadding, mPaintText);
483
 
484
                //If we are within the selected bounds draw the selected text
485
                if (currentPage && currentSelected) {
486
                    mPaintText.setColor(mColorSelected);
487
                    mPaintText.setAlpha((int)((mColorSelected >>> 24) * selectedPercent));
488
                    canvas.drawText(pageTitle, 0, pageTitle.length(), bound.left, bound.bottom + mTopPadding, mPaintText);
489
                }
490
            }
491
        }
492
 
493
        //If we want the line on the top change height to zero and invert the line height to trick the drawing code
494
        float footerLineHeight = mFooterLineHeight;
495
        float footerIndicatorLineHeight = mFooterIndicatorHeight;
496
        if (mLinePosition == LinePosition.Top) {
497
            height = 0;
498
            footerLineHeight = -footerLineHeight;
499
            footerIndicatorLineHeight = -footerIndicatorLineHeight;
500
        }
501
 
502
        //Draw the footer line
503
        mPath.reset();
504
        mPath.moveTo(0, height - footerLineHeight / 2f);
505
        mPath.lineTo(width, height - footerLineHeight / 2f);
506
        mPath.close();
507
        canvas.drawPath(mPath, mPaintFooterLine);
508
 
509
        float heightMinusLine = height - footerLineHeight;
510
        switch (mFooterIndicatorStyle) {
511
            case Triangle:
512
                mPath.reset();
513
                mPath.moveTo(halfWidth, heightMinusLine - footerIndicatorLineHeight);
514
                mPath.lineTo(halfWidth + footerIndicatorLineHeight, heightMinusLine);
515
                mPath.lineTo(halfWidth - footerIndicatorLineHeight, heightMinusLine);
516
                mPath.close();
517
                canvas.drawPath(mPath, mPaintFooterIndicator);
518
                break;
519
 
520
            case Underline:
521
                if (!currentSelected || page >= boundsSize) {
522
                    break;
523
                }
524
 
525
                Rect underlineBounds = bounds.get(page);
526
                final float rightPlusPadding = underlineBounds.right + mFooterIndicatorUnderlinePadding;
527
                final float leftMinusPadding = underlineBounds.left - mFooterIndicatorUnderlinePadding;
528
                final float heightMinusLineMinusIndicator = heightMinusLine - footerIndicatorLineHeight;
529
 
530
                mPath.reset();
531
                mPath.moveTo(leftMinusPadding, heightMinusLine);
532
                mPath.lineTo(rightPlusPadding, heightMinusLine);
533
                mPath.lineTo(rightPlusPadding, heightMinusLineMinusIndicator);
534
                mPath.lineTo(leftMinusPadding, heightMinusLineMinusIndicator);
535
                mPath.close();
536
 
537
                mPaintFooterIndicator.setAlpha((int)(0xFF * selectedPercent));
538
                canvas.drawPath(mPath, mPaintFooterIndicator);
539
                mPaintFooterIndicator.setAlpha(0xFF);
540
                break;
541
        }
542
    }
543
 
544
    public boolean onTouchEvent(android.view.MotionEvent ev) {
545
        if (super.onTouchEvent(ev)) {
546
            return true;
547
        }
548
        if ((mViewPager == null) || (mViewPager.getAdapter().getCount() == 0)) {
549
            return false;
550
        }
551
 
552
        final int action = ev.getAction() & MotionEventCompat.ACTION_MASK;
553
        switch (action) {
554
            case MotionEvent.ACTION_DOWN:
555
                mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
556
                mLastMotionX = ev.getX();
557
                break;
558
 
559
            case MotionEvent.ACTION_MOVE: {
560
                final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
561
                final float x = MotionEventCompat.getX(ev, activePointerIndex);
562
                final float deltaX = x - mLastMotionX;
563
 
564
                if (!mIsDragging) {
565
                    if (Math.abs(deltaX) > mTouchSlop) {
566
                        mIsDragging = true;
567
                    }
568
                }
569
 
570
                if (mIsDragging) {
571
                    mLastMotionX = x;
572
                    if (mViewPager.isFakeDragging() || mViewPager.beginFakeDrag()) {
573
                        mViewPager.fakeDragBy(deltaX);
574
                    }
575
                }
576
 
577
                break;
578
            }
579
 
580
            case MotionEvent.ACTION_CANCEL:
581
            case MotionEvent.ACTION_UP:
582
                if (!mIsDragging) {
583
                    final int count = mViewPager.getAdapter().getCount();
584
                    final int width = getWidth();
585
                    final float halfWidth = width / 2f;
586
                    final float sixthWidth = width / 6f;
587
                    final float leftThird = halfWidth - sixthWidth;
588
                    final float rightThird = halfWidth + sixthWidth;
589
                    final float eventX = ev.getX();
590
 
591
                    if (eventX < leftThird) {
592
                        if (mCurrentPage > 0) {
593
                            if (action != MotionEvent.ACTION_CANCEL) {
594
                                mViewPager.setCurrentItem(mCurrentPage - 1);
595
                            }
596
                            return true;
597
                        }
598
                    } else if (eventX > rightThird) {
599
                        if (mCurrentPage < count - 1) {
600
                            if (action != MotionEvent.ACTION_CANCEL) {
601
                                mViewPager.setCurrentItem(mCurrentPage + 1);
602
                            }
603
                            return true;
604
                        }
605
                    } else {
606
                        //Middle third
607
                        if (mCenterItemClickListener != null && action != MotionEvent.ACTION_CANCEL) {
608
                            mCenterItemClickListener.onCenterItemClick(mCurrentPage);
609
                        }
610
                    }
611
                }
612
 
613
                mIsDragging = false;
614
                mActivePointerId = INVALID_POINTER;
615
                if (mViewPager.isFakeDragging()) mViewPager.endFakeDrag();
616
                break;
617
 
618
            case MotionEventCompat.ACTION_POINTER_DOWN: {
619
                final int index = MotionEventCompat.getActionIndex(ev);
620
                mLastMotionX = MotionEventCompat.getX(ev, index);
621
                mActivePointerId = MotionEventCompat.getPointerId(ev, index);
622
                break;
623
            }
624
 
625
            case MotionEventCompat.ACTION_POINTER_UP:
626
                final int pointerIndex = MotionEventCompat.getActionIndex(ev);
627
                final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex);
628
                if (pointerId == mActivePointerId) {
629
                    final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
630
                    mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex);
631
                }
632
                mLastMotionX = MotionEventCompat.getX(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId));
633
                break;
634
        }
635
 
636
        return true;
637
    }
638
 
639
    /**
640
     * Set bounds for the right textView including clip padding.
641
     *
642
     * @param curViewBound
643
     *            current bounds.
644
     * @param curViewWidth
645
     *            width of the view.
646
     */
647
    private void clipViewOnTheRight(Rect curViewBound, float curViewWidth, int right) {
648
        curViewBound.right = (int) (right - mClipPadding);
649
        curViewBound.left = (int) (curViewBound.right - curViewWidth);
650
    }
651
 
652
    /**
653
     * Set bounds for the left textView including clip padding.
654
     *
655
     * @param curViewBound
656
     *            current bounds.
657
     * @param curViewWidth
658
     *            width of the view.
659
     */
660
    private void clipViewOnTheLeft(Rect curViewBound, float curViewWidth, int left) {
661
        curViewBound.left = (int) (left + mClipPadding);
662
        curViewBound.right = (int) (mClipPadding + curViewWidth);
663
    }
664
 
665
    /**
666
     * Calculate views bounds and scroll them according to the current index
667
     *
668
     * @param paint
669
     * @return
670
     */
671
    private ArrayList<Rect> calculateAllBounds(Paint paint) {
672
        ArrayList<Rect> list = new ArrayList<Rect>();
673
        //For each views (If no values then add a fake one)
674
        final int count = mViewPager.getAdapter().getCount();
675
        final int width = getWidth();
676
        final int halfWidth = width / 2;
677
        for (int i = 0; i < count; i++) {
678
            Rect bounds = calcBounds(i, paint);
679
            int w = bounds.right - bounds.left;
680
            int h = bounds.bottom - bounds.top;
681
            bounds.left = (int)(halfWidth - (w / 2f) + ((i - mCurrentPage - mPageOffset) * width));
682
            bounds.right = bounds.left + w;
683
            bounds.top = 0;
684
            bounds.bottom = h;
685
            list.add(bounds);
686
        }
687
 
688
        return list;
689
    }
690
 
691
    /**
692
     * Calculate the bounds for a view's title
693
     *
694
     * @param index
695
     * @param paint
696
     * @return
697
     */
698
    private Rect calcBounds(int index, Paint paint) {
699
        //Calculate the text bounds
700
        Rect bounds = new Rect();
701
        CharSequence title = getTitle(index);
702
        bounds.right = (int) paint.measureText(title, 0, title.length());
703
        bounds.bottom = (int) (paint.descent() - paint.ascent());
704
        return bounds;
705
    }
706
 
707
    @Override
708
    public void setViewPager(ViewPager view) {
709
        if (mViewPager == view) {
710
            return;
711
        }
712
        if (mViewPager != null) {
713
            mViewPager.setOnPageChangeListener(null);
714
        }
715
        if (view.getAdapter() == null) {
716
            throw new IllegalStateException("ViewPager does not have adapter instance.");
717
        }
718
        mViewPager = view;
719
        mViewPager.setOnPageChangeListener(this);
720
        invalidate();
721
    }
722
 
723
    @Override
724
    public void setViewPager(ViewPager view, int initialPosition) {
725
        setViewPager(view);
726
        setCurrentItem(initialPosition);
727
    }
728
 
729
    @Override
730
    public void notifyDataSetChanged() {
731
        invalidate();
732
    }
733
 
734
    /**
735
     * Set a callback listener for the center item click.
736
     *
737
     * @param listener Callback instance.
738
     */
739
    public void setOnCenterItemClickListener(OnCenterItemClickListener listener) {
740
        mCenterItemClickListener = listener;
741
    }
742
 
743
    @Override
744
    public void setCurrentItem(int item) {
745
        if (mViewPager == null) {
746
            throw new IllegalStateException("ViewPager has not been bound.");
747
        }
748
        mViewPager.setCurrentItem(item);
749
        mCurrentPage = item;
750
        invalidate();
751
    }
752
 
753
    @Override
754
    public void onPageScrollStateChanged(int state) {
755
        mScrollState = state;
756
 
757
        if (mListener != null) {
758
            mListener.onPageScrollStateChanged(state);
759
        }
760
    }
761
 
762
    @Override
763
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
764
        mCurrentPage = position;
765
        mPageOffset = positionOffset;
766
        invalidate();
767
 
768
        if (mListener != null) {
769
            mListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
770
        }
771
    }
772
 
773
    @Override
774
    public void onPageSelected(int position) {
775
        if (mScrollState == ViewPager.SCROLL_STATE_IDLE) {
776
            mCurrentPage = position;
777
            invalidate();
778
        }
779
 
780
        if (mListener != null) {
781
            mListener.onPageSelected(position);
782
        }
783
    }
784
 
785
    @Override
786
    public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
787
        mListener = listener;
788
    }
789
 
790
    @Override
791
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
792
        //Measure our width in whatever mode specified
793
        final int measuredWidth = MeasureSpec.getSize(widthMeasureSpec);
794
 
795
        //Determine our height
796
        float height;
797
        final int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
798
        if (heightSpecMode == MeasureSpec.EXACTLY) {
799
            //We were told how big to be
800
            height = MeasureSpec.getSize(heightMeasureSpec);
801
        } else {
802
            //Calculate the text bounds
803
            mBounds.setEmpty();
804
            mBounds.bottom = (int) (mPaintText.descent() - mPaintText.ascent());
805
            height = mBounds.bottom - mBounds.top + mFooterLineHeight + mFooterPadding + mTopPadding;
806
            if (mFooterIndicatorStyle != IndicatorStyle.None) {
807
                height += mFooterIndicatorHeight;
808
            }
809
        }
810
        final int measuredHeight = (int)height;
811
 
812
        setMeasuredDimension(measuredWidth, measuredHeight);
813
    }
814
 
815
    @Override
816
    public void onRestoreInstanceState(Parcelable state) {
817
        SavedState savedState = (SavedState)state;
818
        super.onRestoreInstanceState(savedState.getSuperState());
819
        mCurrentPage = savedState.currentPage;
820
        requestLayout();
821
    }
822
 
823
    @Override
824
    public Parcelable onSaveInstanceState() {
825
        Parcelable superState = super.onSaveInstanceState();
826
        SavedState savedState = new SavedState(superState);
827
        savedState.currentPage = mCurrentPage;
828
        return savedState;
829
    }
830
 
831
    static class SavedState extends BaseSavedState {
832
        int currentPage;
833
 
834
        public SavedState(Parcelable superState) {
835
            super(superState);
836
        }
837
 
838
        private SavedState(Parcel in) {
839
            super(in);
840
            currentPage = in.readInt();
841
        }
842
 
843
        @Override
844
        public void writeToParcel(Parcel dest, int flags) {
845
            super.writeToParcel(dest, flags);
846
            dest.writeInt(currentPage);
847
        }
848
 
849
        @SuppressWarnings("UnusedDeclaration")
850
        public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() {
851
            @Override
852
            public SavedState createFromParcel(Parcel in) {
853
                return new SavedState(in);
854
            }
855
 
856
            @Override
857
            public SavedState[] newArray(int size) {
858
                return new SavedState[size];
859
            }
860
        };
861
    }
862
 
863
    private CharSequence getTitle(int i) {
864
        CharSequence title = mViewPager.getAdapter().getPageTitle(i);
865
        if (title == null) {
866
            title = EMPTY_TITLE;
867
        }
868
        return title;
869
    }
870
}