3

I want to set a radio button tint programmatically. in xml there is an attribute called "buttonTint" to do the work. but in program I am not able to find any method to set tint or color to the radio button. is there any method or any ways to do that?

 <RadioButton
    android:buttonTint="@color/colorPrimaryDark"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Payeer" />
Cœur
  • 37,241
  • 25
  • 195
  • 267

3 Answers3

5

You can use setButtonTintList (ColorStateList tint)

Applies a tint to the button drawable. Does not modify the current tint mode, which is SRC_IN by default.

Subsequent calls to setButtonDrawable(Drawable) will automatically mutate the drawable and apply the specified tint and tint mode using setTintList(ColorStateList).

SAMPLE CODE

public class MainActivity extends AppCompatActivity {

    RadioButton radioButton;

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        radioButton = findViewById(R.id.radioButton);

        ColorStateList myColorStateList = new ColorStateList(
                new int[][]{
                        new int[]{getResources().getColor(R.color.colorPrimaryDark)}
                },
                new int[]{getResources().getColor(R.color.colorAccent)}
        );

        radioButton.setButtonTintList(myColorStateList);

    }


}
Community
  • 1
  • 1
AskNilesh
  • 67,701
  • 16
  • 123
  • 163
  • thank you brother. it is working. but it is requiring minimum API (LOLLIPOP). is it going to crash if the version of the running phone lower than LOLLIPOP? – Sorwar Hossain Mostafa Apr 24 '18 at 12:31
  • @SorwarHossainMostafa *`is it going to crash if the version of the running phone lower than LOLLIPOP`* the answer is **NO** – AskNilesh Apr 24 '18 at 12:32
5

Based on both previous answer one line code for setting background color is

Java code

button.setButtonTintList(ColorStateList.valueOf(getColor(R.color.red)));

Kotlin code

button.buttonTintList=ColorStateList.valueOf(getColor(R.color.red))
Faraz Ahmed
  • 1,467
  • 2
  • 18
  • 33
3

Use Below Code:

button.setBackgroundTintList(ColorStateList.valueOf(resources.getColor(R.id.red)));
Rohan Lodhi
  • 1,385
  • 9
  • 24