gpt4 book ai didi

android - 动态添加单选按钮时在单选组中发出问题

转载 作者:行者123 更新时间:2023-11-29 16:47:17 26 4
gpt4 key购买 nike

我没有看到任何与我的问题类似的帖子。我有一个 radiogroup,它有两个按钮,如下所示,

<RadioGroup
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<RadioButton
android:id="@+id/basic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<RadioButton
android:id="@+id/advanced"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RadioGroup>

在我的应用程序中,有时我需要一个动态添加的按钮,例如,

button=new AppCompatRadioButton(Activity.this);                                                              
button.setId(R.id.my_custom_id);
radiogroup.addView(button);

该 radio 组的 Oncheckedchangelistener 代码,

(radioGroup).setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId== R.id.basic) {
button.setChecked(false);
//my code
}
else if(checkedId== R.id.advanced) {
button.setChecked(false);
//my code
}
else {
//it is newly added button's part
}
}
});

The problem is, when the newly added button is checked, it is not unchecked when I am clicking other button. I tried to solve this in OnCheckedChangeListener by setting button.setChecked(false); when other buttons were checked. But it doesn't work. I don't know which makes problem in that.

任何人都可以帮助我。谢谢!

最佳答案

不是通过 java 代码以编程方式制作单选按钮,而是这样做,即将该单选按钮放入 xml 文件中,但最初将 android:visibility 设置为 gone,这将确保您的最后一个单选按钮不可见:

<RadioGroup
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<RadioButton
android:id="@+id/basic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<RadioButton
android:id="@+id/advanced"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>

<RadioButton
android:id="@+id/new_radio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility:"gone"
/>
</RadioGroup>

并且,当您需要使用单选按钮时,然后在 java 类中,使您的单选按钮再次可见,如下所示:

button.setVisibility(View.VISIBLE);

然后,您就可以使用 setOnCheckedChangeListener 了:

radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
//your code
});

关于android - 动态添加单选按钮时在单选组中发出问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47471915/

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