gpt4 book ai didi

android - 以编程方式设置 RadioGroup

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:47:50 28 4
gpt4 key购买 nike

我想创建一个包含 RadioGroup 的自定义 View。在 RadioGroup 内部,我想设置 RadioButtons,以便第一个 RadioButton 位于左上角,第二个是在那之下,第一个右边的第三个和下面的第四个。换句话说,我想创建一个组,其中单选按钮以某种正方形的形式布置。我想如果我将组的方向设置为垂直,那么所有单选按钮都会在一条直线上。另一方面,如果我将方向设置为水平,那么单选按钮将再次排成一条直线,水平方向。有没有办法做我想做的事,或者我是否被迫设置两个单独的 RadioGroups,都是水平方向?

最佳答案

尝试处理 RadioButtons不使用 RadioGroup .

连接个人 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.

设置一个 OnCheckedChangeListener对于每个 RadioButton .

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 布局中的任何位置。

关于android - 以编程方式设置 RadioGroup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6332042/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com