在沒有棄用警告的情況下獲取資源

使用 Android API 23 或更高版本,通常可以看到這樣的情況:

StackOverflow 文件

這種情況是由 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);
...