欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ArrayAdapter.add-->java.lang.UnsupportedOperationException

程序员文章站 2022-06-04 10:37:17
...
[b]source code[/b]:
cities = new String[] { "Android", "BlackBerry", "J2ME","Symbian","Broncho", "LinuxMobile", "Palm", "WindwosMobile" }; 
cityList = Arrays.asList(cities);
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,cityList);


[b]situation[/b]:
利用ArrayAdapter.add方法添加spinner item时,抛出java.lang.[color=red]UnsupportedOperationException[/color]...

[b]root cause[/b]:[color=red]ArrayList size固定,导致ArrayAdapter也是resizeable[/color]

[b]solutions[/b]:
1.在创建ArrayAdapter时,不设置固定size的ArrayList
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item); 
cities = new String[] { "Android", "BlackBerry", "J2ME","Symbian","Broncho", "LinuxMobile", "Palm", "WindwosMobile" };
for(int i=0; i<cities.length; i++){
arrayAdapter.add(cities[i]);
}


2.利用[color=green]arrayAdapter.addAll(String...items)[/color]或者[color=green]arrayAdapter.addAll(Collection<? extends String> collection)[/color],需API11及以上提供支持