更新ListView而不清除和闪烁

时间:2014-03-11 14:28:08

标签: java android multithreading listview

我需要刷新我的列表视图而不清除和闪烁,只显示新项目。但我不能马上做到这一点,因为我在几秒钟内得到了项目异步。由于在程序开始时清除适配器,此代码无法正常工作。

private void scanLeDevice(final boolean enable) {
    if (enable) {
        mLeDeviceListAdapterNew.clear();
        //mLeDeviceListAdapterNew.notifyDataSetChanged();

        // Stops scanning after a pre-defined scan period.
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mScanning = false;
                mBluetoothAdapter.stopLeScan(mLeScanCallback);

                runOnUiThread(new Runnable(){
                    @Override
                    public void run() {
                        mLeDeviceListAdapterNew.notifyDataSetChanged();
                        scanLeDevice(true);
                        //invalidateOptionsMenu();
                    }
                });
            }
        }, SCAN_PERIOD);


//Here my adapter updates with new items, 
//but it's shouldn't be displayed until I call adapter 
//refresh data in SCAN_PERIOD

2 个答案:

答案 0 :(得分:0)

您可以在设置适配器后立即调用notifyDataSetChanged();以反映列表更改。例如

ListView modeList = new ListView(getActivity());
            ArrayAdapter<CharSequence> adapter = ArrayAdapter
                    .createFromResource(getActivity(), R.array.PGA_Arrays,
                            R.layout.simple_spinner_item);
            modeList.setAdapter(adapter);
            adapter.notifyDataSetChanged();
希望这可以提供帮助。

答案 1 :(得分:0)

您需要在适配器中使用setData方法来更新数据。在notiftyDataSetChanged之前调用它。

公共类MyAdapter扩展了BaseAdapter {

public MyAdapter(...) {
    super(...);
}

@Override
public View getView(int position, View view, ViewGroup parent) {
    .....
    return view;

}

private void setData() {
    ...
    notifyDataSetChanged();
}

}