Sorwar Hossain Mostafa
Sorwar Hossain Mostafa

Reputation: 255

Setting button tint on radio button programmatically

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" />

Upvotes: 3

Views: 3738

Answers (3)

Faraz Ahmed
Faraz Ahmed

Reputation: 1607

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))

Upvotes: 5

Rohan Lodhi
Rohan Lodhi

Reputation: 1395

Use Below Code:

button.setBackgroundTintList(ColorStateList.valueOf(resources.getColor(R.id.red)));

Upvotes: 3

AskNilesh
AskNilesh

Reputation: 69734

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);

    }


}

Upvotes: 5

Related Questions