Reputation: 893
I am trying to implement a Radio Group
dynamically, but I am getting an error saying "The child already has a parent call removeView() on parent first". Below is my code:
RadioGroup rg = new RadioGroup(getContext());
RadioButton[] allSongsRadio = new RadioButton[countOfAllSongs];
ArrayList<String> allSongsInMap = new ArrayList<>(countOfAllSongs);
for(final String eachMood : allSongs.keySet()) {
for(String eachSong : allSongs.get(eachMood)) {
allSongsInMap.add(eachMood+" : "+eachSong);
}
}
for(int i=0;i<allSongsInMap.size();i++){
final String eachSong = allSongsInMap.get(i);
LinearLayout playButtonAndSeekBar = new LinearLayout(getContext());
final FloatingActionButton playButton = new FloatingActionButton(getContext());
playButton.setBackgroundTintList(ColorStateList.valueOf(Color.WHITE));
playButton.setImageResource(R.drawable.play);
playButton.setSize(FloatingActionButton.SIZE_MINI);
playButton.setId(++playButtonId);
SeekBar seekBarForEachSong = new SeekBar(getContext());
layoutDetails = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutDetails.rightMargin = 50;
seekBarForEachSong.setLayoutParams(layoutDetails);
allSongsRadio[i] = new RadioButton(getContext());
playButtonAndSeekBar.addView(allSongsRadio[i]);
playButtonAndSeekBar.addView(playButton);
playButtonAndSeekBar.addView(seekBarForEachSong);
eachSongPanel.addView(playButtonAndSeekBar);
rg.addView(allSongsRadio[i]);
dialogContainer.addView(eachSongPanel);
}
dialogContainer.addView(rg);
}
Need help guys.
Upvotes: 0
Views: 196
Reputation: 924
You are seeing this error cause you are adding the same component to two different ViewGroup
which is not allowed in Android
(each element belong to one ViewGroup Parent), there is where you are doing so:
First you are adding the radio button here :
playButtonAndSeekBar.addView(allSongsRadio[i]);
And then you are adding it to the radio group :
rg.addView(allSongsRadio[i]);
At this point allSongsRadio[i]
belong to playButtonAndSeekBar
you cannot add it to another ViewGroup.
To correct you code, add the buttons to just the radio group, then finally add the whole radio group to playButtonAndSeekBar
regarding to your desired design.
Upvotes: 1