更改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
}
}
有人能看出我错在哪里吗
# 1 楼答案
虽然公认的答案解决了问题,但对原因的解释是不正确的,因为这是一个重要的概念,我想我会尝试澄清
Slartibartfast关于
notifyDataSetChanged()
仅在适配器上调用add
、insert
、remove
或clear
时有效的解释是不正确的这种解释适用于
setNotifyOnChange()
方法,如果设置为true(默认情况下),当这四个操作中的任何一个发生时,该方法将自动调用notifyDataSetChanged()
我认为海报混淆了这两种方法
notifyDatasetChanged()
本身没有这些限制。它只是告诉适配器它正在查看的列表已经更改,而对列表的更改实际上是如何发生的并不重要虽然我看不到
createNewDeviceList()
的源代码,但我猜您的问题是因为适配器引用了您创建的原始列表,然后您在createNewDeviceList()
中创建了一个新列表,并且由于适配器仍然指向旧列表,所以无法看到更改slartibartfast提到的解决方案之所以有效,是因为它清除了适配器,并专门向该适配器添加了更新的列表。因此,您不会遇到适配器指向错误位置的问题
希望这对别人有帮助
# 2 楼答案
对于ArrayAdapter,
notifyDataSetChanged
只有在适配器上使用add
、insert
、remove
和clear
函数时才有效arrayAdapter.clear()
arrayAdapter.addAll(deviceList)
备选方案:
在新恶魔主义者形成后重复这一步——但这是错误的 多余的
# 3 楼答案
你的方法导致了无休止的循环。不要像您在这里所做的那样从自身调用方法: