blob: 23e55e2be2fa1c5d812112737024c1022b026598 [file] [log] [blame]
Adam Powell12190b32010-11-28 19:07:53 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
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
17package android.widget;
18
Adam Powell12190b32010-11-28 19:07:53 -080019import android.content.Context;
20import android.content.res.ColorStateList;
21import android.content.res.Resources;
22import android.content.res.TypedArray;
23import android.graphics.Canvas;
24import android.graphics.Paint;
25import android.graphics.Rect;
26import android.graphics.Typeface;
27import android.graphics.drawable.Drawable;
28import android.text.Layout;
29import android.text.StaticLayout;
30import android.text.TextPaint;
31import android.text.TextUtils;
32import android.util.AttributeSet;
33import android.view.Gravity;
34import android.view.MotionEvent;
35import android.view.VelocityTracker;
36import android.view.ViewConfiguration;
Svetoslav Ganov63bce032011-07-23 19:52:17 -070037import android.view.accessibility.AccessibilityEvent;
Svetoslav Ganov8a78fd42012-01-17 14:36:46 -080038import android.view.accessibility.AccessibilityNodeInfo;
Adam Powell12190b32010-11-28 19:07:53 -080039
Adam Powellbe0a4532010-11-29 17:47:48 -080040import com.android.internal.R;
41
Adam Powell12190b32010-11-28 19:07:53 -080042/**
43 * A Switch is a two-state toggle switch widget that can select between two
44 * options. The user may drag the "thumb" back and forth to choose the selected option,
Chet Haase150176d2011-08-26 09:54:06 -070045 * or simply tap to toggle as if it were a checkbox. The {@link #setText(CharSequence) text}
46 * property controls the text displayed in the label for the switch, whereas the
47 * {@link #setTextOff(CharSequence) off} and {@link #setTextOn(CharSequence) on} text
48 * controls the text on the thumb. Similarly, the
49 * {@link #setTextAppearance(android.content.Context, int) textAppearance} and the related
50 * setTypeface() methods control the typeface and style of label text, whereas the
51 * {@link #setSwitchTextAppearance(android.content.Context, int) switchTextAppearance} and
52 * the related seSwitchTypeface() methods control that of the thumb.
Adam Powell12190b32010-11-28 19:07:53 -080053 *
Adam Powell12190b32010-11-28 19:07:53 -080054 */
55public class Switch extends CompoundButton {
56 private static final int TOUCH_MODE_IDLE = 0;
57 private static final int TOUCH_MODE_DOWN = 1;
58 private static final int TOUCH_MODE_DRAGGING = 2;
59
60 // Enum for the "typeface" XML parameter.
61 private static final int SANS = 1;
62 private static final int SERIF = 2;
63 private static final int MONOSPACE = 3;
64
65 private Drawable mThumbDrawable;
66 private Drawable mTrackDrawable;
67 private int mThumbTextPadding;
68 private int mSwitchMinWidth;
69 private int mSwitchPadding;
70 private CharSequence mTextOn;
71 private CharSequence mTextOff;
72
73 private int mTouchMode;
74 private int mTouchSlop;
75 private float mTouchX;
76 private float mTouchY;
77 private VelocityTracker mVelocityTracker = VelocityTracker.obtain();
78 private int mMinFlingVelocity;
79
80 private float mThumbPosition;
81 private int mSwitchWidth;
82 private int mSwitchHeight;
83 private int mThumbWidth; // Does not include padding
84
85 private int mSwitchLeft;
86 private int mSwitchTop;
87 private int mSwitchRight;
88 private int mSwitchBottom;
89
90 private TextPaint mTextPaint;
91 private ColorStateList mTextColors;
92 private Layout mOnLayout;
93 private Layout mOffLayout;
94
Adam Powellbe0a4532010-11-29 17:47:48 -080095 @SuppressWarnings("hiding")
Adam Powell12190b32010-11-28 19:07:53 -080096 private final Rect mTempRect = new Rect();
97
98 private static final int[] CHECKED_STATE_SET = {
99 R.attr.state_checked
100 };
101
102 /**
103 * Construct a new Switch with default styling.
104 *
105 * @param context The Context that will determine this widget's theming.
106 */
107 public Switch(Context context) {
108 this(context, null);
109 }
110
111 /**
112 * Construct a new Switch with default styling, overriding specific style
113 * attributes as requested.
114 *
115 * @param context The Context that will determine this widget's theming.
116 * @param attrs Specification of attributes that should deviate from default styling.
117 */
118 public Switch(Context context, AttributeSet attrs) {
119 this(context, attrs, com.android.internal.R.attr.switchStyle);
120 }
121
122 /**
123 * Construct a new Switch with a default style determined by the given theme attribute,
124 * overriding specific style attributes as requested.
125 *
126 * @param context The Context that will determine this widget's theming.
127 * @param attrs Specification of attributes that should deviate from the default styling.
128 * @param defStyle An attribute ID within the active theme containing a reference to the
129 * default style for this widget. e.g. android.R.attr.switchStyle.
130 */
131 public Switch(Context context, AttributeSet attrs, int defStyle) {
132 super(context, attrs, defStyle);
133
134 mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
135 Resources res = getResources();
136 mTextPaint.density = res.getDisplayMetrics().density;
137 mTextPaint.setCompatibilityScaling(res.getCompatibilityInfo().applicationScale);
138
139 TypedArray a = context.obtainStyledAttributes(attrs,
140 com.android.internal.R.styleable.Switch, defStyle, 0);
141
Chet Haase150176d2011-08-26 09:54:06 -0700142 mThumbDrawable = a.getDrawable(com.android.internal.R.styleable.Switch_thumb);
143 mTrackDrawable = a.getDrawable(com.android.internal.R.styleable.Switch_track);
Adam Powell12190b32010-11-28 19:07:53 -0800144 mTextOn = a.getText(com.android.internal.R.styleable.Switch_textOn);
145 mTextOff = a.getText(com.android.internal.R.styleable.Switch_textOff);
146 mThumbTextPadding = a.getDimensionPixelSize(
147 com.android.internal.R.styleable.Switch_thumbTextPadding, 0);
148 mSwitchMinWidth = a.getDimensionPixelSize(
149 com.android.internal.R.styleable.Switch_switchMinWidth, 0);
150 mSwitchPadding = a.getDimensionPixelSize(
151 com.android.internal.R.styleable.Switch_switchPadding, 0);
152
153 int appearance = a.getResourceId(
154 com.android.internal.R.styleable.Switch_switchTextAppearance, 0);
155 if (appearance != 0) {
Chet Haase150176d2011-08-26 09:54:06 -0700156 setSwitchTextAppearance(context, appearance);
Adam Powell12190b32010-11-28 19:07:53 -0800157 }
158 a.recycle();
159
160 ViewConfiguration config = ViewConfiguration.get(context);
161 mTouchSlop = config.getScaledTouchSlop();
162 mMinFlingVelocity = config.getScaledMinimumFlingVelocity();
163
164 // Refresh display with current params
Gilles Debunnee724ee42011-08-31 11:20:27 -0700165 refreshDrawableState();
Adam Powell12190b32010-11-28 19:07:53 -0800166 setChecked(isChecked());
167 }
168
169 /**
170 * Sets the switch text color, size, style, hint color, and highlight color
171 * from the specified TextAppearance resource.
Adam Powell6c86e1b2012-03-08 15:11:46 -0800172 *
173 * @attr ref android.R.styleable#Switch_switchTextAppearance
Adam Powell12190b32010-11-28 19:07:53 -0800174 */
Chet Haase150176d2011-08-26 09:54:06 -0700175 public void setSwitchTextAppearance(Context context, int resid) {
Adam Powell12190b32010-11-28 19:07:53 -0800176 TypedArray appearance =
Chet Haase150176d2011-08-26 09:54:06 -0700177 context.obtainStyledAttributes(resid,
Adam Powell12190b32010-11-28 19:07:53 -0800178 com.android.internal.R.styleable.TextAppearance);
179
180 ColorStateList colors;
181 int ts;
182
183 colors = appearance.getColorStateList(com.android.internal.R.styleable.
184 TextAppearance_textColor);
185 if (colors != null) {
186 mTextColors = colors;
Chet Haase150176d2011-08-26 09:54:06 -0700187 } else {
188 // If no color set in TextAppearance, default to the view's textColor
189 mTextColors = getTextColors();
Adam Powell12190b32010-11-28 19:07:53 -0800190 }
191
192 ts = appearance.getDimensionPixelSize(com.android.internal.R.styleable.
193 TextAppearance_textSize, 0);
194 if (ts != 0) {
195 if (ts != mTextPaint.getTextSize()) {
196 mTextPaint.setTextSize(ts);
197 requestLayout();
198 }
199 }
200
201 int typefaceIndex, styleIndex;
202
203 typefaceIndex = appearance.getInt(com.android.internal.R.styleable.
204 TextAppearance_typeface, -1);
205 styleIndex = appearance.getInt(com.android.internal.R.styleable.
206 TextAppearance_textStyle, -1);
207
208 setSwitchTypefaceByIndex(typefaceIndex, styleIndex);
209
Adam Powell12190b32010-11-28 19:07:53 -0800210 appearance.recycle();
211 }
212
213 private void setSwitchTypefaceByIndex(int typefaceIndex, int styleIndex) {
214 Typeface tf = null;
215 switch (typefaceIndex) {
216 case SANS:
217 tf = Typeface.SANS_SERIF;
218 break;
219
220 case SERIF:
221 tf = Typeface.SERIF;
222 break;
223
224 case MONOSPACE:
225 tf = Typeface.MONOSPACE;
226 break;
227 }
228
229 setSwitchTypeface(tf, styleIndex);
230 }
231
232 /**
233 * Sets the typeface and style in which the text should be displayed on the
234 * switch, and turns on the fake bold and italic bits in the Paint if the
235 * Typeface that you provided does not have all the bits in the
236 * style that you specified.
237 */
238 public void setSwitchTypeface(Typeface tf, int style) {
239 if (style > 0) {
240 if (tf == null) {
241 tf = Typeface.defaultFromStyle(style);
242 } else {
243 tf = Typeface.create(tf, style);
244 }
245
246 setSwitchTypeface(tf);
247 // now compute what (if any) algorithmic styling is needed
248 int typefaceStyle = tf != null ? tf.getStyle() : 0;
249 int need = style & ~typefaceStyle;
250 mTextPaint.setFakeBoldText((need & Typeface.BOLD) != 0);
251 mTextPaint.setTextSkewX((need & Typeface.ITALIC) != 0 ? -0.25f : 0);
252 } else {
253 mTextPaint.setFakeBoldText(false);
254 mTextPaint.setTextSkewX(0);
255 setSwitchTypeface(tf);
256 }
257 }
258
259 /**
Chet Haase150176d2011-08-26 09:54:06 -0700260 * Sets the typeface in which the text should be displayed on the switch.
Adam Powell12190b32010-11-28 19:07:53 -0800261 * Note that not all Typeface families actually have bold and italic
262 * variants, so you may need to use
263 * {@link #setSwitchTypeface(Typeface, int)} to get the appearance
264 * that you actually want.
265 *
266 * @attr ref android.R.styleable#TextView_typeface
267 * @attr ref android.R.styleable#TextView_textStyle
268 */
269 public void setSwitchTypeface(Typeface tf) {
270 if (mTextPaint.getTypeface() != tf) {
271 mTextPaint.setTypeface(tf);
272
273 requestLayout();
274 invalidate();
275 }
276 }
277
278 /**
Adam Powell6c86e1b2012-03-08 15:11:46 -0800279 * Set the amount of horizontal padding between the switch and the associated text.
280 *
281 * @param pixels Amount of padding in pixels
282 *
283 * @attr ref android.R.styleable#Switch_switchPadding
284 */
285 public void setSwitchPadding(int pixels) {
286 mSwitchPadding = pixels;
287 requestLayout();
288 }
289
290 /**
291 * Get the amount of horizontal padding between the switch and the associated text.
292 *
293 * @return Amount of padding in pixels
294 *
295 * @attr ref android.R.styleable#Switch_switchPadding
296 */
297 public int getSwitchPadding() {
298 return mSwitchPadding;
299 }
300
301 /**
302 * Set the minimum width of the switch in pixels. The switch's width will be the maximum
303 * of this value and its measured width as determined by the switch drawables and text used.
304 *
305 * @param pixels Minimum width of the switch in pixels
306 *
307 * @attr ref android.R.styleable#Switch_switchMinWidth
308 */
309 public void setSwitchMinWidth(int pixels) {
310 mSwitchMinWidth = pixels;
311 requestLayout();
312 }
313
314 /**
315 * Get the minimum width of the switch in pixels. The switch's width will be the maximum
316 * of this value and its measured width as determined by the switch drawables and text used.
317 *
318 * @return Minimum width of the switch in pixels
319 *
320 * @attr ref android.R.styleable#Switch_switchMinWidth
321 */
322 public int getSwitchMinWidth() {
323 return mSwitchMinWidth;
324 }
325
326 /**
327 * Set the horizontal padding around the text drawn on the switch itself.
328 *
329 * @param pixels Horizontal padding for switch thumb text in pixels
330 *
331 * @attr ref android.R.styleable#Switch_thumbTextPadding
332 */
333 public void setThumbTextPadding(int pixels) {
334 mThumbTextPadding = pixels;
335 requestLayout();
336 }
337
338 /**
339 * Get the horizontal padding around the text drawn on the switch itself.
340 *
341 * @return Horizontal padding for switch thumb text in pixels
342 *
343 * @attr ref android.R.styleable#Switch_thumbTextPadding
344 */
345 public int getThumbTextPadding() {
346 return mThumbTextPadding;
347 }
348
349 /**
350 * Set the drawable used for the track that the switch slides within.
351 *
352 * @param track Track drawable
353 *
354 * @attr ref android.R.styleable#Switch_track
355 */
356 public void setTrackDrawable(Drawable track) {
357 mTrackDrawable = track;
358 requestLayout();
359 }
360
361 /**
362 * Get the drawable used for the track that the switch slides within.
363 *
364 * @return Track drawable
365 *
366 * @attr ref android.R.styleable#Switch_track
367 */
368 public Drawable getTrackDrawable() {
369 return mTrackDrawable;
370 }
371
372 /**
373 * Set the drawable used for the switch "thumb" - the piece that the user
374 * can physically touch and drag along the track.
375 *
376 * @param thumb Thumb drawable
377 *
378 * @attr ref android.R.styleable#Switch_thumb
379 */
380 public void setThumbDrawable(Drawable thumb) {
381 mThumbDrawable = thumb;
382 requestLayout();
383 }
384
385 /**
386 * Get the drawable used for the switch "thumb" - the piece that the user
387 * can physically touch and drag along the track.
388 *
389 * @return Thumb drawable
390 *
391 * @attr ref android.R.styleable#Switch_thumb
392 */
393 public Drawable getThumbDrawable() {
394 return mThumbDrawable;
395 }
396
397 /**
Chet Haase150176d2011-08-26 09:54:06 -0700398 * Returns the text displayed when the button is in the checked state.
Adam Powell6c86e1b2012-03-08 15:11:46 -0800399 *
400 * @attr ref android.R.styleable#Switch_textOn
Adam Powell12190b32010-11-28 19:07:53 -0800401 */
402 public CharSequence getTextOn() {
403 return mTextOn;
404 }
405
406 /**
Chet Haase150176d2011-08-26 09:54:06 -0700407 * Sets the text displayed when the button is in the checked state.
Adam Powell6c86e1b2012-03-08 15:11:46 -0800408 *
409 * @attr ref android.R.styleable#Switch_textOn
Adam Powell12190b32010-11-28 19:07:53 -0800410 */
411 public void setTextOn(CharSequence textOn) {
412 mTextOn = textOn;
413 requestLayout();
414 }
415
416 /**
Chet Haase150176d2011-08-26 09:54:06 -0700417 * Returns the text displayed when the button is not in the checked state.
Adam Powell6c86e1b2012-03-08 15:11:46 -0800418 *
419 * @attr ref android.R.styleable#Switch_textOff
Adam Powell12190b32010-11-28 19:07:53 -0800420 */
421 public CharSequence getTextOff() {
422 return mTextOff;
423 }
424
425 /**
Chet Haase150176d2011-08-26 09:54:06 -0700426 * Sets the text displayed when the button is not in the checked state.
Adam Powell6c86e1b2012-03-08 15:11:46 -0800427 *
428 * @attr ref android.R.styleable#Switch_textOff
Adam Powell12190b32010-11-28 19:07:53 -0800429 */
430 public void setTextOff(CharSequence textOff) {
431 mTextOff = textOff;
432 requestLayout();
433 }
434
435 @Override
436 public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
437 final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
438 final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
439 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
440 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
441
442
443 if (mOnLayout == null) {
444 mOnLayout = makeLayout(mTextOn);
445 }
446 if (mOffLayout == null) {
447 mOffLayout = makeLayout(mTextOff);
448 }
449
450 mTrackDrawable.getPadding(mTempRect);
451 final int maxTextWidth = Math.max(mOnLayout.getWidth(), mOffLayout.getWidth());
452 final int switchWidth = Math.max(mSwitchMinWidth,
453 maxTextWidth * 2 + mThumbTextPadding * 4 + mTempRect.left + mTempRect.right);
454 final int switchHeight = mTrackDrawable.getIntrinsicHeight();
455
456 mThumbWidth = maxTextWidth + mThumbTextPadding * 2;
457
458 switch (widthMode) {
459 case MeasureSpec.AT_MOST:
460 widthSize = Math.min(widthSize, switchWidth);
461 break;
462
463 case MeasureSpec.UNSPECIFIED:
464 widthSize = switchWidth;
465 break;
466
467 case MeasureSpec.EXACTLY:
468 // Just use what we were given
469 break;
470 }
471
472 switch (heightMode) {
473 case MeasureSpec.AT_MOST:
474 heightSize = Math.min(heightSize, switchHeight);
475 break;
476
477 case MeasureSpec.UNSPECIFIED:
478 heightSize = switchHeight;
479 break;
480
481 case MeasureSpec.EXACTLY:
482 // Just use what we were given
483 break;
484 }
485
486 mSwitchWidth = switchWidth;
487 mSwitchHeight = switchHeight;
488
489 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
Adam Powell12190b32010-11-28 19:07:53 -0800490 final int measuredHeight = getMeasuredHeight();
491 if (measuredHeight < switchHeight) {
Dianne Hackborn189ee182010-12-02 21:48:53 -0800492 setMeasuredDimension(getMeasuredWidthAndState(), switchHeight);
Adam Powell12190b32010-11-28 19:07:53 -0800493 }
494 }
495
Svetoslav Ganov63bce032011-07-23 19:52:17 -0700496 @Override
497 public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
498 super.onPopulateAccessibilityEvent(event);
Svetoslav Ganov76502592011-07-29 10:44:59 -0700499 if (isChecked()) {
500 CharSequence text = mOnLayout.getText();
501 if (TextUtils.isEmpty(text)) {
502 text = mContext.getString(R.string.switch_on);
503 }
504 event.getText().add(text);
505 } else {
506 CharSequence text = mOffLayout.getText();
507 if (TextUtils.isEmpty(text)) {
508 text = mContext.getString(R.string.switch_off);
509 }
510 event.getText().add(text);
511 }
Svetoslav Ganov63bce032011-07-23 19:52:17 -0700512 }
513
Adam Powell12190b32010-11-28 19:07:53 -0800514 private Layout makeLayout(CharSequence text) {
515 return new StaticLayout(text, mTextPaint,
516 (int) Math.ceil(Layout.getDesiredWidth(text, mTextPaint)),
517 Layout.Alignment.ALIGN_NORMAL, 1.f, 0, true);
518 }
519
520 /**
521 * @return true if (x, y) is within the target area of the switch thumb
522 */
523 private boolean hitThumb(float x, float y) {
524 mThumbDrawable.getPadding(mTempRect);
525 final int thumbTop = mSwitchTop - mTouchSlop;
526 final int thumbLeft = mSwitchLeft + (int) (mThumbPosition + 0.5f) - mTouchSlop;
527 final int thumbRight = thumbLeft + mThumbWidth +
528 mTempRect.left + mTempRect.right + mTouchSlop;
529 final int thumbBottom = mSwitchBottom + mTouchSlop;
530 return x > thumbLeft && x < thumbRight && y > thumbTop && y < thumbBottom;
531 }
532
533 @Override
534 public boolean onTouchEvent(MotionEvent ev) {
535 mVelocityTracker.addMovement(ev);
536 final int action = ev.getActionMasked();
537 switch (action) {
538 case MotionEvent.ACTION_DOWN: {
539 final float x = ev.getX();
540 final float y = ev.getY();
Gilles Debunnec2ab0d62011-06-13 12:52:48 -0700541 if (isEnabled() && hitThumb(x, y)) {
Adam Powell12190b32010-11-28 19:07:53 -0800542 mTouchMode = TOUCH_MODE_DOWN;
543 mTouchX = x;
544 mTouchY = y;
545 }
546 break;
547 }
548
549 case MotionEvent.ACTION_MOVE: {
550 switch (mTouchMode) {
551 case TOUCH_MODE_IDLE:
552 // Didn't target the thumb, treat normally.
553 break;
554
555 case TOUCH_MODE_DOWN: {
556 final float x = ev.getX();
557 final float y = ev.getY();
558 if (Math.abs(x - mTouchX) > mTouchSlop ||
559 Math.abs(y - mTouchY) > mTouchSlop) {
560 mTouchMode = TOUCH_MODE_DRAGGING;
561 getParent().requestDisallowInterceptTouchEvent(true);
562 mTouchX = x;
563 mTouchY = y;
564 return true;
565 }
566 break;
567 }
568
569 case TOUCH_MODE_DRAGGING: {
570 final float x = ev.getX();
571 final float dx = x - mTouchX;
572 float newPos = Math.max(0,
573 Math.min(mThumbPosition + dx, getThumbScrollRange()));
574 if (newPos != mThumbPosition) {
575 mThumbPosition = newPos;
576 mTouchX = x;
577 invalidate();
578 }
579 return true;
580 }
581 }
582 break;
583 }
584
585 case MotionEvent.ACTION_UP:
586 case MotionEvent.ACTION_CANCEL: {
587 if (mTouchMode == TOUCH_MODE_DRAGGING) {
588 stopDrag(ev);
589 return true;
590 }
591 mTouchMode = TOUCH_MODE_IDLE;
592 mVelocityTracker.clear();
593 break;
594 }
595 }
596
597 return super.onTouchEvent(ev);
598 }
599
600 private void cancelSuperTouch(MotionEvent ev) {
601 MotionEvent cancel = MotionEvent.obtain(ev);
602 cancel.setAction(MotionEvent.ACTION_CANCEL);
603 super.onTouchEvent(cancel);
604 cancel.recycle();
605 }
606
607 /**
608 * Called from onTouchEvent to end a drag operation.
609 *
610 * @param ev Event that triggered the end of drag mode - ACTION_UP or ACTION_CANCEL
611 */
612 private void stopDrag(MotionEvent ev) {
613 mTouchMode = TOUCH_MODE_IDLE;
Gilles Debunnec2ab0d62011-06-13 12:52:48 -0700614 // Up and not canceled, also checks the switch has not been disabled during the drag
615 boolean commitChange = ev.getAction() == MotionEvent.ACTION_UP && isEnabled();
Adam Powell12190b32010-11-28 19:07:53 -0800616
617 cancelSuperTouch(ev);
618
619 if (commitChange) {
620 boolean newState;
621 mVelocityTracker.computeCurrentVelocity(1000);
622 float xvel = mVelocityTracker.getXVelocity();
623 if (Math.abs(xvel) > mMinFlingVelocity) {
Adam Powell01d11ed2011-08-09 16:32:12 -0700624 newState = xvel > 0;
Adam Powell12190b32010-11-28 19:07:53 -0800625 } else {
626 newState = getTargetCheckedState();
627 }
628 animateThumbToCheckedState(newState);
629 } else {
630 animateThumbToCheckedState(isChecked());
631 }
632 }
633
634 private void animateThumbToCheckedState(boolean newCheckedState) {
Adam Powell12190b32010-11-28 19:07:53 -0800635 // TODO animate!
Joe Onoratoc3eabb92011-01-07 15:58:44 -0800636 //float targetPos = newCheckedState ? 0 : getThumbScrollRange();
637 //mThumbPosition = targetPos;
Adam Powell12190b32010-11-28 19:07:53 -0800638 setChecked(newCheckedState);
639 }
640
641 private boolean getTargetCheckedState() {
Adam Powellec1d6032011-08-07 18:03:39 -0700642 return mThumbPosition >= getThumbScrollRange() / 2;
Adam Powell12190b32010-11-28 19:07:53 -0800643 }
644
645 @Override
646 public void setChecked(boolean checked) {
647 super.setChecked(checked);
Adam Powellec1d6032011-08-07 18:03:39 -0700648 mThumbPosition = checked ? getThumbScrollRange() : 0;
Joe Onoratoc3eabb92011-01-07 15:58:44 -0800649 invalidate();
Adam Powell12190b32010-11-28 19:07:53 -0800650 }
651
652 @Override
653 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
654 super.onLayout(changed, left, top, right, bottom);
655
Adam Powellec1d6032011-08-07 18:03:39 -0700656 mThumbPosition = isChecked() ? getThumbScrollRange() : 0;
Joe Onoratoc3eabb92011-01-07 15:58:44 -0800657
Adam Powell12190b32010-11-28 19:07:53 -0800658 int switchRight = getWidth() - getPaddingRight();
659 int switchLeft = switchRight - mSwitchWidth;
660 int switchTop = 0;
661 int switchBottom = 0;
662 switch (getGravity() & Gravity.VERTICAL_GRAVITY_MASK) {
663 default:
664 case Gravity.TOP:
665 switchTop = getPaddingTop();
666 switchBottom = switchTop + mSwitchHeight;
667 break;
668
669 case Gravity.CENTER_VERTICAL:
670 switchTop = (getPaddingTop() + getHeight() - getPaddingBottom()) / 2 -
671 mSwitchHeight / 2;
672 switchBottom = switchTop + mSwitchHeight;
673 break;
674
675 case Gravity.BOTTOM:
676 switchBottom = getHeight() - getPaddingBottom();
677 switchTop = switchBottom - mSwitchHeight;
678 break;
679 }
680
681 mSwitchLeft = switchLeft;
682 mSwitchTop = switchTop;
683 mSwitchBottom = switchBottom;
684 mSwitchRight = switchRight;
685 }
686
687 @Override
688 protected void onDraw(Canvas canvas) {
689 super.onDraw(canvas);
690
691 // Draw the switch
692 int switchLeft = mSwitchLeft;
693 int switchTop = mSwitchTop;
694 int switchRight = mSwitchRight;
695 int switchBottom = mSwitchBottom;
696
697 mTrackDrawable.setBounds(switchLeft, switchTop, switchRight, switchBottom);
698 mTrackDrawable.draw(canvas);
699
700 canvas.save();
701
702 mTrackDrawable.getPadding(mTempRect);
703 int switchInnerLeft = switchLeft + mTempRect.left;
704 int switchInnerTop = switchTop + mTempRect.top;
705 int switchInnerRight = switchRight - mTempRect.right;
706 int switchInnerBottom = switchBottom - mTempRect.bottom;
707 canvas.clipRect(switchInnerLeft, switchTop, switchInnerRight, switchBottom);
708
709 mThumbDrawable.getPadding(mTempRect);
710 final int thumbPos = (int) (mThumbPosition + 0.5f);
711 int thumbLeft = switchInnerLeft - mTempRect.left + thumbPos;
712 int thumbRight = switchInnerLeft + thumbPos + mThumbWidth + mTempRect.right;
713
714 mThumbDrawable.setBounds(thumbLeft, switchTop, thumbRight, switchBottom);
715 mThumbDrawable.draw(canvas);
716
Chet Haase150176d2011-08-26 09:54:06 -0700717 // mTextColors should not be null, but just in case
718 if (mTextColors != null) {
719 mTextPaint.setColor(mTextColors.getColorForState(getDrawableState(),
720 mTextColors.getDefaultColor()));
721 }
Adam Powell12190b32010-11-28 19:07:53 -0800722 mTextPaint.drawableState = getDrawableState();
723
724 Layout switchText = getTargetCheckedState() ? mOnLayout : mOffLayout;
725
726 canvas.translate((thumbLeft + thumbRight) / 2 - switchText.getWidth() / 2,
727 (switchInnerTop + switchInnerBottom) / 2 - switchText.getHeight() / 2);
728 switchText.draw(canvas);
729
730 canvas.restore();
731 }
732
733 @Override
734 public int getCompoundPaddingRight() {
735 int padding = super.getCompoundPaddingRight() + mSwitchWidth;
736 if (!TextUtils.isEmpty(getText())) {
737 padding += mSwitchPadding;
738 }
739 return padding;
740 }
741
742 private int getThumbScrollRange() {
743 if (mTrackDrawable == null) {
744 return 0;
745 }
746 mTrackDrawable.getPadding(mTempRect);
747 return mSwitchWidth - mThumbWidth - mTempRect.left - mTempRect.right;
748 }
749
750 @Override
751 protected int[] onCreateDrawableState(int extraSpace) {
752 final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
753 if (isChecked()) {
754 mergeDrawableStates(drawableState, CHECKED_STATE_SET);
755 }
756 return drawableState;
757 }
758
759 @Override
760 protected void drawableStateChanged() {
761 super.drawableStateChanged();
762
763 int[] myDrawableState = getDrawableState();
764
765 // Set the state of the Drawable
Gilles Debunnee724ee42011-08-31 11:20:27 -0700766 // Drawable may be null when checked state is set from XML, from super constructor
767 if (mThumbDrawable != null) mThumbDrawable.setState(myDrawableState);
768 if (mTrackDrawable != null) mTrackDrawable.setState(myDrawableState);
Adam Powell12190b32010-11-28 19:07:53 -0800769
770 invalidate();
771 }
772
773 @Override
774 protected boolean verifyDrawable(Drawable who) {
775 return super.verifyDrawable(who) || who == mThumbDrawable || who == mTrackDrawable;
776 }
777
778 @Override
779 public void jumpDrawablesToCurrentState() {
780 super.jumpDrawablesToCurrentState();
781 mThumbDrawable.jumpToCurrentState();
782 mTrackDrawable.jumpToCurrentState();
783 }
Svetoslav Ganov8a78fd42012-01-17 14:36:46 -0800784
785 @Override
786 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
787 super.onInitializeAccessibilityEvent(event);
788 event.setClassName(Switch.class.getName());
789 }
790
791 @Override
792 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
793 super.onInitializeAccessibilityNodeInfo(info);
794 info.setClassName(Switch.class.getName());
795 }
Adam Powell12190b32010-11-28 19:07:53 -0800796}