2012-03-26 32 views
3

替換項是有沒有辦法在ArrayAdapter在ArrayAdapter

mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name); 
.. 
.. 
for (BluetoothDevice device : pairedDevices) { 
    String name = MPGDeviceDetailsControl.getDeviceDetails(this, device.getAddress(), device.getName()).getDisplayName(); 
    mPairedDevicesArrayAdapter.add(name + "\n" + device.getAddress()); 
} 

替換值。如果我想要替換的條目之一是有做,但不刪除和reinstering的任何方式。 問題在於它將它置於底部。

回答

14

像這樣的東西應該工作,以取代項目

int i = 0; 
for (BluetoothDevice device : pairedDevices) { 
    String name = MPGDeviceDetailsControl.getDeviceDetails(this, device.getAddress(), device.getName()).getDisplayName(); 
    mPairedDevicesArrayAdapter.remove(name); // has to copy all items back 1 position 
    mPairedDevicesArrayAdapter.insert(name + "\n" + device.getAddress(), i); // copy them +1 again 
    i++; 
} 

,但它會更有效,如果你有機會到被支持這個ArrayAdapter並更換列表/修改。

ArrayList<Strign> mList = new ArrayList<String>(); 
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name, mList); 

// setup 
mList.add... 
mPairedDevicesArrayAdapter.notifyDatasetChanged(); 

// change something 
mList.set(i, newValue); // just a replace, no copy 
mPairedDevicesArrayAdapter.notifyDatasetChanged(); 
+0

太棒了!非常感謝。 – theblitz 2012-03-26 09:29:28

-4

否您可以替換而不刪除或重新插入。

+0

請讓我們知道如何做到這一點。 – 2014-04-30 04:12:35

0

可以在不重新插入和使用嵌套適配器的情況下替換顯示值。簡單地改變原來的集合,並調用適配器的notifyDatasetChanged()

//adapter initialization 
MyClass[] someArray = ... ; 
ArrayList<Strign> adapter = new ArrayList<String>(context, R.layout.item_layout, someArray); 

//change something 
someArray[i] = newValue; 
adapter.notifyDatasetChanged(); 

這幾乎是一樣的zapl的答案只是它不使用嵌套適配器。當適配器使用List初始化時它應該工作,但我沒有測試過。