Created
July 23, 2015 10:12
-
-
Save ipcjs/b17d2fa64bbfd4d70091 to your computer and use it in GitHub Desktop.
不使用v7包,使没有文字的Switch兼容到Api16+
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.googfit.view; | |
import android.annotation.TargetApi; | |
import android.content.Context; | |
import android.os.Build; | |
import android.util.AttributeSet; | |
import android.widget.Switch; | |
import java.lang.reflect.Field; | |
/** | |
* 至少可以兼容到api16+ | |
* Created by JiangSong on 2015/7/23. | |
*/ | |
public class NoTextSwitch extends Switch { | |
private Field mThumbWidthField; | |
public NoTextSwitch(Context context) { | |
super(context); | |
init(); | |
} | |
public NoTextSwitch(Context context, AttributeSet attrs) { | |
super(context, attrs); | |
init(); | |
} | |
public NoTextSwitch(Context context, AttributeSet attrs, int defStyleAttr) { | |
super(context, attrs, defStyleAttr); | |
init(); | |
} | |
@TargetApi(Build.VERSION_CODES.LOLLIPOP) | |
public NoTextSwitch(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { | |
super(context, attrs, defStyleAttr, defStyleRes); | |
init(); | |
} | |
private boolean lessApi21() { | |
return Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP; | |
} | |
private void init() { | |
if (lessApi21()) { | |
Class<Switch> switchClass = Switch.class; | |
try { | |
mThumbWidthField = switchClass.getDeclaredField("mThumbWidth"); | |
mThumbWidthField.setAccessible(true); | |
} catch (NoSuchFieldException e) { | |
e.printStackTrace(); | |
mThumbWidthField = null; | |
} | |
} | |
setTextOn("");// 把开关文字去掉 | |
setTextOff(""); | |
} | |
@Override | |
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { | |
if (lessApi21()) { | |
int thumbWidth = getThumbDrawable().getIntrinsicWidth(); | |
int switchWidth = thumbWidth * 2 + getPaddingLeft() + getPaddingRight(); | |
// 因为文字被我们设为了“”,故switchWidth就会等于minSwitchWidth~~ | |
setSwitchMinWidth(switchWidth); | |
// switch的宽度固定为switchWidth | |
super.onMeasure(MeasureSpec.makeMeasureSpec(switchWidth, MeasureSpec.AT_MOST), heightMeasureSpec); | |
// 试图用反射设置thumb的宽度 | |
if (mThumbWidthField != null) { | |
try { | |
mThumbWidthField.set(this, thumbWidth); | |
} catch (IllegalAccessException e) { | |
e.printStackTrace(); | |
} | |
} | |
} else { | |
super.onMeasure(widthMeasureSpec, heightMeasureSpec); | |
} | |
} | |
@Override | |
protected void onLayout(boolean changed, int left, int top, int right, int bottom) { | |
super.onLayout(changed, left, top, right, bottom); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment