You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将startActivityForResult替换为ActivityResultLauncher适配废弃API

替换废弃的startActivityForResult为ActivityResultLauncher的实现方案

核心思路

仅在从AddNote页面成功添加笔记返回时更新RecyclerView,避免onResume触发的无意义更新,同时完成废弃API的替换。


1. 在MainActivity中声明ActivityResultLauncher

在类成员变量区域添加:

private ActivityResultLauncher<Intent> addNoteLauncher;

2. 初始化Launcher并处理返回结果

在MainActivity的onCreate方法中(setContentView之后),注册并初始化Launcher:

addNoteLauncher = registerForActivityResult(
    new ActivityResultContracts.StartActivityForResult(),
    result -> {
        // 仅当返回结果为成功状态时执行更新逻辑
        if (result.getResultCode() == Activity.RESULT_OK) {
            // 重新从数据库拉取最新数据
            dbHelper = new DbHelper(this);
            allItems = dbHelper.getNotesAndChecklists();
            // 更新RecyclerView
            noteAdapter.update(allItems);
        }
    }
);

3. 修改Fab点击事件的启动逻辑

替换原来的startActivityForResult调用:

fabNote.setOnClickListener(view -> {
    Intent intent = new Intent(MainActivity.this, AddNote.class);
    addNoteLauncher.launch(intent);
});

4. AddNote类代码无需改动

保持原有的结果设置和页面关闭逻辑即可:

Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();

方案优势

  • 完全替换废弃的startActivityForResult与onActivityResultAPI,符合Android最新开发规范
  • 仅在从AddNote页面成功返回时触发RecyclerView更新,避免了用户按Home键返回应用时的无效更新操作
  • 无需回传额外数据的场景下,仅通过结果码即可精准控制更新时机

内容的提问来源于stack exchange,提问作者java296642

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 19:24:10