问题来源:

在这篇博客里我介绍了如何在 xamarin.Android 中自定义 ​​View​​, 一切顺利。但是几个月后其他人测试我代码的时候 app 会在启动时 crash, 分析原因后发现是

york:image="@drawable/Icon"

这行代码的原因,debug 了很久很久。希望帮到其它遇到这个问题的人。

问题描述:

 image = BitmapFactory.DecodeResource(Resources, typedArray.GetResourceId(index, 0));

image == null --> bitmapfactory.decoderesource return null

把这些代码转换成 Java 代码在 AS 中测试: api 19 的模拟器上是没问题的,但是在 API 26 和 API 27 的手机上遇到了这个问题

但对于 Xamarin.Android 来说,在 api 19 和 api 26、27 上都有这个问题

解决办法

不存在 ​​image​​ 属性的错误

delete bin 和 obj 目录,restart vs, rebuild your project should resolve this issue

api 19 的模拟器上是没问题的,但是在 API 26 和 API 27 的手机上遇到了这个问题

我引用图片时是这么写的:

app:image="@mipmap/ic_launcher"

但是我的项目中存在 ​​res\mipmap-anydpi-v26​​​ 目录,目录下的 ​​ic_launcher​​​ 全称为: ​​ic_launcher.xml​​:

<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>

所以 ​​image = BitmapFactory.DecodeResource(Resources, typedArray.GetResourceId(index, 0));​​ 会 return null

​image = BitmapFactory.DecodeResource​​ 为 null

VS 中建议 ​​drawable​​​ 和 ​​mipmap​​ 目录下图片 名称全部小写, eg:

app:image="@drawable/icon2"

参考链接:

  • ​anydpi-v26​​​:通过将其放置在​​mipmap-anydpi-v26​​​文件夹中,资源系统将优先使用其它​​dpi​​​ 文件夹中的文件,仅仅在​​API 26+​​ 设备上才会使用。