您好我想在我的数组适配器中添加一个项目,我使用下面的代码但是当我点击添加按钮时,我有一个力量关闭我做错了什么? (我正在使用列表片段)
public class list extends ListFragment {
String[] str = {""};
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
final View v = inflater.inflate(R.layout.main, null);
Button add = (Button) v.findViewById(R.id.button1);
final ArrayAdapter<String> ar = new ArrayAdapter<String>(getActivity(), R.layout.listback_layout, str);
final EditText enter = (EditText) v.findViewById(R.id.editText1);
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
ar.add(enter.getText().toString());
ar.notifyDataSetChanged();
ar.notifyDataSetInvalidated();
}
});
setListAdapter(ar);
return v;
}
}
这是日志:
12-08 16:50:20.801: E/AndroidRuntime(1832): FATAL EXCEPTION: main
12-08 16:50:20.801: E/AndroidRuntime(1832): java.lang.UnsupportedOperationException
12-08 16:50:20.801: E/AndroidRuntime(1832): at java.util.AbstractList.add(AbstractList.java:404)
12-08 16:50:20.801: E/AndroidRuntime(1832): at java.util.AbstractList.add(AbstractList.java:425)
12-08 16:50:20.801: E/AndroidRuntime(1832): at android.widget.ArrayAdapter.add(ArrayAdapter.java:179)
12-08 16:50:20.801: E/AndroidRuntime(1832): at mr.chag.va.lagar.lagari.mohasebelagari$1.onClick(mohasebelagari.java:27)
12-08 16:50:20.801: E/AndroidRuntime(1832): at android.view.View.performClick(View.java:4084)
12-08 16:50:20.801: E/AndroidRuntime(1832): at android.view.View$PerformClick.run(View.java:16966)
12-08 16:50:20.801: E/AndroidRuntime(1832): at android.os.Handler.handleCallback(Handler.java:615)
12-08 16:50:20.801: E/AndroidRuntime(1832): at android.os.Handler.dispatchMessage(Handler.java:92)
12-08 16:50:20.801: E/AndroidRuntime(1832): at android.os.Looper.loop(Looper.java:137)
12-08 16:50:20.801: E/AndroidRuntime(1832): at android.app.ActivityThread.main(ActivityThread.java:4745)
12-08 16:50:20.801: E/AndroidRuntime(1832): at java.lang.reflect.Method.invokeNative(Native Method)
12-08 16:50:20.801: E/AndroidRuntime(1832): at java.lang.reflect.Method.invoke(Method.java:511)
12-08 16:50:20.801: E/AndroidRuntime(1832): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
12-08 16:50:20.801: E/AndroidRuntime(1832): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-08 16:50:20.801: E/AndroidRuntime(1832): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:1)
这是因为,ArrayAdapter在被数组初始化时会将数组转换为无法修改的AbstractList(List)。
解决方案 - 在初始化ArrayAdapter时使用ArrayList而不是使用数组。
Examaple-
String[] array = {"a","b","c","d","e","f","g"};
ArrayList<String> lst = new ArrayList<String>();
lst.addAll(Arrays.asList(array));
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, lst);