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

Kotlin中onActivityResult已废弃,求替代实现方案(附问题代码)

替代废弃的onActivityResult:用Activity Result API处理图片裁剪结果

在AndroidX生态中,onActivityResult已被官方废弃,推荐使用Activity Result API来替代,以下是适配你现有图片裁剪逻辑的完整方案:

1. 确保依赖配置

确保项目已引入AndroidX Activity/Fragment KTX依赖(版本≥1.2.0),一般在build.gradle(Module)中:

dependencies {
    // 若已引入可忽略
    implementation "androidx.activity:activity-ktx:1.8.2"
    implementation "androidx.fragment:fragment-ktx:1.6.2"
}

2. 替换原有代码

步骤1:声明Activity Result Launcher

在你的Activity/Fragment类中,添加用于处理裁剪结果的ActivityResultLauncher实例:

private val cropImageLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
    when (result.resultCode) {
        RESULT_OK -> {
            val cropResult = CropImage.getActivityResult(result.data)
            cropResult?.uri?.let { uri ->
                image = uri
                Glide.with(this).load(image).into(binding.imgPick)
            }
        }
        else -> {
            Snackbar.make(binding.root, "Image not selected", Snackbar.LENGTH_SHORT).show()
        }
    }
}

步骤2:启动裁剪界面

将原来启动裁剪的startActivityForResult代码,替换为调用launcher的launch方法:

// 示例:构建裁剪Intent(根据你原有逻辑调整参数)
val cropIntent = CropImage.activity(yourSourceImageUri)
    .setGuidelines(CropImageView.Guidelines.ON)
    .getIntent(this)

// 替换原有的 startActivityForResult(cropIntent, CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
cropImageLauncher.launch(cropIntent)

3. 清理废弃代码

直接删除原有的onActivityResult重写方法即可,所有结果处理逻辑已迁移到launcher的回调中。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 17:10:37