如何替换startActivityForResult,因为它现在已被弃用——这是我完成项目所需的最后一部分



如何用ActivityResultLauncher替换它。对不起,伙计们,我只是编码和编程的新手。

SelectImageGallery.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image From Gallery"), 1);
}
});

您需要使用以下Kotlin代码在onCreate之外注册活动结果

val getContent = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
// Callback after selecting image
// Do whatever you want to do with uri
}
}
}

现在,当您想打开库来拾取图像时,不需要startActivityForResult(..)调用下面的方法

getContent.launch("image/*")
SelectImageGallery.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
result.launch(Intent.createChooser(intent, "Select Image From Gallery"));
}
});

在与侦听器相同的方法中:

ActivityResultLauncher<String> result = registerForActivityResult(
new ActivityResultContracts.GetContent(),
new ActivityResultCallback<Uri>() {
@Override
public void onActivityResult(Uri result) {
//DO whatever with received image content scheme Uri
}
});

相关内容

  • 没有找到相关文章

最新更新