【问题标题】:How do I replace an item in a listview?如何替换列表视图中的项目?
【发布时间】:2014-08-24 20:19:03
【问题描述】:

我有一个由数组 adpater 填充的列表视图。用户从活动 a 开始,单击列表视图中的项目后,将转到活动 b,他们可以在其中编辑他们单击的项目。用户返回 A 后,来自 B 的已编辑项目通过 Intent 发送回 A。我希望将在 A 中单击的原始项目替换为从 B 的 Intent 接收到的数据。

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

        }
    });

谢谢!

【问题讨论】:

    标签: android listview adapter onitemclicklistener


    【解决方案1】:

    在您的原始活动中,您需要保留一个引用列表中所选项目索引的 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】:

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

      【讨论】:

      • 只是 .set ?我没有看到只有 .set(index, Object) 的方法
      • 它可用于 ArrayList。尝试将您的“值”转换为 ArrayList
      【解决方案3】:

      您可以使用 ArrayList#set() 方法,因此如果您的“值”数据集是 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();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-22
        • 1970-01-01
        • 2019-12-02
        • 2011-12-15
        • 1970-01-01
        • 2012-11-11
        • 2021-03-06
        • 1970-01-01
        相关资源
        最近更新 更多