问题描述
我有一个 TableLayout,我想在每一行的第三列放置一个单选组.我像这样构建 RadioButtons:
I have a TableLayout and in the third column of every row I want to place a radio group.I build the RadioButtons like this:
rg = (RadioGroup) findViewById(R.id.radioGroup1);
for (int k = 0; k < size; k++) {
rb[k] = new RadioButton(context);
rg.addView(rb[k]);
}
但是这会导致我的应用崩溃,有什么想法吗?
However this cause my app to crash, any ideas?
推荐答案
你正在构建一个长度为 megethos
的原始数组,但你的循环使用长度 size
.如果 megethos
和 size
是不同的值,这可能会导致许多不同类型的错误......但是所有这些都是多余的,因为 RadioGroup 会为您保持这个数组是最新的.
You are building a primitive array with the length of megethos
, but your loop uses the length size
. If megethos
and size
are different values this can cause many different types of errors... But all of this redundant since a RadioGroup keeps this array up to date for you.
我会尝试这样的:
RadioGroup group = (RadioGroup) findViewById(R.id.radioGroup1);
RadioButton button;
for(int i = 0; i < 3; i++) {
button = new RadioButton(this);
button.setText("Button " + i);
group.addView(button);
}
当你想在 index
引用一个按钮时:
And when you want to reference a button at index
:
group.getChildAt(index);
另外,请始终发布您的 logcat 错误,它确切地告诉我们出了什么问题以及在哪里查看.否则我们只能这样猜测.
Also please always post your logcat errors, it tells us exactly what went wrong and where to look. Otherwise we have to guess like this.
更新
错误是因为您试图将同一个按钮添加到两个不同的布局中:
The error is because you are trying to add the same button to two different layouts:
tr[k].addView(rb[k]);
rg.addView(rb[k]);
一个视图只能有一个父视图.据我所知,如果没有首先进行大量定制,您无法将 RadioGroup 拆分为多个视图.然而,ListView 已经具有类似于 RadioGroup 的内置功能 setChoiceMode():
a view can only have one parent. As far as I know you cannot break a RadioGroup apart into multiple views without a lot of customization first. However a ListView already has the built-in feature setChoiceMode() that behaves like a RadioGroup:
List<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, list);
ListView listView = (ListView) findViewById(R.id.list);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listView.setAdapter(adapter);
您可以轻松调整 simple_list_item_checked
以显示 SSID 和信号强度.希望有帮助.(如果您等待足够长的时间,imran khan 可能会通过图形更改剪切并粘贴我的答案,然后再次将其声明为他自己的.)
You can easily adapt simple_list_item_checked
to display the SSID and signal strength. Hope that helps. (If you wait long enough imran khan might cut & paste my answer with graphical change, then claim it as his own again.)
这篇关于如何将单选按钮添加到单选组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!