How to Refresh Android List Adapter, so it shows new-added items

后端 未结 4 1686
一向
一向 2020-12-20 15:51

I was working on a project. It\'s just showing a list of tasks and Adding new tasks to it. I have 3 CLASSES. One for adding, One for view and One to hold all information (or

4条回答
  •  时光取名叫无心
    2020-12-20 16:16

    The solutions proposed thus far work, but are dependent on the Android version of your device. For example, to use the AddAll method you have to put android:minSdkVersion="10" in your android device.

    To solve this questions for all devices I have created my on own method in my adapter and use inside the add and remove method inherits from ArrayAdapter that update you data without problems.

    My Code: Using my own data class RaceResult, you use your own data model.

    ResultGpRowAdapter.java

    public class ResultGpRowAdapter extends ArrayAdapter {
    
        Context context;
        int resource;
        List data=null;
    
            public ResultGpRowAdapter(Context context, int resource, List 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 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()); //Empty data
    
       list.setAdapter(adapter);
    
       .... 
       ....
       ....
       //LOAD a ArrayList with data
    
       ArrayList data = new ArrayList();
       data.add(new RaceResult(....));
       data.add(new RaceResult(....));
       .......
    
       adapter.myAddAll(data); //Your list will be udpdated!!!
    

提交回复
热议问题