简体   繁体   中英

How to fix addView/removeView from crashing app

I am using a switch method to determine whether or not to show elements in my view based on the selected value of my spinner. I can remove views without any problem but when I change my selection in my spinner then I am unable to add the view back as the app crashes.

I have tried to remove all the views by default and then adding it in each switch case as I need it but the app crashes when I add a new view. I have tried to add and remove the views in each case without using default but still keeps crashing when I add a view to the list.

LinearLayout has an id of reps_layout

switch (a){

case "one":                       
myLayout.removeView(rowView.findViewById(R.id.reps_layout));
break;

case "two":
myLayout.addView(rowView.findViewById(R.id.reps_layout));
break;

default:
//myLayout.removeView(rowView.findViewById(R.id.reps_layout));
}

When I select case "one" the expected result should have the list but has removed the sets_field. Then when I select case "two" I want to add the reps_layout back to the list.

You add your LinearLayout like this. In any case you will need a parent layout.

 switch (a){ case "one": myLayout.removeView(rowView.findViewById(R.id.reps_layout)); break; case "two": LinearLayout layout =new LinearLayout(this); layout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); myLayout.addView(layout)); break; default: //myLayout.removeView(rowView.findViewById(R.id.reps_layout)); } 

I dont know your project, but consider that it maybe makes more sense to just set the visibility of the view to GONE rather then hide it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM