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

Pip*_*ith 11 java android android-arrayadapter android-listview android-activity

我有一个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
}
}
Run Code Online (Sandbox Code Playgroud)

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

Sla*_*ast 37

对于一个ArrayAdapter,notifyDataSetChanged只有当你使用的作品add,insert,remove,和clear在适配器的功能.

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

备择方案:

  1. 在新的设备列表形成后重复此步骤 - 但这是多余的

    arrayAdapter = new ArrayAdapter<Device>(this, android.R.layout.simple_list_item_1, deviceList);
    
    Run Code Online (Sandbox Code Playgroud)
  2. 创建自己的派生自BaseAdapter和ListAdapter的类,为您提供更大的灵活性.这是最值得推荐的.


小智 10

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