10

我有一个Android应用程序,包含一个ListView,我用它来显示设备列表的屏幕。这些设备保存在一个阵列中。阵列列表和列表视图Android阵列适配器不更新时阵列列表更改

我想使用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 
} 
} 

任何人都可以看到我要去哪里吗?

回答

36

对于一个ArrayAdapter,如果使用notifyDataSetChanged不仅工程addinsertremove,并在适配器clear功能。

  1. 使用Clear清除适配器 - arrayAdapter.clear()
  2. 使用Adapter.add并加入新成立的名单 - arrayAdapter.add(deviceList)
  3. 呼叫notifyDataSetChanged

替代方案:

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

    arrayAdapter = new ArrayAdapter<Device>(this, android.R.layout.simple_list_item_1, deviceList); 
    
  2. 创建一个从BaseAdapter和ListAdapter派生自己的类 为您提供了更多的灵活性。这是最值得推荐的。
0

您的方法addDevice正在导致无限循环。不要从自身调用一个方法像你在这里做什么:

deviceList = addDevice(); 
+0

麻烦,这只是我的一个错字...抱歉的混乱 –

+0

嘿pippa,它很酷,没有biggy。 – petey

+0

你可以发布你的createNewDeviceList()吗?它的机会是它不会向你的列表中添加任何新东西,并在原始中创建具有相同元素和顺序的新列表 – petey

9

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