如何在删除从 recyclerview 适配器打开的 activity 时更新 recyclerview

How to update recyclerview when an activity is deleted which is open from recyclerview adapter

我正在使用 Recyclerview 适配器来填充 Recyclerview。从 SQLite 填充 Recyclerview 后,如果用户想要打开 recyclerview 项目需要单击该项目和适配器打开相关 activity。这是一张图片,可以帮助您轻松理解。

当 activity 打开时,用户可以在删除数据后单击删除按钮从 SQLite 中删除 post recyclerview 应该动态更新数据。

您必须在 activity 中实现一个侦听器,它会告诉您的回收站视图物品已更改。我想您已经为回收者视图实现了自己的 onItemClickListener,因此您有位置并且可以轻松地从回收者视图数据集中删除项目。如需更多信息,请post您的代码。

此侦听器进入填充 Recycler 视图的 class。

     public interface DeletedListener {
         void deleted(int position);
     }

使您的 activity 实现此侦听器,并发送必须删除的位置。

    public void setListener(DeletedListener listener) {
       this.listener = listener;
    }

    DeletedListener listener;

从您的 activity 调用 setListener 方法,并从适配器调用 deleted 方法。

您还可以使用 StartActivityForResult 并使用第二个 activity 的结果删除第一个中的项目。

我的意思是:

  1. FirstActivity启动SecondActivity等待结果
  2. SecondActivity 将结果发送回 FirstActivity。只有当你删除 项目。
  3. 现在 FirstActivity 删除并刷新列表。

在第一个活动中:

Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);

在 SecondActivity 中,当您按下删除按钮时:

Intent returnIntent = new Intent();
returnIntent.putExtra("delete", true);
returnIntent.putExtra("position", position);
setResult(Activity.RESULT_OK, returnIntent);
finish();

最后,FirstActivity 处理结果:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 1) {
        if(resultCode == Activity.RESULT_OK){
            if (data.getBooleanExtra("delete") {
                 // get position and delete item from list and refresh
                 int position = data.getIntegerExtra("position");
            }
        }
        if (resultCode == Activity.RESULT_CANCELED) {
            //Write your code if there's no result
        }
    }
}//onActivityResult

已编辑:

在适配器构造函数中获取 activity 的上下文:

FirstActivity listener;

public myAdapter(Context context, List<String> items) {
        super(context, R.layout.row_edition, items);

        this.listener = ((FirstActivity) context);
        this.items = items;
    }

然后,在适配器内部,当您按下项目时,调用 activity 启动第二个:

listener.startSecondActivity(int position, parameters you need to use);

最后,在您的 FirstActivity

startSecondActivity(int position, parameters you need to use) {
    // whatever you have to do
    Intent i = new Intent(this, SecondActivity.class);
    // push position inside intent and whatever you need
    startActivityForResult(i, 1);
}

流程是:

  1. 推送项目
  2. 使用FirstActivityListener调用SecondActivity
  3. 在SecondActivity中删除并返回senr结果
  4. 在 FirstActivity 中使用辅助方法从适配器中删除项目 内部队列适配器

如果你在 recyclerview 中显示公司列表,一旦你点击显示公司的详细信息,然后你删除公司,你应该发现该项目消失了,这就是我的代码所做的

 protected void onResume()
{
    super.onResume();
    Log.i("TAG", "resume");
    if(yourlist.size() > 0)
    {
        yourlist.clear();
        yourlist.addAll(where your data come from 
        ex:databaseHelper.GetOrganization());
        youradapter.notifyDataSetChanged();
    }
}