2012-08-07 37 views
3

我有一个自定义视图,其中包含一个RadioButton视图。使用单选按钮添加自定义视图到广播组

的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); 

显然,当我添加RadioGroup运作良好。

它甚至可以添加一个视图,它拥有一个单选按钮到一个radiogroup,我只是缺少一些东西或根本不可能?

谢谢!

SOLUTION: 延长@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可点击:false。

回答

2

RadioButton必须直接隶属于RadioGroup,否则您的按钮将被视为来自不同的组。 最好的想法是在你的案例中的每个RadioButton上使用监听器。

编辑: 每当我想打一个单选按钮组作为一部分从一组,但不能使用RadioGroup中我做这样的事:

RadioButton r1,r2,....; 
// Instantiate all your buttons; 
... 
// Set listener on each 
for(each RadioButton) { 
    rx.setOnCheckedChangeListener(OnCheckedChangeListener() { 
     @Override 
     public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
      if (isChecked) { 
       //set all buttons to false; 
       for(each RadioButton) { 
        rx.setChecked(false); 
       } 
       //set new selected button to true; 
       buttonView.setChecked(true); 
      } 
     } 
    }); 
} 
0

当您将视图添加到RadioGroup时,仅当该视图仅是一个instanceof RadioButton时,该组才能正常工作。在你的情况下,你正在添加一个LinearLayout。所以SingleRadioItem应该扩展RadioButton。