以编程方式设置一个RadioGroup

5

我想创建一个包含RadioGroup的自定义View。在RadioGroup内,我希望RadioButtons被设置成这样:第一个RadioButton在左上角,第二个在其下方,第三个在第一个右侧,第四个在其下方。换句话说,我想创建一个RadioButtons以正方形方式布局的组。如果我将该组的方向设置为垂直,那么所有的RadioButtons都将位于一条直线上。如果我将方向设置为水平,则RadioButtons也会在一条水平直线上。是否有办法实现我的需求,或者我必须设置两个不同方向的RadioGroups


你可以使用RelativeLayout而不是LinearLayout。 - Pratik
1
@Pratik那怎么会有帮助呢?那可以帮我相对于其他事物设置组,但按钮彼此之间的相对关系怎么办? - LuxuryMode
2个回答

32

尝试在不使用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);
    }

}

使用这种方法,RadioButtons可以放置在XML布局的任何位置。


很棒的回答Matt,你能否解释一下如何获取选定单选按钮的ID,我尝试过但失败了。期待您宝贵的回答。谢谢。 - MohanRaj S

0

谢谢!你有一个示例覆盖的样子,以实现我想做的事情吗? - LuxuryMode
你可以从Roman Nurik的仪表板视图中找到如何实现onLayout:https://gist.github.com/882650 - woodshy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接