当前位置: 首页 > 知识库问答 >
问题:

startActivityForResult的备选方案[重复]

丌官瀚
2023-03-14
 private void openFileChooser() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(intent, PICK_IMAGE_REQUEST);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
            && data != null && data.getData() != null) {
        mImageUri = data.getData();
        Picasso.get().load(mImageUri).into(productImage);
    }
}

共有1个答案

张华池
2023-03-14

以下是如何迁移到新Api。

步骤1:在类中声明一个top变量,用于从图库中获取图像

ActivityResultLauncher<String> mGetContent = registerForActivityResult(new GetContent(),
    new ActivityResultCallback<Uri>() {
        @Override
        public void onActivityResult(Uri uri) {
            //You are provided with uri of the image . Take this uri and assign it to Picasso
        }
});

步骤2:现在,在OnCreate中,在按钮上设置一个onClickListener,您希望用户通过该按钮转到库并以以下方式启动契约:


    selectButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            // Pass in the mime type you'd like to allow the user to select
            // as the input
            mGetContent.launch("image/*");
        }
    });
 类似资料: