2

我的应用程序需要 SDK 9+,其中包含setBackgroundDrawable()API 级别 16 的代码。在编码或构建 apk 时我没有收到任何错误。但我在谷歌分析中收到了大约 50 份关于此错误的报告,在我的开发人员控制台中收到了一些报告。

当我运行 lint 检查器时,它也没有警告我。我正在使用日食。当您添加最小 API 不支持的方法或者它只是一个 Eclipse 错误时,它没有像通常那样编译失败的原因吗?

4

2 回答 2

6

首先,您在构建时不会出错,因为您可能正在使用 SDK 16+ 构建并且该方法就在那里。但是,如果您将 apk 安装到 2.1 Android 手机上,它会抛出MethodNotFound异常。因此,将来始终将您的 apk 安装在最小目标设备上,以查看您是否没有忘记某些内容。Min-Target 基本上只是 PLAY 商店的过滤器(以及 lint 警告等)

AFAIK 从imageView.setBackground(...)imageView.setBackgroundDrawable(...)只是一个 api 风格的设计选择。因此,如果您查看 Android SDK 18 的源代码,您将看到:

/**
     * Set the background to a given Drawable, or remove the background. If the
     * background has padding, this View's padding is set to the background's
     * padding. However, when a background is removed, this View's padding isn't
     * touched. If setting the padding is desired, please use
     * {@link #setPadding(int, int, int, int)}.
     *
     * @param background The Drawable to use as the background, or null to remove the
     *        background
     */
    public void setBackground(Drawable background) {
        //noinspection deprecation
        setBackgroundDrawable(background);
    }

因此,就目前而言,如果您使用其中一个,它绝对无关紧要 - 但当然这可能会改变(但未来不太可能这样做,因为它会破坏 SDK 16 之前完成的几乎所有应用程序) - 基本上setBackground()即使在 SDK 上也可以使用18+

因此,如果您想成为面向未来但丑陋的一面,您可以使用其他答案所描述的版本叉

if(Build.VERSION.SDK_INT >= 16) {
//new code
} else {
//deprecated code
}

只是一件事,也许这是个人风格偏好,我不会用这样的注释来抑制 Lint 警告:

@SuppressLint("NewApi")
@SuppressWarnings("deprecation")

我喜欢保留警告,因为以后如果我想重构/迁移到更高的 SDK,我可以轻松摆脱这些丑陋的开关。


更新Google 的 v4 支持库包含 sdk 样板代码的帮助类。在这种情况下,您将使用:

ViewCompat.setBackground(view,drawable);

它为您处理 SDK 检查。

于 2013-10-25T07:38:51.473 回答
0

似乎是 Eclipse 中的一个错误,或者您的 Eclipse 无法正常工作。但是您可以尝试项目清理并尝试。但是代码明智的你可以尝试这样的事情:

@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
public void setImage(ImageView imageView, BitmapDrawable bd) {
    if(Build.VERSION.SDK_INT > 16) {
        imageView.setBackground(bd);
    } else {
        imageView.setBackgroundDrawable(bd);
    }
}

您可以将此函数与 ImageView 和 bitmap drawable 一起调用。

于 2013-10-25T07:28:00.413 回答