有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

更改ArrayList时不更新ArrayList和ListView的java Android阵列适配器

我有一个安卓应用程序,屏幕上有一个ListView,我用它来显示设备列表。这些设备被放置在一个阵列中

我试图使用ArrayAdapter在屏幕上的列表中显示数组中的内容

当我第一次加载SetupActivity类时,它就可以工作了,但是,在addDevice()方法中可以添加一个新设备,这意味着保存设备的数组会被更新

我正在使用notifyDataSetChanged(),它应该会更新列表,但似乎不起作用

public class SetupActivity extends Activity
{   
    private ArrayList<Device> deviceList;

    private ArrayAdapter<Device> arrayAdapter;

    private ListView listView;

    private DevicesAdapter devicesAdapter;

    private Context context;

    public void onCreate(Bundle savedInstanceState)  //Method run when the activity is created
    {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.setup);  //Set the layout

        context = getApplicationContext();  //Get the screen

        listView = (ListView)findViewById(R.id.listView);

        deviceList = new ArrayList<Device>();

        deviceList = populateDeviceList();  //Get all the devices into the list

        arrayAdapter = new ArrayAdapter<Device>(this, 安卓.R.layout.simple_list_item_1, deviceList);

        listView.setAdapter(arrayAdapter);  
    }

    protected void addDevice()  //Add device Method (Simplified)
    {
        deviceList = createNewDeviceList();    //Add device to the list and returns an updated list

        arrayAdapter.notifyDataSetChanged();    //Update the list
}
}

有人能看出我错在哪里吗


共 (3) 个答案

  1. # 1 楼答案

    虽然公认的答案解决了问题,但对原因的解释是不正确的,因为这是一个重要的概念,我想我会尝试澄清

    Slartibartfast关于notifyDataSetChanged()仅在适配器上调用addinsertremoveclear时有效的解释是不正确的

    这种解释适用于setNotifyOnChange()方法,如果设置为true(默认情况下),当这四个操作中的任何一个发生时,该方法将自动调用notifyDataSetChanged()

    我认为海报混淆了这两种方法notifyDatasetChanged()本身没有这些限制。它只是告诉适配器它正在查看的列表已经更改,而对列表的更改实际上是如何发生的并不重要

    虽然我看不到createNewDeviceList()的源代码,但我猜您的问题是因为适配器引用了您创建的原始列表,然后您在createNewDeviceList()中创建了一个新列表,并且由于适配器仍然指向旧列表,所以无法看到更改

    slartibartfast提到的解决方案之所以有效,是因为它清除了适配器,并专门向该适配器添加了更新的列表。因此,您不会遇到适配器指向错误位置的问题

    希望这对别人有帮助

  2. # 2 楼答案

    对于ArrayAdapter,notifyDataSetChanged只有在适配器上使用addinsertremoveclear函数时才有效

    1. 使用clear清除适配器-arrayAdapter.clear()
    2. 使用适配器。addAll并添加新形成的列表arrayAdapter.addAll(deviceList)
    3. 调用notifyDataSetChanged

    备选方案:

    1. 在新恶魔主义者形成后重复这一步——但这是错误的 多余的

      arrayAdapter = new ArrayAdapter<Device>(this, android.R.layout.simple_list_item_1, deviceList);
      
    2. 创建从BaseAdapter和ListAdapter派生的自己的类 给你更多的灵活性。这是最推荐的
  3. # 3 楼答案

    你的方法导致了无休止的循环。不要像您在这里所做的那样从自身调用方法:

    deviceList = addDevice();