【问题标题】:setOnCheckedChangeListener for every radiobutton每个单选按钮的 setOnCheckedChangeListener
【发布时间】:2021-08-15 23:57:23
【问题描述】:

我有一个单选组,其中包含几个背景颜色为灰色的单选按钮。当我单击一个单选按钮时,我需要单击的单选按钮将背景颜色更改为黑色,而其他人将保持灰色背景。我知道我可以像这样为所有单选按钮设置 OnCheckedChangeListeners:

if(checked) 然后 setBackGroundColor 为黑色;

否则 setBackGroundColor 为灰色;

但是有没有更有效的方法来做到这一点?就像为整个组只写一个 OnCheckedChangeListener

【问题讨论】:

  • 我以为整个小组只有一个听众。
  • 你也可以在你的设计中尝试这样stackoverflow.com/a/67724183/8133524id.setBackgroundColor(getResources().getColor(R.color.Black));

标签: android radio-button oncheckedchanged


【解决方案1】:

创建一个选择器 -> drawable/radio_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true"
        android:color="@color/black" /> <!-- checked -->
    <item android:state_checked="false"
        android:color="@color/grey" /> <!-- unchecked -->
</selector>

然后在 RadioButton 视图中添加

android:buttonTint="@drawable/radio_selector"

这适用于 api 21+ 如果您使用较低的最低 api,则需要在样式中设置 buttonTint

   <style name="radio_style" parent="Widget.AppCompat.CompoundButton.RadioButton">
       <item name="buttonTint">@drawable/radio_selector</item>
   </style>

并将其添加到您的 RadionButton

style="@style/radio_style"

【讨论】:

    猜你喜欢
    • 2012-10-28
    • 2012-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多