从文件获取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
相关产品推荐
相关产品推荐

