如何替换列表视图中的项目?

时间:2014-08-24 20:19:04

标签: android listview adapter onitemclicklistener

我有一个listview,由数组adpater填充。用户在活动a上开始,并且在单击列表视图中的项目之后将其带到活动b,在那里他们可以编辑他们单击的项目。用户返回A后,B中编辑的项目通过意图发回给A.我希望A中单击的原始项目被替换为从B的意图中收到的数据。

ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this,
            android.R.layout.simple_list_item_1, values);

    // setListAdapter(adapter);

    final ListView listView = (ListView) findViewById(R.id.list);
    listView.setAdapter(adapter);


//intent receiving data from Activity B; I want to add in statement to change the original item clicked to this new String, edit;
    Bundle fromedit = getIntent().getExtras();
    if (fromedit != null) {
        String edit = fromedit.getString("BENG");
        int ps = fromedit.getInt("POSITION");

    }

//onclicklistener for the listview
    listView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {

            Intent intent = new Intent(Notes.this, EditNote.class);

            intent.putExtra("KEY", values.get(position).toString());
            intent.putExtra("POSITION", position);

            startActivity(intent);

        }
    });

谢谢!

3 个答案:

答案 0 :(得分:0)

您是否尝试通过调用mList.set(index, Object);更新列表,然后刷新适配器以更新ListView显示的数据?

答案 1 :(得分:0)

在原始活动中,您需要保留一个int变量,引用列表中的选定项索引。所以你的onItemClick()看起来像那样:

    public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {

        currentSelected = position;
        Intent intent = new Intent(Notes.this, EditNote.class);

        intent.putExtra("KEY", values.get(position).toString());
        intent.putExtra("POSITION", position);

        startActivity(intent);

    }

当您从修改数据的活动返回时,您需要更新values列表中的项目并致电adapter.notifyDataSetChanged()

答案 2 :(得分:0)

您可以使用ArrayList#set()方法,因此如果您的'values'数据集是ArrayList。

java.util.ArrayList.set(int index,E element)用指定的元素替换此列表中指定位置的元素。

按如下方式修改代码:

//intent receiving data from Activity B; I want to add in statement to change the original item clicked to this new String, edit;

Bundle fromedit = getIntent().getExtras();
if (fromedit != null) {
    String edit = fromedit.getString("BENG");
    int ps = fromedit.getInt("POSITION");
    values.set(ps, edit);
    adapter.notifyDataSetChanged();
}