I have a custom view that holds, among other views, a RadioButton.
The 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);
}
}
I want to create instances of this view, add them to a RadioGroup and add the RadioGroup to a LinearLayout. When I do so, it allows me to set all the radio buttons as selected, which means, the RadioGroup isn't functioning well (probably because how I do it..)
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);
Obviously, when I add RadioButton radio1 = new RadioButton(this);
the RadioGroup works well.
Is it even possible to add a view that holds a radio button to a radiogroup and I'm just missing something or not possible at all?
Thanks!
SOLUTION: To extend @cosmincalistru Answer and help others:
for each SingleRadioItem I added to the LinearLayout I attached a listener like this:
radio1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (lastRadioChecked != null) {
lastRadioChecked.setCheckedState(false);
}
lastRadioChecked = (SingleRadioItem)v;
lastRadioChecked.setCheckedState(true);
}
});
You also need to set the RadioButton View inside the SingleRadioItem XML to clickable:false.