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

Fragment中从图库选图设置ImageView遇Bundle为空问题求助

我尝试了多种解决方案,这是目前最接近实现选择图片并显示功能的版本,但调试时发现Bundle为null。

onActivityResult 启动器(原代码)

activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
    @Override
    public void onActivityResult(ActivityResult result) {
        if (result.getResultCode() == RESULT_OK && result.getData() != null) {
            Bundle bundle = result.getData().getExtras();
            Bitmap bitmap = (Bitmap) bundle.get("data");

            imagePP.setImageBitmap(bitmap);
        }
    }
});

点击事件监听器(原代码)

add1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

        activityResultLauncher.launch(intent);
    }
});

问题原因

ACTION_PICK的返回机制并非通过Bundle传递Bitmap,它只会返回选中图片的Content URI,所以result.getData().getExtras()得到的必然是null。

修正后的实现代码

1. 调整ActivityResultLauncher逻辑

activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
    @Override
    public void onActivityResult(ActivityResult result) {
        if (result.getResultCode() == RESULT_OK && result.getData() != null) {
            // 获取选中图片的Content URI
            Uri imageUri = result.getData().getData();
            if (imageUri != null) {
                try {
                    // 通过URI解析得到Bitmap
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
                    imagePP.setImageBitmap(bitmap);
                } catch (IOException e) {
                    e.printStackTrace();
                    // 可添加读取失败的提示逻辑
                }
            }
        }
    }
});

2. 点击事件可保持不变

add1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent = new Intent(Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        activityResultLauncher.launch(intent);
    }
});

兼容性优化提示(Android 10+)

建议使用ContentResolver.openInputStream()替代MediaStore.Images.Media.getBitmap(),避免版本兼容问题:

// 替换Bitmap获取逻辑
InputStream inputStream = getContentResolver().openInputStream(imageUri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
inputStream.close();
imagePP.setImageBitmap(bitmap);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 18:30:54