我有一个 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
仅在您使用 add
、insert
、remove
和 clear
适配器上的函数。
- 使用 clear 清除适配器 -
arrayAdapter.clear()
- 使用 Adapter.addAll 并添加新形成的列表 -
arrayAdapter.addAll(deviceList)
- 调用notifyDataSetChanged
备选方案:
在形成新的设备列表后重复此步骤 - 但这是 多余的
arrayAdapter = new ArrayAdapter<Device>(this, android.R.layout.simple_list_item_1, deviceList);
- 创建您自己的派生自 BaseAdapter 和 ListAdapter 的类 给你更多的灵 active 。这是最推荐的。
关于java - 具有 ArrayList 和 ListView 的 Android Array Adapter 在更改 arraylist 时不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13274952/