以编程方式设置单选按钮的按钮色调

3

我希望能够通过编程设置单选按钮的着色。在XML中,有一个名为“buttonTint”的属性可以完成此工作。但是在程序中,我无法找到任何方法来设置单选按钮的着色或颜色。是否有任何方法或方式可以实现这一点?

 <RadioButton
    android:buttonTint="@color/colorPrimaryDark"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Payeer" />
3个回答

5
您可以使用 setButtonTintList(ColorStateList tint) 来应用按钮Drawable的色调。它不会修改当前色调模式,默认情况下是SRC_IN。后续对 setButtonDrawable(Drawable) 的调用将自动突变Drawable并使用 setTintList(ColorStateList) 应用指定的色调和色调模式。 示例代码:
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);

    }


}

谢谢兄弟。它正在运行。但是它需要最低API(LOLLIPOP)。如果运行手机的版本低于LOLLIPOP,它会崩溃吗? - Sorwar Hossain Mostafa
@SorwarHossainMostafa:“如果正在运行的手机版本低于LOLLIPOP,它会崩溃吗?”答案是不会 - AskNilesh

5

根据之前的回答,设置背景颜色的一行代码为:

Java 代码

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

Kotlin 代码

button.buttonTintList=ColorStateList.valueOf(getColor(R.color.red))

3
请使用以下代码:
button.setBackgroundTintList(ColorStateList.valueOf(resources.getColor(R.id.red)));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接