b3c3eb8e5ddd8664431949152c5a466ff1882d43.svn-base 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. package com.hjq.widget;
  2. import android.annotation.SuppressLint;
  3. import android.content.Context;
  4. import android.content.res.TypedArray;
  5. import android.graphics.Canvas;
  6. import android.graphics.Color;
  7. import android.graphics.Paint;
  8. import android.graphics.Path;
  9. import android.graphics.RadialGradient;
  10. import android.graphics.RectF;
  11. import android.graphics.Shader;
  12. import android.os.Build;
  13. import android.os.Parcel;
  14. import android.os.Parcelable;
  15. import android.support.annotation.Nullable;
  16. import android.support.annotation.RequiresApi;
  17. import android.util.AttributeSet;
  18. import android.util.TypedValue;
  19. import android.view.MotionEvent;
  20. import android.view.View;
  21. import android.view.animation.AccelerateInterpolator;
  22. /**
  23. * desc : 开关按钮
  24. */
  25. public final class SwitchButton extends View {
  26. private static final int STATE_SWITCH_OFF = 1;
  27. private static final int STATE_SWITCH_OFF2 = 2;
  28. private static final int STATE_SWITCH_ON = 3;
  29. private static final int STATE_SWITCH_ON2 = 4;
  30. private final AccelerateInterpolator mInterpolator = new AccelerateInterpolator(2);
  31. private final Paint mPaint = new Paint();
  32. private final Path mBackgroundPath = new Path();
  33. private final Path mBarPath = new Path();
  34. private final RectF mBound = new RectF();
  35. private float mAnim1, mAnim2;
  36. private RadialGradient mShadowGradient;
  37. protected float mAspectRatio = 0.68f; // 按钮宽高形状比率(0,1] 不推荐大幅度调整
  38. protected float mAnimationSpeed = 0.1f; // (0,1]
  39. private int mLastCheckedState; // 上一个选中状态
  40. private int mCheckedState; // 当前的选中状态
  41. private boolean isCanVisibleDrawing = false;
  42. protected boolean isShadow; // 是否显示按钮阴影
  43. protected boolean mChecked; // 是否选中
  44. protected int mAccentColor = 0xFF4BD763; // 开启状态背景色
  45. protected int mPrimaryDarkColor = 0xFF3AC652; // 开启状态按钮描边色
  46. protected int mOffColor = 0xFFE3E3E3; // 关闭状态描边色
  47. protected int mOffDarkColor = 0xFFBFBFBF; // 关闭状态按钮描边色
  48. protected int mShadowColor = 0xFF333333; // 按钮阴影色
  49. private OnCheckedChangeListener mListener; // 监听器
  50. private float mRight;
  51. private float mCenterX, mCenterY;
  52. private float mScale;
  53. private float mOffset;
  54. private float mRadius, mStrokeWidth;
  55. private float mWidth;
  56. private float mLeft;
  57. private float bRight;
  58. private float mOnLeftX, mOn2LeftX, mOff2LeftX, mOffLeftX;
  59. private float mShadowReservedHeight;
  60. public SwitchButton(Context context) {
  61. super(context);
  62. initialize(null);
  63. }
  64. public SwitchButton(Context context, @Nullable AttributeSet attrs) {
  65. super(context, attrs);
  66. initialize(attrs);
  67. }
  68. public SwitchButton(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
  69. super(context, attrs, defStyleAttr);
  70. initialize(attrs);
  71. }
  72. @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
  73. public SwitchButton(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
  74. super(context, attrs, defStyleAttr, defStyleRes);
  75. initialize(attrs);
  76. }
  77. private void initialize(AttributeSet attrs) {
  78. setLayerType(LAYER_TYPE_SOFTWARE, null);
  79. TypedArray array = getContext().obtainStyledAttributes(attrs, R.styleable.SwitchButton);
  80. mChecked = array.getBoolean(R.styleable.SwitchButton_android_checked, mChecked);
  81. setEnabled(array.getBoolean(R.styleable.SwitchButton_android_enabled, isEnabled()));
  82. mLastCheckedState = mCheckedState = mChecked ? STATE_SWITCH_ON : STATE_SWITCH_OFF;
  83. array.recycle();
  84. }
  85. @Override
  86. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  87. switch (MeasureSpec.getMode(widthMeasureSpec)) {
  88. case MeasureSpec.AT_MOST:
  89. case MeasureSpec.UNSPECIFIED:
  90. widthMeasureSpec = MeasureSpec.makeMeasureSpec((int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 56, getResources().getDisplayMetrics())
  91. + getPaddingLeft() + getPaddingRight()), MeasureSpec.EXACTLY);
  92. break;
  93. case MeasureSpec.EXACTLY:
  94. break;
  95. }
  96. switch (MeasureSpec.getMode(heightMeasureSpec)) {
  97. case MeasureSpec.AT_MOST:
  98. case MeasureSpec.UNSPECIFIED:
  99. heightMeasureSpec = MeasureSpec.makeMeasureSpec((int) (MeasureSpec.getSize(widthMeasureSpec) * mAspectRatio)
  100. + getPaddingTop() + getPaddingBottom(), MeasureSpec.EXACTLY);
  101. break;
  102. case MeasureSpec.EXACTLY:
  103. break;
  104. }
  105. setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
  106. }
  107. @Override
  108. protected void onSizeChanged(int w, int h, int oldw, int oldh) {
  109. isCanVisibleDrawing = w > getPaddingLeft() + getPaddingRight() && h > getPaddingTop() + getPaddingBottom();
  110. if (isCanVisibleDrawing) {
  111. int actuallyDrawingAreaWidth = w - getPaddingLeft() - getPaddingRight();
  112. int actuallyDrawingAreaHeight = h - getPaddingTop() - getPaddingBottom();
  113. int actuallyDrawingAreaLeft;
  114. int actuallyDrawingAreaRight;
  115. int actuallyDrawingAreaTop;
  116. int actuallyDrawingAreaBottom;
  117. if (actuallyDrawingAreaWidth * mAspectRatio < actuallyDrawingAreaHeight) {
  118. actuallyDrawingAreaLeft = getPaddingLeft();
  119. actuallyDrawingAreaRight = w - getPaddingRight();
  120. int heightExtraSize = (int) (actuallyDrawingAreaHeight - actuallyDrawingAreaWidth * mAspectRatio);
  121. actuallyDrawingAreaTop = getPaddingTop() + heightExtraSize / 2;
  122. actuallyDrawingAreaBottom = getHeight() - getPaddingBottom() - heightExtraSize / 2;
  123. } else {
  124. int widthExtraSize = (int) (actuallyDrawingAreaWidth - actuallyDrawingAreaHeight / mAspectRatio);
  125. actuallyDrawingAreaLeft = getPaddingLeft() + widthExtraSize / 2;
  126. actuallyDrawingAreaRight = getWidth() - getPaddingRight() - widthExtraSize / 2;
  127. actuallyDrawingAreaTop = getPaddingTop();
  128. actuallyDrawingAreaBottom = getHeight() - getPaddingBottom();
  129. }
  130. mShadowReservedHeight = (int) ((actuallyDrawingAreaBottom - actuallyDrawingAreaTop) * 0.07f);
  131. float left = actuallyDrawingAreaLeft;
  132. float top = actuallyDrawingAreaTop + mShadowReservedHeight;
  133. mRight = actuallyDrawingAreaRight;
  134. float bottom = actuallyDrawingAreaBottom - mShadowReservedHeight;
  135. float sHeight = bottom - top;
  136. mCenterX = (mRight + left) / 2;
  137. mCenterY = (bottom + top) / 2;
  138. mLeft = left;
  139. mWidth = bottom - top;
  140. bRight = left + mWidth;
  141. final float halfHeightOfS = mWidth / 2; // OfB
  142. mRadius = halfHeightOfS * 0.95f;
  143. mOffset = mRadius * 0.2f; // offset of switching
  144. mStrokeWidth = (halfHeightOfS - mRadius) * 2;
  145. mOnLeftX = mRight - mWidth;
  146. mOn2LeftX = mOnLeftX - mOffset;
  147. mOffLeftX = left;
  148. mOff2LeftX = mOffLeftX + mOffset;
  149. mScale = 1 - mStrokeWidth / sHeight;
  150. mBackgroundPath.reset();
  151. RectF bound = new RectF();
  152. bound.top = top;
  153. bound.bottom = bottom;
  154. bound.left = left;
  155. bound.right = left + sHeight;
  156. mBackgroundPath.arcTo(bound, 90, 180);
  157. bound.left = mRight - sHeight;
  158. bound.right = mRight;
  159. mBackgroundPath.arcTo(bound, 270, 180);
  160. mBackgroundPath.close();
  161. mBound.left = mLeft;
  162. mBound.right = bRight;
  163. mBound.top = top + mStrokeWidth / 2; // bTop = sTop
  164. mBound.bottom = bottom - mStrokeWidth / 2; // bBottom = sBottom
  165. float bCenterX = (bRight + mLeft) / 2;
  166. float bCenterY = (bottom + top) / 2;
  167. int red = mShadowColor >> 16 & 0xFF;
  168. int green = mShadowColor >> 8 & 0xFF;
  169. int blue = mShadowColor & 0xFF;
  170. mShadowGradient = new RadialGradient(bCenterX, bCenterY, mRadius, Color.argb(200, red, green, blue),
  171. Color.argb(25, red, green, blue), Shader.TileMode.CLAMP);
  172. }
  173. }
  174. private void calcBPath(float percent) {
  175. mBarPath.reset();
  176. mBound.left = mLeft + mStrokeWidth / 2;
  177. mBound.right = bRight - mStrokeWidth / 2;
  178. mBarPath.arcTo(mBound, 90, 180);
  179. mBound.left = mLeft + percent * mOffset + mStrokeWidth / 2;
  180. mBound.right = bRight + percent * mOffset - mStrokeWidth / 2;
  181. mBarPath.arcTo(mBound, 270, 180);
  182. mBarPath.close();
  183. }
  184. private float calcBTranslate(float percent) {
  185. float result = 0;
  186. switch (mCheckedState - mLastCheckedState) {
  187. case 1:
  188. if (mCheckedState == STATE_SWITCH_OFF2) {
  189. result = mOffLeftX; // off -> off2
  190. } else if (mCheckedState == STATE_SWITCH_ON) {
  191. result = mOnLeftX - (mOnLeftX - mOn2LeftX) * percent; // on2 -> on
  192. }
  193. break;
  194. case 2:
  195. if (mCheckedState == STATE_SWITCH_ON) {
  196. result = mOnLeftX - (mOnLeftX - mOffLeftX) * percent; // off2 -> on
  197. } else if (mCheckedState == STATE_SWITCH_ON2) {
  198. result = mOn2LeftX - (mOn2LeftX - mOffLeftX) * percent; // off -> on2
  199. }
  200. break;
  201. case 3:
  202. result = mOnLeftX - (mOnLeftX - mOffLeftX) * percent; // off -> on
  203. break;
  204. case -1:
  205. if (mCheckedState == STATE_SWITCH_ON2) {
  206. result = mOn2LeftX + (mOnLeftX - mOn2LeftX) * percent; // on -> on2
  207. } else if (mCheckedState == STATE_SWITCH_OFF) {
  208. result = mOffLeftX; // off2 -> off
  209. }
  210. break;
  211. case -2:
  212. if (mCheckedState == STATE_SWITCH_OFF) {
  213. result = mOffLeftX + (mOn2LeftX - mOffLeftX) * percent; // on2 -> off
  214. } else if (mCheckedState == STATE_SWITCH_OFF2) {
  215. result = mOff2LeftX + (mOnLeftX - mOff2LeftX) * percent; // on -> off2
  216. }
  217. break;
  218. case -3:
  219. result = mOffLeftX + (mOnLeftX - mOffLeftX) * percent; // on -> off
  220. break;
  221. default: // init
  222. case 0:
  223. if (mCheckedState == STATE_SWITCH_OFF) {
  224. result = mOffLeftX; // off -> off
  225. } else if (mCheckedState == STATE_SWITCH_ON) {
  226. result = mOnLeftX; // on -> on
  227. }
  228. break;
  229. }
  230. return result - mOffLeftX;
  231. }
  232. @Override
  233. protected void onDraw(Canvas canvas) {
  234. if (!isCanVisibleDrawing) return;
  235. mPaint.setAntiAlias(true);
  236. final boolean isOn = (mCheckedState == STATE_SWITCH_ON || mCheckedState == STATE_SWITCH_ON2);
  237. // Draw background
  238. mPaint.setStyle(Paint.Style.FILL);
  239. mPaint.setColor(isOn ? mAccentColor : mOffColor);
  240. canvas.drawPath(mBackgroundPath, mPaint);
  241. mAnim1 = mAnim1 - mAnimationSpeed > 0 ? mAnim1 - mAnimationSpeed : 0;
  242. mAnim2 = mAnim2 - mAnimationSpeed > 0 ? mAnim2 - mAnimationSpeed : 0;
  243. final float dsAnim = mInterpolator.getInterpolation(mAnim1);
  244. final float dbAnim = mInterpolator.getInterpolation(mAnim2);
  245. // Draw background animation
  246. final float scale = mScale * (isOn ? dsAnim : 1 - dsAnim);
  247. final float scaleOffset = (mRight - mCenterX - mRadius) * (isOn ? 1 - dsAnim : dsAnim);
  248. canvas.save();
  249. canvas.scale(scale, scale, mCenterX + scaleOffset, mCenterY);
  250. mPaint.setColor(0xFFFFFFFF);
  251. canvas.drawPath(mBackgroundPath, mPaint);
  252. canvas.restore();
  253. // To prepare center bar path
  254. canvas.save();
  255. canvas.translate(calcBTranslate(dbAnim), mShadowReservedHeight);
  256. final boolean isState2 = (mCheckedState == STATE_SWITCH_ON2 || mCheckedState == STATE_SWITCH_OFF2);
  257. calcBPath(isState2 ? 1 - dbAnim : dbAnim);
  258. // Use center bar path to draw shadow
  259. if (isShadow) {
  260. mPaint.setStyle(Paint.Style.FILL);
  261. mPaint.setShader(mShadowGradient);
  262. canvas.drawPath(mBarPath, mPaint);
  263. mPaint.setShader(null);
  264. }
  265. canvas.translate(0, -mShadowReservedHeight);
  266. // draw bar
  267. canvas.scale(0.98f, 0.98f, mWidth / 2, mWidth / 2);
  268. mPaint.setStyle(Paint.Style.FILL);
  269. mPaint.setColor(0xFFFFFFFF);
  270. canvas.drawPath(mBarPath, mPaint);
  271. mPaint.setStyle(Paint.Style.STROKE);
  272. mPaint.setStrokeWidth(mStrokeWidth * 0.5f);
  273. mPaint.setColor(isOn ? mPrimaryDarkColor : mOffDarkColor);
  274. canvas.drawPath(mBarPath, mPaint);
  275. canvas.restore();
  276. mPaint.reset();
  277. if (mAnim1 > 0 || mAnim2 > 0) invalidate();
  278. }
  279. @SuppressLint("ClickableViewAccessibility")
  280. @Override
  281. public boolean onTouchEvent(MotionEvent event) {
  282. super.onTouchEvent(event);
  283. if (isEnabled()
  284. && (mCheckedState == STATE_SWITCH_ON || mCheckedState == STATE_SWITCH_OFF)
  285. && (mAnim1 * mAnim2 == 0)) {
  286. switch (event.getAction()) {
  287. case MotionEvent.ACTION_DOWN:
  288. break;
  289. case MotionEvent.ACTION_UP:
  290. mLastCheckedState = mCheckedState;
  291. mAnim2 = 1;
  292. switch (mCheckedState) {
  293. case STATE_SWITCH_OFF:
  294. setChecked(true, false);
  295. if (mListener != null) {
  296. mListener.onCheckedChanged(this, true);
  297. }
  298. break;
  299. case STATE_SWITCH_ON:
  300. setChecked(false, false);
  301. if (mListener != null) {
  302. mListener.onCheckedChanged(this, false);
  303. }
  304. break;
  305. }
  306. break;
  307. }
  308. }
  309. return true;
  310. }
  311. @Override
  312. public Parcelable onSaveInstanceState() {
  313. Parcelable superState = super.onSaveInstanceState();
  314. SavedState state = new SavedState(superState);
  315. state.checked = mChecked;
  316. return state;
  317. }
  318. @Override
  319. public void onRestoreInstanceState(Parcelable state) {
  320. SavedState savedState = (SavedState) state;
  321. super.onRestoreInstanceState(savedState.getSuperState());
  322. mChecked = savedState.checked;
  323. mCheckedState = mChecked ? STATE_SWITCH_ON : STATE_SWITCH_OFF;
  324. invalidate();
  325. }
  326. public void setColor(int newColorPrimary, int newColorPrimaryDark) {
  327. setColor(newColorPrimary, newColorPrimaryDark, mOffColor, mOffDarkColor);
  328. }
  329. public void setColor(int newColorPrimary, int newColorPrimaryDark, int newColorOff, int newColorOffDark) {
  330. setColor(newColorPrimary, newColorPrimaryDark, newColorOff, newColorOffDark, mShadowColor);
  331. }
  332. public void setColor(int newColorPrimary, int newColorPrimaryDark, int newColorOff, int newColorOffDark, int newColorShadow) {
  333. mAccentColor = newColorPrimary;
  334. mPrimaryDarkColor = newColorPrimaryDark;
  335. mOffColor = newColorOff;
  336. mOffDarkColor = newColorOffDark;
  337. mShadowColor = newColorShadow;
  338. invalidate();
  339. }
  340. /**
  341. * 设置按钮阴影开关
  342. */
  343. public void setShadow(boolean shadow) {
  344. isShadow = shadow;
  345. invalidate();
  346. }
  347. /**
  348. * 当前状态是否选中
  349. */
  350. public boolean isChecked() {
  351. return mChecked;
  352. }
  353. /**
  354. * 设置选择状态(默认会回调监听器)
  355. */
  356. public void setChecked(boolean checked) {
  357. setChecked(checked, true); // 回调监听器
  358. }
  359. /**
  360. * 设置选择状态
  361. */
  362. public void setChecked(boolean checked, boolean callback) {
  363. int newState = checked ? STATE_SWITCH_ON : STATE_SWITCH_OFF;
  364. if (newState == mCheckedState) {
  365. return;
  366. }
  367. if ((newState == STATE_SWITCH_ON && (mCheckedState == STATE_SWITCH_OFF || mCheckedState == STATE_SWITCH_OFF2))
  368. || (newState == STATE_SWITCH_OFF && (mCheckedState == STATE_SWITCH_ON || mCheckedState == STATE_SWITCH_ON2))) {
  369. mAnim1 = 1;
  370. }
  371. mAnim2 = 1;
  372. if (!mChecked && newState == STATE_SWITCH_ON) {
  373. mChecked = true;
  374. } else if (mChecked && newState == STATE_SWITCH_OFF) {
  375. mChecked = false;
  376. }
  377. mLastCheckedState = mCheckedState;
  378. mCheckedState = newState;
  379. postInvalidate();
  380. if (callback && mListener != null) {
  381. mListener.onCheckedChanged(this, checked);
  382. }
  383. }
  384. /**
  385. * 设置选中状态改变监听
  386. */
  387. public void setOnCheckedChangeListener(OnCheckedChangeListener l) {
  388. mListener = l;
  389. }
  390. public interface OnCheckedChangeListener {
  391. void onCheckedChanged(SwitchButton button, boolean isChecked);
  392. }
  393. /**
  394. * 保存开关状态
  395. */
  396. private static final class SavedState extends BaseSavedState {
  397. private boolean checked;
  398. SavedState(Parcelable superState) {
  399. super(superState);
  400. }
  401. private SavedState(Parcel in) {
  402. super(in);
  403. checked = 1 == in.readInt();
  404. }
  405. @Override
  406. public void writeToParcel(Parcel out, int flags) {
  407. super.writeToParcel(out, flags);
  408. out.writeInt(checked ? 1 : 0);
  409. }
  410. // fixed by Night99 https://github.com/g19980115
  411. @Override
  412. public int describeContents() {
  413. return 0;
  414. }
  415. public static final Creator<SavedState> CREATOR = new Creator<SavedState>() {
  416. @Override
  417. public SavedState createFromParcel(Parcel in) {
  418. return new SavedState(in);
  419. }
  420. @Override
  421. public SavedState[] newArray(int size) {
  422. return new SavedState[size];
  423. }
  424. };
  425. }
  426. }