LinePageIndicator.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. /*
  2. * Copyright (C) 2012 Jake Wharton
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.viewpagerindicator;
  17. import android.content.Context;
  18. import android.content.res.Resources;
  19. import android.content.res.TypedArray;
  20. import android.graphics.Canvas;
  21. import android.graphics.Paint;
  22. import android.graphics.drawable.Drawable;
  23. import android.os.Parcel;
  24. import android.os.Parcelable;
  25. import android.support.v4.view.MotionEventCompat;
  26. import android.support.v4.view.ViewConfigurationCompat;
  27. import android.support.v4.view.ViewPager;
  28. import android.util.AttributeSet;
  29. import android.view.MotionEvent;
  30. import android.view.View;
  31. import android.view.ViewConfiguration;
  32. /**
  33. * Draws a line for each page. The current page line is colored differently
  34. * than the unselected page lines.
  35. */
  36. public class LinePageIndicator extends View implements PageIndicator {
  37. private static final int INVALID_POINTER = -1;
  38. private final Paint mPaintUnselected = new Paint(Paint.ANTI_ALIAS_FLAG);
  39. private final Paint mPaintSelected = new Paint(Paint.ANTI_ALIAS_FLAG);
  40. private ViewPager mViewPager;
  41. private ViewPager.OnPageChangeListener mListener;
  42. private int mCurrentPage;
  43. private boolean mCentered;
  44. private float mLineWidth;
  45. private float mGapWidth;
  46. private int mTouchSlop;
  47. private float mLastMotionX = -1;
  48. private int mActivePointerId = INVALID_POINTER;
  49. private boolean mIsDragging;
  50. public LinePageIndicator(Context context) {
  51. this(context, null);
  52. }
  53. public LinePageIndicator(Context context, AttributeSet attrs) {
  54. this(context, attrs, R.attr.vpiLinePageIndicatorStyle);
  55. }
  56. public LinePageIndicator(Context context, AttributeSet attrs, int defStyle) {
  57. super(context, attrs, defStyle);
  58. if (isInEditMode()) return;
  59. final Resources res = getResources();
  60. //Load defaults from resources
  61. final int defaultSelectedColor = res.getColor(R.color.default_line_indicator_selected_color);
  62. final int defaultUnselectedColor = res.getColor(R.color.default_line_indicator_unselected_color);
  63. final float defaultLineWidth = res.getDimension(R.dimen.default_line_indicator_line_width);
  64. final float defaultGapWidth = res.getDimension(R.dimen.default_line_indicator_gap_width);
  65. final float defaultStrokeWidth = res.getDimension(R.dimen.default_line_indicator_stroke_width);
  66. final boolean defaultCentered = res.getBoolean(R.bool.default_line_indicator_centered);
  67. //Retrieve styles attributes
  68. TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.LinePageIndicator, defStyle, 0);
  69. mCentered = a.getBoolean(R.styleable.LinePageIndicator_centered, defaultCentered);
  70. mLineWidth = a.getDimension(R.styleable.LinePageIndicator_lineWidth, defaultLineWidth);
  71. mGapWidth = a.getDimension(R.styleable.LinePageIndicator_gapWidth, defaultGapWidth);
  72. setStrokeWidth(a.getDimension(R.styleable.LinePageIndicator_strokeWidth, defaultStrokeWidth));
  73. mPaintUnselected.setColor(a.getColor(R.styleable.LinePageIndicator_unselectedColor, defaultUnselectedColor));
  74. mPaintSelected.setColor(a.getColor(R.styleable.LinePageIndicator_selectedColor, defaultSelectedColor));
  75. Drawable background = a.getDrawable(R.styleable.LinePageIndicator_android_background);
  76. if (background != null) {
  77. setBackgroundDrawable(background);
  78. }
  79. a.recycle();
  80. final ViewConfiguration configuration = ViewConfiguration.get(context);
  81. mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration);
  82. }
  83. public void setCentered(boolean centered) {
  84. mCentered = centered;
  85. invalidate();
  86. }
  87. public boolean isCentered() {
  88. return mCentered;
  89. }
  90. public void setUnselectedColor(int unselectedColor) {
  91. mPaintUnselected.setColor(unselectedColor);
  92. invalidate();
  93. }
  94. public int getUnselectedColor() {
  95. return mPaintUnselected.getColor();
  96. }
  97. public void setSelectedColor(int selectedColor) {
  98. mPaintSelected.setColor(selectedColor);
  99. invalidate();
  100. }
  101. public int getSelectedColor() {
  102. return mPaintSelected.getColor();
  103. }
  104. public void setLineWidth(float lineWidth) {
  105. mLineWidth = lineWidth;
  106. invalidate();
  107. }
  108. public float getLineWidth() {
  109. return mLineWidth;
  110. }
  111. public void setStrokeWidth(float lineHeight) {
  112. mPaintSelected.setStrokeWidth(lineHeight);
  113. mPaintUnselected.setStrokeWidth(lineHeight);
  114. invalidate();
  115. }
  116. public float getStrokeWidth() {
  117. return mPaintSelected.getStrokeWidth();
  118. }
  119. public void setGapWidth(float gapWidth) {
  120. mGapWidth = gapWidth;
  121. invalidate();
  122. }
  123. public float getGapWidth() {
  124. return mGapWidth;
  125. }
  126. @Override
  127. protected void onDraw(Canvas canvas) {
  128. super.onDraw(canvas);
  129. if (mViewPager == null) {
  130. return;
  131. }
  132. final int count = mViewPager.getAdapter().getCount();
  133. if (count == 0) {
  134. return;
  135. }
  136. if (mCurrentPage >= count) {
  137. setCurrentItem(count - 1);
  138. return;
  139. }
  140. final float lineWidthAndGap = mLineWidth + mGapWidth;
  141. final float indicatorWidth = (count * lineWidthAndGap) - mGapWidth;
  142. final float paddingTop = getPaddingTop();
  143. final float paddingLeft = getPaddingLeft();
  144. final float paddingRight = getPaddingRight();
  145. float verticalOffset = paddingTop + ((getHeight() - paddingTop - getPaddingBottom()) / 2.0f);
  146. float horizontalOffset = paddingLeft;
  147. if (mCentered) {
  148. horizontalOffset += ((getWidth() - paddingLeft - paddingRight) / 2.0f) - (indicatorWidth / 2.0f);
  149. }
  150. //Draw stroked circles
  151. for (int i = 0; i < count; i++) {
  152. float dx1 = horizontalOffset + (i * lineWidthAndGap);
  153. float dx2 = dx1 + mLineWidth;
  154. canvas.drawLine(dx1, verticalOffset, dx2, verticalOffset, (i == mCurrentPage) ? mPaintSelected : mPaintUnselected);
  155. }
  156. }
  157. public boolean onTouchEvent(android.view.MotionEvent ev) {
  158. if (super.onTouchEvent(ev)) {
  159. return true;
  160. }
  161. if ((mViewPager == null) || (mViewPager.getAdapter().getCount() == 0)) {
  162. return false;
  163. }
  164. final int action = ev.getAction() & MotionEventCompat.ACTION_MASK;
  165. switch (action) {
  166. case MotionEvent.ACTION_DOWN:
  167. mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
  168. mLastMotionX = ev.getX();
  169. break;
  170. case MotionEvent.ACTION_MOVE: {
  171. final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
  172. final float x = MotionEventCompat.getX(ev, activePointerIndex);
  173. final float deltaX = x - mLastMotionX;
  174. if (!mIsDragging) {
  175. if (Math.abs(deltaX) > mTouchSlop) {
  176. mIsDragging = true;
  177. }
  178. }
  179. if (mIsDragging) {
  180. mLastMotionX = x;
  181. if (mViewPager.isFakeDragging() || mViewPager.beginFakeDrag()) {
  182. mViewPager.fakeDragBy(deltaX);
  183. }
  184. }
  185. break;
  186. }
  187. case MotionEvent.ACTION_CANCEL:
  188. case MotionEvent.ACTION_UP:
  189. if (!mIsDragging) {
  190. final int count = mViewPager.getAdapter().getCount();
  191. final int width = getWidth();
  192. final float halfWidth = width / 2f;
  193. final float sixthWidth = width / 6f;
  194. if ((mCurrentPage > 0) && (ev.getX() < halfWidth - sixthWidth)) {
  195. if (action != MotionEvent.ACTION_CANCEL) {
  196. mViewPager.setCurrentItem(mCurrentPage - 1);
  197. }
  198. return true;
  199. } else if ((mCurrentPage < count - 1) && (ev.getX() > halfWidth + sixthWidth)) {
  200. if (action != MotionEvent.ACTION_CANCEL) {
  201. mViewPager.setCurrentItem(mCurrentPage + 1);
  202. }
  203. return true;
  204. }
  205. }
  206. mIsDragging = false;
  207. mActivePointerId = INVALID_POINTER;
  208. if (mViewPager.isFakeDragging()) mViewPager.endFakeDrag();
  209. break;
  210. case MotionEventCompat.ACTION_POINTER_DOWN: {
  211. final int index = MotionEventCompat.getActionIndex(ev);
  212. mLastMotionX = MotionEventCompat.getX(ev, index);
  213. mActivePointerId = MotionEventCompat.getPointerId(ev, index);
  214. break;
  215. }
  216. case MotionEventCompat.ACTION_POINTER_UP:
  217. final int pointerIndex = MotionEventCompat.getActionIndex(ev);
  218. final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex);
  219. if (pointerId == mActivePointerId) {
  220. final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
  221. mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex);
  222. }
  223. mLastMotionX = MotionEventCompat.getX(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId));
  224. break;
  225. }
  226. return true;
  227. }
  228. @Override
  229. public void setViewPager(ViewPager viewPager) {
  230. if (mViewPager == viewPager) {
  231. return;
  232. }
  233. if (mViewPager != null) {
  234. //Clear us from the old pager.
  235. mViewPager.setOnPageChangeListener(null);
  236. }
  237. if (viewPager.getAdapter() == null) {
  238. throw new IllegalStateException("ViewPager does not have adapter instance.");
  239. }
  240. mViewPager = viewPager;
  241. mViewPager.setOnPageChangeListener(this);
  242. invalidate();
  243. }
  244. @Override
  245. public void setViewPager(ViewPager view, int initialPosition) {
  246. setViewPager(view);
  247. setCurrentItem(initialPosition);
  248. }
  249. @Override
  250. public void setCurrentItem(int item) {
  251. if (mViewPager == null) {
  252. throw new IllegalStateException("ViewPager has not been bound.");
  253. }
  254. mViewPager.setCurrentItem(item);
  255. mCurrentPage = item;
  256. invalidate();
  257. }
  258. @Override
  259. public void notifyDataSetChanged() {
  260. invalidate();
  261. }
  262. @Override
  263. public void onPageScrollStateChanged(int state) {
  264. if (mListener != null) {
  265. mListener.onPageScrollStateChanged(state);
  266. }
  267. }
  268. @Override
  269. public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
  270. if (mListener != null) {
  271. mListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
  272. }
  273. }
  274. @Override
  275. public void onPageSelected(int position) {
  276. mCurrentPage = position;
  277. invalidate();
  278. if (mListener != null) {
  279. mListener.onPageSelected(position);
  280. }
  281. }
  282. @Override
  283. public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
  284. mListener = listener;
  285. }
  286. @Override
  287. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  288. setMeasuredDimension(measureWidth(widthMeasureSpec), measureHeight(heightMeasureSpec));
  289. }
  290. /**
  291. * Determines the width of this view
  292. *
  293. * @param measureSpec
  294. * A measureSpec packed into an int
  295. * @return The width of the view, honoring constraints from measureSpec
  296. */
  297. private int measureWidth(int measureSpec) {
  298. float result;
  299. int specMode = MeasureSpec.getMode(measureSpec);
  300. int specSize = MeasureSpec.getSize(measureSpec);
  301. if ((specMode == MeasureSpec.EXACTLY) || (mViewPager == null)) {
  302. //We were told how big to be
  303. result = specSize;
  304. } else {
  305. //Calculate the width according the views count
  306. final int count = mViewPager.getAdapter().getCount();
  307. result = getPaddingLeft() + getPaddingRight() + (count * mLineWidth) + ((count - 1) * mGapWidth);
  308. //Respect AT_MOST value if that was what is called for by measureSpec
  309. if (specMode == MeasureSpec.AT_MOST) {
  310. result = Math.min(result, specSize);
  311. }
  312. }
  313. return (int)Math.ceil(result);
  314. }
  315. /**
  316. * Determines the height of this view
  317. *
  318. * @param measureSpec
  319. * A measureSpec packed into an int
  320. * @return The height of the view, honoring constraints from measureSpec
  321. */
  322. private int measureHeight(int measureSpec) {
  323. float result;
  324. int specMode = MeasureSpec.getMode(measureSpec);
  325. int specSize = MeasureSpec.getSize(measureSpec);
  326. if (specMode == MeasureSpec.EXACTLY) {
  327. //We were told how big to be
  328. result = specSize;
  329. } else {
  330. //Measure the height
  331. result = mPaintSelected.getStrokeWidth() + getPaddingTop() + getPaddingBottom();
  332. //Respect AT_MOST value if that was what is called for by measureSpec
  333. if (specMode == MeasureSpec.AT_MOST) {
  334. result = Math.min(result, specSize);
  335. }
  336. }
  337. return (int)Math.ceil(result);
  338. }
  339. @Override
  340. public void onRestoreInstanceState(Parcelable state) {
  341. SavedState savedState = (SavedState)state;
  342. super.onRestoreInstanceState(savedState.getSuperState());
  343. mCurrentPage = savedState.currentPage;
  344. requestLayout();
  345. }
  346. @Override
  347. public Parcelable onSaveInstanceState() {
  348. Parcelable superState = super.onSaveInstanceState();
  349. SavedState savedState = new SavedState(superState);
  350. savedState.currentPage = mCurrentPage;
  351. return savedState;
  352. }
  353. static class SavedState extends BaseSavedState {
  354. int currentPage;
  355. public SavedState(Parcelable superState) {
  356. super(superState);
  357. }
  358. private SavedState(Parcel in) {
  359. super(in);
  360. currentPage = in.readInt();
  361. }
  362. @Override
  363. public void writeToParcel(Parcel dest, int flags) {
  364. super.writeToParcel(dest, flags);
  365. dest.writeInt(currentPage);
  366. }
  367. @SuppressWarnings("UnusedDeclaration")
  368. public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() {
  369. @Override
  370. public SavedState createFromParcel(Parcel in) {
  371. return new SavedState(in);
  372. }
  373. @Override
  374. public SavedState[] newArray(int size) {
  375. return new SavedState[size];
  376. }
  377. };
  378. }
  379. }