如何刷新一个Android列表视图后添加/删除动态数据?


当前回答

我认为这取决于你对刷新的定义。您的意思是应该刷新GUI显示,还是应该刷新子视图,以便您可以通过编程调用getChildAt(int)并获得与适配器中内容对应的视图?

如果希望刷新GUI显示,则调用适配器上的notifyDataSetChanged()。下次重绘时,GUI将被刷新。

如果您希望能够调用getChildAt(int)并获得反映适配器中的内容的视图,则调用layoutChildren()。这将导致从适配器数据重构子视图。

其他回答

我只能通过获得新的适配器数据来获得notifyDataSetChanged,然后为列表视图重置适配器,然后像这样调用:

    expandableAdapter = baseFragmentParent.setupEXLVAdapter();
    baseFragmentParent.setAdapter(expandableAdapter);
    expandableAdapter.notifyDataSetChanged(); 

我也是一样,在一个片段中,我想用一段时间内扫描的BLE设备的mac地址填充一个ListView(在一个TextView中)。

我所做的是:

public class Fragment01 extends android.support.v4.app.Fragment implements ...
{
    private ListView                listView;
    private ArrayAdapter<String>    arrayAdapter_string;

...

@Override
public void onActivityCreated(Bundle savedInstanceState)
{
    ...
    this.listView= (ListView) super.getActivity().findViewById(R.id.fragment01_listView);
    ...
    this.arrayAdapter_string= new ArrayAdapter<String>(super.getActivity(), R.layout.dispositivo_ble_item, R.id.fragment01_item_textView_titulo);
    this.listView.setAdapter(this.arrayAdapter_string);
}


@Override
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord)
{
    ...
    super.getActivity().runOnUiThread(new RefreshListView(device));
}


private class RefreshListView implements Runnable
{
    private BluetoothDevice bluetoothDevice;

    public RefreshListView(BluetoothDevice bluetoothDevice)
    {
        this.bluetoothDevice= bluetoothDevice;
    }

    @Override
    public void run()
    {
        Fragment01.this.arrayAdapter_string.add(new String(bluetoothDevice.toString()));
        Fragment01.this.arrayAdapter_string.notifyDataSetChanged();
    }
}

然后ListView开始动态地填充找到的设备的mac地址。

如果您正在使用SimpleCursorAdapter,请尝试在Cursor对象上调用requery()。

对我来说,在sql数据库中更改信息后,没有什么可以刷新列表视图(具体是可扩展的列表视图),所以如果notifyDataSetChanged()没有帮助,你可以尝试先清除你的列表,并在调用notifyDataSetChanged()后再次添加它。例如

private List<List<SomeNewArray>> arrayList;
List<SomeNewArray> array1= getArrayList(...);
List<SomeNewArray> array2= getArrayList(...);
arrayList.clear();
arrayList.add(array1);
arrayList.add(array2);
notifyDataSetChanged();

希望你能理解。

当使用SimpleCursorAdapter时,可以在适配器上调用changeCursor(newCursor)。