2

In regards to this thread, Lollipop's backgroundTint has no effect on a Button, is there anyway at all to set the tint colour for a RadioButton background, that works in API < 21?

setSupportBackgroundTintList is not available it seems, when using the Design Support lib v22+

Community
  • 1
  • 1
Mr Pablo
  • 4,109
  • 8
  • 51
  • 104

1 Answers1

0

Create a new class that extends from 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);
        }
    }
}

In attr.xml add:

<declare-styleable name="CustomRadioButton">
    <attr name="tintColor" format="color"/>
</declare-styleable>

Use in your layout:

<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"/>
Galya
  • 6,294
  • 6
  • 27
  • 45