java - 具有 ArrayList 和 ListView 的 Android Array Adapter 在更改 arraylist 时不更新

标签 java android android-activity android-listview android-arrayadapter

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

谁能看出我哪里出错了?

最佳答案

对于 ArrayAdapter,notifyDataSetChanged 仅在您使用 addinsertremoveclear 适配器上的函数。

  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 的类 给你更多的灵 active 。这是最推荐的。

关于java - 具有 ArrayList 和 ListView 的 Android Array Adapter 在更改 arraylist 时不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13274952/

相关文章:

java - 您无法在使用 Glide 的回收 View 时启动已销毁 Activity 的加载

android - 按下后退按钮时避免调用 Activity 的 onCreate() 函数

android - 如何刷新一次调用后从Android tabview调用的webview

java - 我的应用程序在单击按钮后崩溃

java - Eclipse:具有相同名称但位置不同的多个项目

java - Erlang 和 Java 接口(interface)

android-activity - 具有 Activity 堆栈的全局应用程序类

java - 在Mac上使用mysql进行 hibernate 的步骤是什么?

android - 设置android View 可点击

java - 尝试从我的应用程序启动 Activity 但不断获得拒绝权限