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


当前回答

你也可以用这个:

myListView.invalidateViews();

其他回答

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

本文中提出的解决方案是否有效主要取决于你的Android设备版本。例如,使用AddAll方法,你必须把android:minSdkVersion="10"在你的android设备。

为了解决所有设备的这个问题,我在适配器中创建了自己的方法,并在添加和删除方法中使用,该方法继承自ArrayAdapter,可以毫无问题地更新数据。

我的代码:使用我自己的数据类RaceResult,使用自己的数据模型。

ResultGpRowAdapter.java

public class ResultGpRowAdapter extends ArrayAdapter<RaceResult> {

    Context context;
    int resource;
    List<RaceResult> data=null;

        public ResultGpRowAdapter(Context context, int resource, List<RaceResult> objects)           {
        super(context, resource, objects);

        this.context = context;
        this.resource = resource;
        this.data = objects;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ........
        }

        //my own method to populate data           
        public void myAddAll(List<RaceResult> items) {

        for (RaceResult item:items){
            super.add(item);
        }
    }

ResultsGp.java

public class ResultsGp extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {

    ...........
    ...........
    ListView list = (ListView)findViewById(R.id.resultsGpList); 

    ResultGpRowAdapter adapter = new ResultGpRowAdapter(this,  R.layout.activity_result_gp_row, new ArrayList<RaceResult>()); //Empty data

   list.setAdapter(adapter);

   .... 
   ....
   ....
   //LOAD a ArrayList<RaceResult> with data

   ArrayList<RaceResult> data = new ArrayList<RaceResult>();
   data.add(new RaceResult(....));
   data.add(new RaceResult(....));
   .......

   adapter.myAddAll(data); //Your list will be udpdated!!!

如果你按照android指南,使用ContentProviders从数据库中获取数据,并使用CursorLoader和CursorAdapters在ListView中显示它,那么你对相关数据的所有更改将自动反映在ListView中。

你的getContext () .getContentResolver()。notifyChange (uri, null);在ContentProvider中的游标上进行调整就足以反映这些变化。不需要额外的工作。

但是当你不使用这些时,你需要告诉适配器数据集什么时候发生变化。此外,您还需要重新填充/重新加载数据集(例如列表),然后您需要在适配器上调用notifyDataSetChanged()。

如果数据集中没有变化,notifyDataSetChanged()将不起作用。 下面是在docs-方法上面的注释

/**
 * Notifies the attached observers that the underlying data has been changed
 * and any View reflecting the data set should refresh itself.
 */

在其他选项是onWindowFocusChanged方法,但肯定它敏感,需要一些额外的编码谁感兴趣

 override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)

       // some controls needed
        programList = usersDBHelper.readProgram(model.title!!)
        notesAdapter = DailyAdapter(this, programList)
        notesAdapter.notifyDataSetChanged()
        listview_act_daily.adapter = notesAdapter
    }

一旦修改了适配器中的数据,就可以在适配器对象上调用notifyDataSetChanged()。

关于如何/何时调用notifyDataSetChanged()的其他细节可以在这个谷歌I/O视频中查看。