我有一个微调器,可以选择特定的文本。我正在以编程方式创建第二个微调器,并根据从第一个微调器中选择某项时激活的开关中的选择,将(不同的)字符串元素数组放入其中。第二个微调器位于LinearLayout内部。当我第一次从第一个微调器中选择一个选项时,一切都OK,当我选择另一个选项时,一切都崩溃了。您能帮我发现是什么导致这种情况发生吗?
final String[] as = {"AB", "AC", "AD", "AE", "AF", "AG","AH"};
final String[] bs = {"BC", "BD", "BE", "BF", "BG", "BH", "BI"};
在onCreate方法内部
//second Spinner
second_layout = findViewById(R.id.second_spinner);
spinner_2 = new Spinner(this);
开关
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String comb_selected = String.valueOf(spinner_1.getSelectedItem());
switch (comb_selected){
case "As"
second_layout.setVisibility(View.VISIBLE);
fillSecondSpinner(as);
break;
case "Bs":
second_layout.setVisibility(View.VISIBLE);
fillSecondSpinner(bs);
break;
default:
flag.setVisibility(View.INVISIBLE);
second_layout.setVisibility(View.INVISIBLE);
break;
使一切崩溃的功能
public void fillSecondSpinner(String[] combinations){
ArrayAdapter<CharSequence> adapter_comb = new ArrayAdapter(this, android.R.layout.simple_spinner_item, combinations);
adapter_comb.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_2.setAdapter(adapter_villes);
second_layout.addView(spinner_2);
}
这是我得到的错误:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.exercice1.spinner2, PID: 2304
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:4417)
at android.view.ViewGroup.addView(ViewGroup.java:4258)
at android.view.ViewGroup.addView(ViewGroup.java:4198)
at android.view.ViewGroup.addView(ViewGroup.java:4171)
at com.exercice1.spinner2.MainActivity.fillSecondSpinner(MainActivity.java:49)
at com.exercice1.spinner2.MainActivity.onItemSelected(MainActivity.java:68)
at android.widget.AdapterView.fireOnSelected(AdapterView.java:931)
at android.widget.AdapterView.dispatchOnItemSelected(AdapterView.java:920)
at android.widget.AdapterView.-wrap1(AdapterView.java)
at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:890)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Application terminated.
答案 0 :(得分:1)
那么,您需要先删除旧视图,然后再删除新视图。 在添加之前尝试调用此方法:
second_layout.removeAllViews()