我是一位有用的助手,可以为您进行翻译。
我有一个自定义视图,其中包含一个单选按钮和其他视图。
这个SingleRadioItem:
public class SingleRadioItem extends LinearLayout {
private TextView mTextKey;
private RadioButton mRadioButton;
private ImageView mImageSeparator;
public SingleRadioItem(Context context, AttributeSet attrs) {
super(context, attrs);
View view = LayoutInflater.from(context).inflate(R.layout.rtl_single_radio_item, this, true);
mTextKey = (TextView)view.findViewById(R.id.single_radio_item_text_key);
mRadioButton = (RadioButton)view.findViewById(R.id.single_radio_item_button);
mImageSeparator = (ImageView)view.findViewById(R.id.single_image_separator);
}
public void setKey(String key) {
mTextKey.setText(key);
}
public boolean getSelectedState() {
return mRadioButton.isSelected();
}
public void setSelectedState(boolean selected) {
mRadioButton.setSelected(selected);
}
}
我想创建此视图的多个实例,将它们添加到一个RadioGroup中,并将RadioGroup添加到一个LinearLayout中。但是当我这样做时,它允许我将所有单选按钮都设置为选中状态,这意味着RadioGroup没有正常工作(可能是因为我的处理方式不正确)。
RadioGroup radioGroup = new RadioGroup(this);
radioGroup.setOrientation(RadioGroup.VERTICAL);
SingleRadioItem radio1 = new SingleRadioItem(this, null);
SingleRadioItem radio2 = new SingleRadioItem(this, null);
radioGroup.addView(radio1);
radioGroup.addView(radio2);
updateDetailsView.addView(radioGroup);
显然,当我添加
RadioButton radio1 = new RadioButton(this);
时,RadioGroup 工作正常。我是否可以将包含单选按钮的视图添加到 Radiogroup 中,我是否遗漏了某些东西或根本不可能?
谢谢!
解决方案: 为了扩展 @cosmincalistru 的答案并帮助其他人:
对于每个添加到 LinearLayout 中的 SingleRadioItem,我都像这样附加了一个监听器:
radio1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (lastRadioChecked != null) {
lastRadioChecked.setCheckedState(false);
}
lastRadioChecked = (SingleRadioItem)v;
lastRadioChecked.setCheckedState(true);
}
});
你还需要将SingleRadioItem XML中的RadioButton View设置为clickable:false。