项目背景:
自定义的SwitchButton效果跟Swith切换效果相似,但是Switch继承自CompoundButton,而CompoundButton又继承自Button,Button只能显示一个文本,无法做法切换多个文本的效果
直接贴图展示效果
代码实现:
public class SwitchButton extends View {
private static final String TAG = "SwitchButton";
private final int mMaxVelocity;
Paint mPaint;
private Paint mTextPaint;
boolean isChecked;
private VelocityTracker mVelocityTracker;
//滑块自动回滚的速度
private final float mEffectiveVelocity = 1000;
//背景颜色
private final int mBackgroundColor;
//switch的高
private float mSwitchHeight;
//switch的宽
private float mSwitchWidth;
//圆角
private final float mCornerRadius;
//选中文本的背景颜色
private final int mSelectBackgroundColor;
//选中的文字颜色
private final int mSelectTextColor;
//默认的文字颜色
private final int mDefaultTextColor;
//文字
private final float mTextSize;
//内部按钮padding值
private float mPadding;
private String mSelectText;
private String mDefaultText;
private float left = 0;
private float right;
private RectF mRectBg;
private RectF mRect;
boolean isSlide = false;
private final boolean mIsThumbSliding;
public SwitchButton(Context context) {
this(context, null);
}
public SwitchButton(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public SwitchButton(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
ViewConfiguration configuration = ViewConfiguration.get(context);
mMaxVelocity = configuration.getScaledMaximumFlingVelocity();
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SwitchButton);
mBackgroundColor = typedArray.getColor(R.styleable.SwitchButton_backgroundColor, Color.parseColor("#333439"));
mCornerRadius = typedArray.getDimension(R.styleable.SwitchButton_switch_corner_radius, 20.0f);
mSelectBackgroundColor = typedArray.getColor(R.styleable.SwitchButton_select_backgroundColor, Color.parseColor("#E9EFF2"));
mSelectTextColor = typedArray.getColor(R.styleable.SwitchButton_select_textColor, Color.parseColor("#FFD2DFE8"));
mDefaultTextColor = typedArray.getColor(R.styleable.SwitchButton_default_textColor, Color.parseColor("#FF30353B"));
mSelectText = typedArray.getString(R.styleable.SwitchButton_select_text);
mTextSize = typedArray.getDimension(R.styleable.SwitchButton_text_size, 20);
mPadding = typedArray.getDimension(R.styleable.SwitchButton_thumb_padding, 2);
mDefaultText = typedArray.getString(R.styleable.SwitchButton_default_text);
mIsThumbSliding = typedArray.getBoolean(R.styleable.SwitchButton_isThumbSliding, false);
isChecked = typedArray.getBoolean(R.styleable.SwitchButton_check