android - How add this view dynamically -


i want add view dynamically.

linearlayout mdescriptionlayout = (linearlayout)findviewbyid(r.id.descriptionlayout);   layoutinflater inflater = (layoutinflater)getsystemservice(layout_inflater_service); view view = inflater.inflate (r.layout.bonus_info_item, null,false); textview counter = (textview) view.findviewbyid(r.id.counter); textview descriptiontext = (textview) view.findviewbyid(r.id.descriptiontext); string [] s = {"","a","b", "c","d"};  (int = 1; < 5; i++){     counter.settext(string.valueof(i));     descriptiontext.settext(s[i]);     mdescriptionlayout.addview(view); } 

this main.xml , want add inflated view in linearlayout(@id/descriptionlayout)

<scrollview             android:layout_width="match_parent"             android:layout_height="match_parent"             android:fillviewport="true">     <relativelayout             android:layout_width="match_parent"             android:layout_height="match_parent">          <textview                 android:id="@+id/days"                 android:layout_width="wrap_content"                 android:layout_height="wrap_content"                    android:textsize="12sp"/>          <linearlayout                 android:id="@+id/descriptionlayout"                 android:layout_width="fill_parent"                 android:layout_height="wrap_content"                 android:layout_below="@id/bonuscardtitletext"                 android:orientation="vertical">          </linearlayout>         </relativelayout>     </scrollview> 

i don't understand problem in here can't add view dynamically , got error.

caused by: java.lang.illegalstateexception: specified child has parent. must call removeview() on child's parent first.         @ android.view.viewgroup.addviewinner(viewgroup.java:3339)         @ android.view.viewgroup.addview(viewgroup.java:3210)         @ android.view.viewgroup.addview(viewgroup.java:3155)         @ android.view.viewgroup.addview(viewgroup.java:3131) 

as error says,

the specified child has parent. must call removeview() on child's parent first.

you trying add child view parent , child has parent( after first iteration of for loop). either declaring , initializing view inside for loop or calling remove() each time should fix it. i'm not sure if trying add layout multiple times if can try

for (int = 1; < 5; i++) {     view view = inflater.inflate (r.layout.bonus_info_item, null,false);     textview counter = (textview) view.findviewbyid(r.id.counter);     textview descriptiontext = (textview) view.findviewbyid(r.id.descriptiontext);     counter.settext(string.valueof(i));     descriptiontext.settext(s[i]);     mdescriptionlayout.addview(view); } 

another way call mdescriptionlayout.removeview(view); don't think want in situation. initializing new view each iteration through loop should solve problem.


Comments