首页 > 解决方案 > 如何在一个片段中添加图像并将其显示在另一个片段中/通过android中的捆绑传递图像

问题描述

我想在一个片段中选择图像并将其显示在另一个片段中。
我怎样才能做到这一点。
我的代码是这样但不工作

button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
            startActivityForResult(gallery, 100);
        }
    });


@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    Uri imageUri;
    if (resultCode == RESULT_OK && requestCode == 100){
        imageUri = data.getData();
        file1path = imageUri.getPath();
        TVfrontimg.setText(file1path);
    }
}

我用捆绑发送这个

Bundle bundle = new Bundle();
bundle.putString("image1", file1path);

registerPartThreeFragment.setArguments(bundle);
transaction.replace(R.id.FLcontainer, registerPartThreeFragment);
transaction.addToBackStack(null);
transaction.commit();

在另一个片段中

String imgPath = getArguments().getString("image1");
Bitmap bitmap = BitmapFactory.decodeFile(String.valueOf(new File(imgPath)));
imageview.setImageBitmap(bitmap);

但它不工作。请帮助。


它给了我这个错误

2020-05-30 00:16:20.808 8995-8995/com.example.deliveryapp E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /raw/storage/emulated/0/DCIM/ Camera/IMG_20200319_173033.jpg(没有那个文件或目录)

标签: android

解决方案


请使用getDataString () 代替getData ()

if (resultCode == RESULT_OK && requestCode == 100){
        Uri imageUri = Uri.parse(data.getDataString());
        //imageUri = data.getData();
        file1path = imageUri.getPath();
        TVfrontimg.setText(file1path);
}

在将其设置为 ImageView 时,使用 ContentResolver 和输入流,如下所示:

ContentResolver cR = getApplication().getContentResolver();
        try {
            InputStream ip = cR.openInputStream(imageUri);
            Bitmap bmp = BitmapFactory.decodeStream(ip);
            imageView.setImageBitmap(bmp)
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

您必须这样做,因为您获得的 contentUri 与文件 Uri 不同。

希望这可以帮助。


推荐阅读