我有一个屏幕,包括一个ListView,我现在用的显示设备列表的Android应用程序。这些装置被保持在一个阵列。
I have an android app with a screen that comprises of a ListView, which I am using to display a list of devices. These devices are held in an array.
我想用一个ArrayAdapter显示的是在列表屏幕上的数组中开始。
I am trying to use the ArrayAdapter to display what is in the array on the screen in a list.
它的工作原理,当我第一次加载在 SetupActivity 类,但是,有设施,以在的AddDevice()方式添加新设备,这意味着数组控股该设备被更新。
It works when I first load the SetupActivity class, however, there is the facility to add a new device in the addDevice() method, which means the array holding the devices is updated.
我使用的 notifyDataSetChanged()这是应该更新列表,但它似乎并没有工作。
I am using notifyDataSetChanged() which is supposed to update the list but it doesn't seem to work.
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
}
}
任何人都可以看到我错了?
Can anyone see where I am going wrong?
对于ArrayAdapter, notifyDataSetChanged
只有当你使用添加,
插入
,删除
和明确
在适配器的功能。
For an ArrayAdapter, notifyDataSetChanged
only works if you use the add
, insert
, remove
, and clear
functions on the Adapter.
arrayAdapter.clear()
使用Adapter.add并加入新成立的名单 - arrayAdapter.add(DEVICELIST)
呼叫notifyDataSetChanged
Use clear to clear the adapter - arrayAdapter.clear()
Use Adapter.add and add the newly formed list - arrayAdapter.add(deviceList)
Call notifyDataSetChanged
替代方案:
重复此步骤,形成新的DEVICELIST后 - 但这是 冗余
Repeat this step after new devicelist is formed - but this is redundant
arrayAdapter = new ArrayAdapter<Device>(this, android.R.layout.simple_list_item_1, deviceList);
创建从BaseAdapter和ListAdapter派生自己的类, 为您提供了更多的灵活性。这是最值得推荐的。
Create your own class derived from BaseAdapter and ListAdapter that gives you more flexibility. This is most recommended.