更改了arraylist时,ArrayList和ListView的Android数组适配器不会更新

问题描述 投票:11回答:3

我有一个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, android.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
}
}

任何人都可以看到我错在哪里?

java android android-activity android-listview android-arrayadapter
3个回答
37
投票

对于ArrayAdapter,只有在适配器上使用notifyDataSetChangedaddinsertremove函数时,clear才有效。

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

备择方案:

  1. 在新的设备列表形成后重复此步骤 - 但这是多余的 arrayAdapter = new ArrayAdapter<Device>(this, android.R.layout.simple_list_item_1, deviceList);
  2. 创建自己的派生自BaseAdapter和ListAdapter的类,为您提供更大的灵活性。这是最值得推荐的。

10
投票

虽然接受的答案解决了问题,但解释原因是不正确的,因为这是一个重要的概念,我认为我试图澄清。 Slartibartfast的解释是notifyDataSetChanged()仅在适配器上调用addinsertremoveclear时才有效。这种解释适用于setNotifyOnChange()方法,如果设置为true(默认情况下),则会在发生这四种操作中的任何一种时自动调用notifyDataSetChanged()。我认为这张海报混淆了这两种方法。 notifyDatasetChanged()本身没有这些限制。它只是告诉适配器它正在查看的列表已经改变,并且列表的更改实际上是如何发生的并不重要。虽然我看不到你的createNewDeviceList()的源代码,我猜你的问题来自于你有适配器引用你创建的原始列表,然后你在createNewDeviceList()中创建了一个新列表,并且因为适配器仍然是指向旧列表,它无法看到更改。提到的解决方案slartibartfast之所以有效,是因为它清除了适配器并专门将更新的列表添加到该适配器。因此,您没有适配器指向错误位置的问题。希望这有助于某人!


0
投票

您的方法和设备正在导致无限循环。不要像在这里一样调用自己的方法:

deviceList = addDevice();
© www.soinside.com 2019 - 2024. All rights reserved.