如何解决以编程方式设置RadioGroup
| 我想创建一个自定义View
,其中包含RadioGroup
。我希望在RadioGroup
的内部设置RadioButtons
,以便第一个RadioButton
在左上方,第二个below4ѭ在其下方,第三个to在第一个one的右侧,而第四个在其下方。换句话说,我想创建一个组,其中单选按钮以正方形排列。我认为如果将组的方向设置为垂直,那么所有单选按钮都将位于一条直线上。另一方面,如果我将方向设置为水平,则单选按钮将全部位于一条直线上,变为水平。有什么方法可以做我想做的,还是我被迫将两个单独的RadioGroups
都水平放置?
解决方法
尝试不使用
RadioGroup
处理RadioButtons
。
将单个RadioButtons
连接起来,然后将其固定在ArrayList<RadioButton>
中。
List<RadioButton> radioButtons = new ArrayList<RadioButton>();
radioButtons.add( (RadioButton)findViewById(R.id.button1) );
radioButtons.add( (RadioButton)findViewById(R.id.button2) );
radioButtons.add( (RadioButton)findViewById(R.id.button3) );
etc.
为每个RadioButton
设置一个OnCheckedChangeListener
。
for (RadioButton button : radioButtons){
button.setOnCheckedChangeListener(new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if (isChecked) processRadioButtonClick(buttonView);
}
});
}
然后创建一种方法来取消选中未选中的RadioButtons
。
private void processRadioButtonClick(CompoundButton buttonView){
for (RadioButton button : radioButtons){
if (button != buttonView ) button.setChecked(false);
}
}
使用这种方法,“ 3”可以位于XML布局内的任何位置。
, 您应该从RadioGroup继承子类,并重写onLayout()方法。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。