如何同步整个列表而不是仅显示可见记录

时间:2014-02-01 07:00:44

标签: android android-listview

尝试同步完整列表,点击按钮,但是而不是同步整个列表代码只同步列表中的可见记录,我的意思是当我滚动时下到列表,它不是同步记录。

例如,我在列表中有 300条记录,但只有10条记录可供相机屏幕显示,因为其余需要滚动,所以我的程序只会同步这10条记录,而不是整个列表,为什么?

    ImageButton buttonSync = (ImageButton) findViewById(R.id.sync_btn);
    buttonSync.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

             for(int i=0; i<lstView.getChildCount(); i++)
             {
                 startUpload(i);
             }          
        }
    });

1 个答案:

答案 0 :(得分:1)

getChildCount()方法仅返回列表视图中当前可见的子项总数。您必须从数据源(提供给listview适配器)获取要同步的数据。这是正确的做法。

但是,如果您必须同步列表视图中的项目并在同步后更新该特定视图,则可以利用适配器的notifyDataSetChanged 。您可以检查一个标志,以查看列表视图的特定记录是否要更新。

// An array of flags, as many as the number of records in the listview
// such that, flag[0] is set to true to indicate that the first item in the
// listview needs to call startUpload()
private SparseBooleanArray flags = new SparseBooleanArray();

// At onClick, set all the flags to indicate that some data needs to be synced
ImageButton buttonSync = (ImageButton) findViewById(R.id.sync_btn);
    buttonSync.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

             for(int position=0; position<listView.getAdapter().getCount(); position++)
             {
                 flags.put(position, true);
             }

             // Calling this would ensure a call to getView() on every
             // visible child of the listview. That is where we will check if
             // the data is to be synced and displayed or not
             ((BaseAdapter) listView.getAdapter()).notifyDataSetChanged();
        }
    });

@Override
// In getView of the listview's adapter
public View getView(int position, View convertView, ViewGroup parent) {

    // If this item is to be synced
    if(flags.get(position)) {
        startUpload();

        // Mark as synced
        flags.put(position, false);
    }

    // Rest of the method that draws the view....
}