public void initialize(Context context, AttributeSet attrs) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
this.setBackground(getResources().getDrawable(R.drawable.toggle_background, null));
} else {
this.setBackground(getResources().getDrawable(R.drawable.toggle_background));
}
StateListDrawable stateListDrawable = (StateListDrawable) this.getBackground();
DrawableContainer.DrawableContainerState dcs = (DrawableContainer.DrawableContainerState) stateListDrawable.getConstantState();
Drawable[] drawableItems = dcs.getChildren();
GradientDrawable unChecked = (GradientDrawable) drawableItems[0];
GradientDrawable checked = (GradientDrawable) drawableItems[1];
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomToggleButton);
// getting all the attributes values set from the typed array i.e from user
int toggleOnColor = typedArray.getColor(R.styleable.CustomToggleButton_checkedColor, Color.parseColor("#FF4081"));
int toggleOffColor = typedArray.getColor(R.styleable.CustomToggleButton_uncheckedColor, Color.parseColor("#FF4081"));
float borderWidth = typedArray.getDimension(R.styleable.CustomToggleButton_borderWidth, 4.0f);
float radius = typedArray.getDimension(R.styleable.CustomToggleButton_radius, 15.0f);
int checkedTextColor = typedArray.getColor(R.styleable.CustomToggleButton_checkedTextColor, getResources().getColor(R.color.CheckedTextColor));
int uncheckedTextColor = typedArray.getColor(R.styleable.CustomToggleButton_uncheckedTextColor, getResources().getColor(R.color.uncheckedTextColor));
Log.d(TAG, "initialize: " + borderWidth);
ColorStateList colorStateList = new ColorStateList(
new int[][]{
new int[]{android.R.attr.state_checked},
new int[]{-android.R.attr.state_checked}
},
new int[]{
checkedTextColor,
uncheckedTextColor
}
);
this.setTextColor(colorStateList);
checked.setStroke(Math.round(borderWidth), toggleOnColor);
checked.setColor(toggleOnColor);
checked.setCornerRadius(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, radius, getResources().getDisplayMetrics()));
unChecked.setStroke(Math.round(borderWidth), toggleOffColor);
unChecked.setCornerRadius(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, radius, getResources().getDisplayMetrics()));
}
CustomToggleButton.java 文件源码
java
阅读 14
收藏 0
点赞 0
评论 0
项目:Custom-Toggle-Button
作者:
评论列表
文章目录