我正在尝试创建一个Listview,其中每个Listview位置都添加了多个radiobuttons。 我不知道该怎么做,并尝试找到一些解决方案,但它们都没有起作用。
这是我的代码。
public class Bouw_onderdeel extends Activity {
public String[] naam = {"Bouw onderdeel", "Kapconstructie","Kapconstructieve bevesiging","Doorbuiging","Vochtinwerking","Dakconstructie","Constructieve bevesiging","Doorbuiging","Vochtinwerking","Waterkerende lagen","Waterdichtheid (folie)laag","Lekwaterafvoerend vermogen","Detaillering aan dakvoet","Thermischeisolatie","Bevestiging","Aansluitdetails","Isolerend vermogen","Dakpannen en vorsten","Conditie dakpannen en vorsten","Breukschade","Vorstschade","Afschilfering","Aangroei algen en mos"};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bouwonderdeel_layout);
getActionBar().setDisplayHomeAsUpEnabled(true);
//RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.layoutBouwonderdeel);
ListView list = new ListView(this);
list.setAdapter(new MyAdapter(this, naam));
setContentView(list);
}
private class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context context, String[] strings) {
super(context, -1, -1, strings);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout listLayout = new LinearLayout(Bouw_onderdeel.this);
listLayout.setLayoutParams(new AbsListView.LayoutParams(
AbsListView.LayoutParams.WRAP_CONTENT,
AbsListView.LayoutParams.WRAP_CONTENT));
listLayout.setId(5000);
RadioButton rbtn = new RadioButton (Bouw_onderdeel.this);
RadioGroup rbg = new RadioGroup(Bouw_onderdeel.this);
TextView listText = new TextView(Bouw_onderdeel.this);
listText.setId(5001);
for (int i = 0; i < 5; i++) {
rbg.addView(rbtn);
}
listLayout.addView(rbg);
listLayout.addView(listText);
listText.setText(super.getItem(position));
return listLayout;
}
}
这是错误消息。
10-27 15:25:19.495: E/AndroidRuntime(18261): FATAL EXCEPTION: main
10-27 15:25:19.495: E/AndroidRuntime(18261): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
10-27 15:25:19.495: E/AndroidRuntime(18261): at android.view.ViewGroup.addViewInner(ViewGroup.java:3739)
10-27 15:25:19.495: E/AndroidRuntime(18261): at android.view.ViewGroup.addView(ViewGroup.java:3610)
10-27 15:25:19.495: E/AndroidRuntime(18261): at android.widget.RadioGroup.addView(RadioGroup.java:141)
10-27 15:25:19.495: E/AndroidRuntime(18261): at android.view.ViewGroup.addView(ViewGroup.java:3555)
10-27 15:25:19.495: E/AndroidRuntime(18261): at android.view.ViewGroup.addView(ViewGroup.java:3531)
10-27 15:25:19.495: E/AndroidRuntime(18261): at nl.opensourcevoormkb.Bouw_onderdeel$MyAdapter.getView(Bouw_onderdeel.java:54)
答案 0 :(得分:3)
在循环内初始化RadioButtons。
RadioGroup rbg = new RadioGroup(Bouw_onderdeel.this);
for (int i = 0; i < 5; i++) {
RadioButton rbtn = new RadioButton (Bouw_onderdeel.this);
rbg.addView(rbtn);
}