[英]Android Radio Button color change after click action
RadioGroup rg = new RadioGroup(context);
for (int i = 0; i < formElement.getRadioOptions().size(); i++) {
RadioButton radiobutton1 = new RadioButton(context);
radiobutton1.setText(formElement.getRadioOptions().get(i).getValue());
radiobutton1.setTextSize(TypedValue.COMPLEX_UNIT_PX, context.getResources().getDimension(R.dimen.meetingNoteCL));
radiobutton1.setHighlightColor(context.getResources().getColor(R.color.text_color));
rg.addView(radiobutton1);
}
textInputLayout.setTypeface(FontUtils.getFontTypeRegular(context));
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// checkedId is the RadioButton selected
int radioButtonID = group.getCheckedRadioButtonId();
View radioButton = group.findViewById(radioButtonID);
int idx = group.indexOfChild(radioButton);
formElement.setKey(formElement.getRadioOptions().get(idx).getKey());
formElement.setValue(formElement.getRadioOptions().get(idx).getValue());
}
});
上面的單選按鈕代碼。,但是在選擇之后我需要將特定的單選按鈕顏色單獨更改為藍色。 你能幫忙嗎
onCheckedChanged 回調有一個 checkedId,你可以用它來獲取那個特定的按鈕
在將它們添加到組之前,您只需要為按鈕分配唯一的 ID。 這是您為實現該目的而修改的代碼。
RadioGroup rg = new RadioGroup(context);
for (int i = 0; i < formElement.getRadioOptions().size(); i++) {
RadioButton radiobutton1 = new RadioButton(context);
//set a unique id
radiobutton1.setId(View.generateViewId());
radiobutton1.setText(formElement.getRadioOptions().get(i).getValue());
radiobutton1.setTextSize(TypedValue.COMPLEX_UNIT_PX, context.getResources().getDimension(R.dimen.meetingNoteCL));
radiobutton1.setHighlightColor(context.getResources().getColor(R.color.text_color));
rg.addView(radiobutton1);
}
textInputLayout.setTypeface(FontUtils.getFontTypeRegular(context));
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// checkedId is the RadioButton selected
int radioButtonID = group.getCheckedRadioButtonId();
RadioButton radioButton = (RadioButton)group.findViewById(radioButtonID);
//if its checked then change it's tintlist
if(radioButton.isChecked()){
radioButton.setButtonTintList(ColorStateList.valueOf(ContextCompat.getColor(context,R.color.yourcolor)));
}
int idx = group.indexOfChild(radioButton);
formElement.setKey(formElement.getRadioOptions().get(idx).getKey());
formElement.setValue(formElement.getRadioOptions().get(idx).getValue());
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.