我有一个按钮,我想设置使用内部存储中的 png 文件的背景。对于 android api 16 及更高版本,这工作正常:
filePath = getActivity().getFileStreamPath(colorCodes.get(i-1));
temp.setBackground(Drawable.createFromPath(filePath.toString()));
在装有 4.0.4 的 Android 平板电脑上运行时,此部分会导致应用程序崩溃并出现 nosuchmethod 错误 (setBackground)。经过一番研究,我发现 setBackground 仅适用于 api 16+。在 SO 和其他几个地方环顾四周之后,看起来我需要使用 setBackgroundDrawable(已弃用)或 setBackgroundResource。我试过这个:
filePath = getActivity().getFileStreamPath(colorCodes.get(i-1));
if (android.os.Build.VERSION.SDK_INT < 16) {
temp.setBackgroundDrawable(Drawable.createFromPath(filePath.toString()));
} else {
temp.setBackground(Drawable.createFromPath(filePath.toString()));
}
注销时,它显示 setBackgroundDrawable 正在运行而不是 setBackground,但我得到相同的 nosuchmethod 错误(setBackground)。
另一个选项是 setBackgroundResource,但它接受一个 int 而不是一个 drawable。为此,我可以从 drawable 转换为 int 吗?
我可以在这里做什么来将按钮的背景设置为 API < 16 的内部存储中的文件?
谢谢。
***编辑 - 好的,这是有效的。只是错过了代码中其他地方有同样问题的一小部分。但是,使用已弃用的方法真的是唯一的方法吗?
最佳答案
Deprecation is a status applied to a computer software feature, characteristic, or practice indicating it should be avoided, typically because of it being superseded. The term is also sometimes used for a feature, design, or practice that is permitted but no longer recommended in other areas, such as hardware design or compliance to building codes. (source link)
现在我们可以回答您的问题了。
在 API 级别 16 之前,有一个名为 setBackgroundDrawable
的方法。在 API 级别 16 之后,谷歌决定为同样的目的编写一个新方法 setBackground
并推荐我们使用新方法。 (原因可以通过谷歌搜索找到。)
您可以对所有 api 级别使用 setBackgroundDrawable
方法。对此没有任何限制。但在 API 级别 16 之后,建议使用新方法 setBackground
。
但是您只能对运行在 API 级别 16 或更高级别上的设备使用 setBackground
方法。因此,如果您仅在代码中实现 setBackground
方法,对于运行在 API 级别 16 以下的设备,您将获得 MethodNotFoundException
。
总结一下;最好的做法是(对我来说这是必须的)先使用新方法,然后使用支持的 api 版本检查的弃用方法,例如;
if (android.os.Build.VERSION.SDK_INT < 16) {
temp.setBackgroundDrawable(Drawable.createFromPath(filePath.toString()));
} else {
temp.setBackground(Drawable.createFromPath(filePath.toString()));
}
关于android - 使用内部存储中的 .png 设置按钮背景资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20010330/