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

从文件获取Bitmap为LinearLayout设置背景失败,路径无误求解决

解决LinearLayout本地图片背景不生效的问题

问题根源

你用data.getData().getPath()获取的Uri路径,在Android 10及以上的分区存储机制下,并不是真实的本地文件路径,导致BitmapFactory.decodeFile()无法正确读取图片,最终生成的bitmap5为null,自然设置背景无效。

修复方案

直接通过Uri获取输入流来解码Bitmap,而非依赖getPath():

try {
    InputStream inputStream = getContentResolver().openInputStream(data.getData());
    Bitmap bitmap5 = BitmapFactory.decodeStream(inputStream);
    if (bitmap5 != null) {
        BitmapDrawable bitmapDrawable = new BitmapDrawable(getResources(), bitmap5);
        mDrawingPad.setBackground(bitmapDrawable);
    }
    if (inputStream != null) {
        inputStream.close();
    }
} catch (IOException e) {
    e.printStackTrace();
}

额外注意事项

  • 确保已申请读取外部存储的权限:Android 6.0及以上需动态申请,同时在AndroidManifest.xml中声明:
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    
  • Android 13+可使用更细化的READ_MEDIA_IMAGES权限替代上述权限。
  • 检查mDrawingPad是否已正确初始化(非null),避免空指针导致设置操作未执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 13:05:18