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

Android:startActivityForResult废弃后获取Activity返回结果及requestCode处理

问题描述

原本通过startActivityForResult()从Activity获取返回结果,现在该方法已废弃,改用registerForActivityResult()实现时,不知道如何处理原逻辑中作为列表位置的requestCode(原代码中用requestCode对应列表项索引,用来更新对应位置的备忘录内容)。

尝试的代码片段:

ActivityResultLauncher<Intent> activityResultLaunch = registerForActivityResult(
        new ActivityResultContracts.StartActivityForResult(),
        new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result.getResultCode() == RESULT_OK) {
                    aMemo[requestCode] = it.getStringExtra("memo"); 
                    aa.notifyDataSetChanged(); 
                }
            }
        });

旧的完整代码(包含废弃方法):

public class MainActivity extends AppCompatActivity
        implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {

    String[] aMemo = { 
            "1. Touch to Edit MEMO",
            "2.","3.","4.","5.","6." };
    ListView lv; 
    ArrayAdapter<String> aa; 

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lv = (ListView)findViewById(R.id.listView);
        aa = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, aMemo);

        lv.setAdapter(aa);    
        lv.setOnItemClickListener(this);
        lv.setOnItemLongClickListener(this);
    }

    public void onItemClick(AdapterView<?> a, View v, int pos, long id) {
        Intent it = new Intent(this, Edit.class);
        it.putExtra("number", pos+1);      
        it.putExtra("memo", aMemo[pos]); 
        startActivityForResult(it, pos); 
    }

    public boolean onItemLongClick(AdapterView<?> a, View v, int pos, long id) {
        aMemo[pos] = (pos+1) + "."; 
        aa.notifyDataSetChanged();  
        return true;                
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent it) {
        if(resultCode == RESULT_OK) {
            aMemo[requestCode] = it.getStringExtra("memo"); 
            aa.notifyDataSetChanged(); 
        }
    }
}
解决方案

原逻辑中requestCode的核心作用是标记需要更新的列表项索引,在新的ActivityResult体系下,我们可以通过将索引存入启动Intent的extra中,编辑完成后再将索引随返回结果带回的方式替代原来的requestCode功能。

步骤1:注册ActivityResultLauncher

在MainActivity的onCreate方法中完成注册(必须在onCreate生命周期内注册,不能懒加载):

private ActivityResultLauncher<Intent> editMemoLauncher;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // 初始化列表、适配器的原有代码保持不变

    // 注册ActivityResultLauncher
    editMemoLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                    // 从返回的Intent中取出列表项索引和新备忘录内容
                    int pos = result.getData().getIntExtra("pos", -1);
                    String newMemo = result.getData().getStringExtra("memo");
                    if (pos != -1 && newMemo != null) {
                        aMemo[pos] = newMemo;
                        aa.notifyDataSetChanged();
                    }
                }
            });
}

步骤2:修改启动编辑Activity的逻辑

在onItemClick方法中,把列表项索引pos存入Intent的extra,然后用注册好的Launcher启动Activity:

public void onItemClick(AdapterView<?> a, View v, int pos, long id) {
    Intent it = new Intent(this, Edit.class);
    it.putExtra("number", pos+1);      
    it.putExtra("memo", aMemo[pos]);
    // 新增:传入当前列表项索引
    it.putExtra("pos", pos); 
    // 用Launcher替代废弃的startActivityForResult
    editMemoLauncher.launch(it); 
}

步骤3:修改Edit页面的返回逻辑

确保编辑完成后,把索引和新内容一起返回给MainActivity(示例为Edit页面保存按钮的点击逻辑):

// Edit页面中保存按钮的点击事件
saveButton.setOnClickListener(v -> {
    String inputMemo = editText.getText().toString().trim();
    Intent resultIntent = new Intent();
    // 带回列表项索引和格式化后的新内容
    resultIntent.putExtra("pos", getIntent().getIntExtra("pos", -1));
    resultIntent.putExtra("memo", getIntent().getIntExtra("number", 0) + ". " + inputMemo);
    setResult(RESULT_OK, resultIntent);
    finish();
});

注意事项

  • 直接移除旧的onActivityResult方法,新体系不再依赖该方法。
  • 处理返回结果时要判断result.getData()不为空,避免空指针异常。
  • 若不需要修改Edit页面逻辑,也可在返回时仅带回新内容,但必须保证返回Intent中包含传入的pos值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 17:45:48