Android ArrayAdapter.Add 方法不起作用 [英] Android ArrayAdapter.Add method not working

查看:47
本文介绍了Android ArrayAdapter.Add 方法不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ArrayAdapter.add() 方法对我不起作用.我使用带有 ADT 插件的 Eclipse Helios 3.6,目标源是 Froyo 2.2 模拟器和 2.2 HTC Evo 4g.这是我的java类

The ArrayAdapter.add() method is not working for me. I am using Eclipse Helios 3.6 with ADT Plugin, Target Source is a Froyo 2.2 emulator and 2.2 HTC Evo 4g. Here is my java class

    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.ArrayAdapter;

    public class Main extends Activity {

         @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            String[] entries = {"List Item A", "List Item B"};

            ArrayAdapter<String> arrAdapt=new ArrayAdapter<String>(this, R.layout.list_item, entries);

             arrAdapt.setNotifyOnChange(true);
             arrAdapt.add("List Item C");
        }
    }

这是我的列表项布局 (list_item.xml)

And here is my layout for the list item (list_item.xml)

<?xml version="1.0" encoding="utf-8"?>
<TextView
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  android:padding="10dp"
  android:textSize="12sp"
</TextView>

它在 LogCat 中给我和错误说

It is giving me and error in the LogCat that says

原因:java.lang.UnsupportedOperationException在java.util.AbstractList.add(AbstractList.java:411)在java.util.AbstractList.add(AbstractList.java:432)在android.widget.ArrayAdapter.add(ArrayAdapter.java:178)

Caused by: java.lang.UnsupportedOperationException at java.util.AbstractList.add(AbstractList.java:411) at java.util.AbstractList.add(AbstractList.java:432) at android.widget.ArrayAdapter.add(ArrayAdapter.java:178)

推荐答案

我只是在学习,但如果我正在阅读 source 正确,ArrayAdapter 的构造函数不会将引用复制到数组或列表中的每个元素.相反,它直接使用传入的列表,或者对于数组使用 asList() 将原始数组视为列表.由于 asList() 返回的列表仍然只是底层数组的表示,因此您不能做任何您不能用数组做的事情(例如调整大小).

I'm just learning, but if I'm reading the source correctly, ArrayAdapter's constructor doesn't copy references to each of the elements in the array or list. Instead, it directly uses the list that's passed in, or for an array uses asList() to treat the original array as a list. Since the list returned by asList() is still just a representation of the underlying array, you can't do anything (such as resize) that you couldn't do with an array.

尝试传递一个像 ArrayList 这样的列表而不是一个数组.

Try passing a list like ArrayList instead of an array.

ArrayList<String> entries = 
        new ArrayList<String>(Arrays.asList("List Item A", "List Item B"));

ArrayAdapter<String> arrAdapt=
        new ArrayAdapter<String>(this, R.layout.list_item, entries);

arrAdapt.setNotifyOnChange(true);
arrAdapt.add("List Item C");

这篇关于Android ArrayAdapter.Add 方法不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆