【问题标题】:Change the text color of an unidentified radio button更改未识别单选按钮的文本颜色
【发布时间】:2017-07-21 02:45:43
【问题描述】:

我有一个带有 4 个单选按钮的单选组。我使用此代码:

int radioButtonID = radioGroup.getCheckedRadioButtonId();
View checkedRadioButton = radioGroup.findViewById(radioButtonID);
int idx = radioGroup.indexOfChild(checkedRadioButton);

检索选中的单选按钮的索引。

问题是我想更改选中单选按钮的文本颜色,而我每次都不知道具体的单选按钮。所以:checkedRadioButton.setTextColor(color); 显示我需要“添加限定符”的错误,这基本上告诉我应该使用特定的单选按钮来调用该方法,例如:

radioButtonAns1.setTextColor(color);

我想是否有人也能解释我为什么会出现该错误以及是否有解决方案。我唯一可以调用的方法是.setBackgroundColor(),它看起来很丑。

提前致谢!

【问题讨论】:

    标签: java android android-studio radio-button


    【解决方案1】:

    如果您将找到的View 转换为RadioButton,则可以使用setTextColor 方法:

    RadioButton checkedRadioButton = (RadioButton) radioGroup.findViewById(radioButtonID);
    checkedRadioButton.setTextColor(color);
    

    【讨论】:

      【解决方案2】:

      嗯,这有点直截了当,错误基本上是说,嘿,你试图改变包含单选按钮组的组的颜色。请先选择你想要的,然后再改变它。为了解决这个问题,声明一个布尔数组,然后设置一个点击监听器来检测被点击的单选按钮的位置,然后在数组中设置布尔值为真。

      【讨论】:

      • 问题是我尝试访问单选按钮而不是单选组。我只需要指定我想要返回 RadioButton 而不是 View。铸造它成功了
      【解决方案3】:

      XML 替代方案是:

      TextColor 设置为@Color 选择器。

      <RadioButton
         android:id="@+id/radio_1"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="Radio 1"
         android:textColor="@color/radiobuttonstate"/>
      

      颜色选择器是:

      <selector xmlns:android="http://schemas.android.com/apk/res/android">
          <item android:state_pressed="true" android:color="#000000"/>
          <item android:state_checked="true" android:color="#ffffff"/>
          <item android:color="#00f"/>
      </selector>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-20
        • 2011-08-29
        相关资源
        最近更新 更多