如何根据`ArrayList`更新`ListView`? [英] How to update the `ListView` according to `ArrayList`?

查看:149
本文介绍了如何根据`ArrayList`更新`ListView`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有接触,我不断更新的数组。我希望我的的ListView 我的联系人更新。

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

我应该使用适配器是什么?我不能在网上找到关于适配器多的信息,让我怎么确保我的列表视图总是有我的阵列? (我一直在研究这个4个半小时!)

Should I use an Adapter for that? I cant find much information about Adapter online, so how do I make sure that my listview always has the contents of my Array? (I have been researching this for 4 and a half hours!)

例如,如果我有一个具有内容苹果橙色,然后一个数组我的名单也应该说苹果橙色

For example, if I have an array that has the contents "apple" and "orange", then my list should also say "apple" and "orange".

如果我选择删除苹果,那么我的名单应该说只是橙色。基本上,我的名单应始终是一样的我的数组。

If I chose to remove "apple", then my list should say just "orange". Basically, my list should always be the same as my array.

我看了<一个href=\"http://stackoverflow.com/questions/2394176/android-populating-a-listview-with-array-items\">this,但我会那么如何去删除和添加更多的项目进入我的列表?

I saw this, but then how would I go about deleting and adding more items to my list?

推荐答案

创建ListAdapter这样的事情。

Create a ListAdapter something like this.

public class MyListAdapter extends BaseAdapter {


  private ArrayList<String> 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;
  }
}

现在在你的活动

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

让假设你需要更新按钮点击列表视图。 IE浏览器。按钮单击您的数组中的值被改变了,你想更新列表视图。

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();
      }
    });

我没有写整个code。只是一个良好的开端给你。

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

这篇关于如何根据`ArrayList`更新`ListView`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆