关于这个帖子,Lollipop's backgroundTint has no effect on a Button,无论如何都要为RadioButton背景设置色调颜色,这在API< 21?
当使用Design Support lib v22 + 时,setSupportBackgroundTintList似乎不可用
答案 0 :(得分:0)
创建一个从RadioButton扩展的新类。
public class CustomRadioButton extends RadioButton {
private int tint;
public CustomRadioButton(Context context) {
super(context);
}
public CustomRadioButton(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, 0);
setBackgroundTint();
}
public CustomRadioButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr);
setBackgroundTint();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public CustomRadioButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs, defStyleAttr, defStyleRes);
setBackgroundTint();
}
@Override
public void toggle() {
if (isChecked()) {
if (getParent() instanceof RadioGroup) {
((RadioGroup) getParent()).clearCheck();
}
} else {
setChecked(true);
}
}
private void init(Context context, AttributeSet attrs, int defStyle) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TintableImageView, defStyle, 0);
tint = a.getColor(R.styleable.CustomRadioButton_tintColor, ContextCompat.getColor(context, R.color.primary_dark));
a.recycle();
}
private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TintableImageView, defStyleAttr, defStyleRes);
tint = a.getColor(R.styleable.CustomRadioButton_tintColor, ContextCompat.getColor(context, R.color.primary_dark));
a.recycle();
}
private void setBackgroundTint() {
Drawable drawable = getBackground();
if (drawable != null) {
drawable.setColorFilter(tint, PorterDuff.Mode.SRC_ATOP);
}
}
}
在attr.xml中添加:
<declare-styleable name="CustomRadioButton">
<attr name="tintColor" format="color"/>
</declare-styleable>
在布局中使用:
<com.my.package.view.custom.CustomRadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/background_radio_button"
android:button="@null"
android:gravity="center"
app:tintColor="@color/tint_color"/>