学而实习之 不亦乐乎

Android:RadioButton 设置 setTextColor 失效

2022-01-13 10:41:20

由于有许多的RadioButton是动态的,需要使用代码动态地添加到 RadioGroup 中,如下:

for (int j = 0; j < 5; j++) {
    RadioButton tempButton = new RadioButton(context);
    tempButton.setButtonDrawable(context.getResources().getDrawable(android.R.color.transparent)); // 设置按钮的样式
    tempButton.setBackground(context.getResources().getDrawable(R.drawable.asthma_bg_radiobutton_selector));
    tempButton.setPadding(AppUtil.dip2px(context, 16), 0, 0, 0); // 设置文字距离按钮四周的距离

    tempButton.setTextColor(context.getResources().getColorStateList(R.drawable.asthma_text_color_selector));
    tempButton.setText(j + " test");
    tempButton.setTag(j);
    tempButton.setOnCheckedChangeListener(new RadioGroupChangeListener());
    radioGroup.addView(tempButton,
        LinearLayout.LayoutParams.MATCH_PARENT,
        AppUtil.dip2px(context, 48));
}

发现在代码 RadioButton 设置字体颜色是不能选中变色的,在xml里面设置是可以的。然后换成

ColorStateList colorStateList = context.getResources().getColorStateList(R.drawable.asthma_text_color_selector);  
tempButton.setTextColor(colorStateList);

使用枚举出来颜色,这样 setTextColor 能显示出你想要的效果了。