How to update the `ListView` according to `ArrayList`?

前端 未结 5 467
傲寒
傲寒 2021-01-29 08:37

I have an array of contacts that I am constantly updating. I want my ListView to update with my contacts.

Should I use an Adapter for that? I

5条回答
  •  孤城傲影
    2021-01-29 09:26

    Create a ListAdapter something like this.

    public class MyListAdapter extends BaseAdapter {
    
    
      private ArrayList names = new ArrayList();
    
      @Override
      public int getCount() {
        return names.length;
      }
    
      @Override
      public Object getItem(int location) {
        return names[location];
      }
    
      @Override
      public long getItemId(int position) {
        return position;
      }
    
      private static class ViewHolder {
        public TextView listViewNgoName, listViewDistance, listViewRating, listViewAbout, ngoIcon;
      }
    
      public MyListAdapter(
          ArrayList names) {
        this.names = names;
      }
    
      @Override
      public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
         // Write code for instantiating a row based view.
        return convertView;
      }
    }
    

    Now in your Activity

        ArrayList names = new ArrayList();
        names.add("oranges");
        names.add("apple");
        ListView listView = (ListView) findViewById(R.id.listview);
        MyListAdapter adapter = new MyListAdapter(names);
        listView.setAdapter(adapter);
    

    Lets suppose you need to update the listview on the button click. ie. on button click the values in your array gets changed and you wanted to update the listView.

    Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            names.add("payaya");
            names.add("grapes");
            adapter.notifyDataSetChanged();
          }
        });
    

    I have not written the entire code. Just a head start for you.

提交回复
热议问题