Android 在没有“不推荐使用”警告的情况下获取资源

示例

使用Android API 23或更高版本,经常会出现这种情况:

这种情况是由于Android API在获取资源方面的结构性变化引起的。
现在的功能:

public int getColor(@ColorRes int id, @Nullable Theme theme) throws NotFoundException

应该使用。但是该android.support.v4库还有另一个解决方案。

将以下依赖项添加到build.gradle文件中:

com.android.support:support-v4:24.0.0

然后,支持库中的所有方法均可用:

ContextCompat.getColor(context, R.color.colorPrimaryDark);
ContextCompat.getDrawable(context, R.drawable.btn_check);
ContextCompat.getColorStateList(context, R.color.colorPrimary);
DrawableCompat.setTint(drawable);
ContextCompat.getColor(context,R.color.colorPrimaryDark));

此外,可以使用支持库中的更多方法:

ViewCompat.setElevation(textView, 1F);
ViewCompat.animate(textView);
TextViewCompat.setTextAppearance(textView, R.style.AppThemeTextStyle);
...