Android getColor 方法過時及解決
阿新 • • 發佈:2019-02-05
Android getColor 方法過時
- 過時方法
@ColorInt
@Deprecated
public int getColor(@ColorRes int id) throws NotFoundException {
return getColor(id, null);
}
- 新增方法
@ColorInt
public int getColor(@ColorRes int id, @Nullable Theme theme) throws NotFoundException {
final TypedValue value = obtainTempTypedValue();
try {
final ResourcesImpl impl = mResourcesImpl;
impl.getValue(id, value, true);
if (value.type >= TypedValue.TYPE_FIRST_INT
&& value.type <= TypedValue.TYPE_LAST_INT) {
return value.data;
} else if (value.type != TypedValue.TYPE_STRING) {
throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
+ " type #0x" + Integer.toHexString(value.type) + " is not valid");
}
final ColorStateList csl = impl.loadColorStateList(this, value, id, theme);
return csl.getDefaultColor();
} finally {
releaseTempTypedValue(value);
}
}
- 推薦方法
ContextCompat.getColor(Context context, int id)
@ColorInt
public static int getColor(@NonNull Context context, @ColorRes int id) {
if (Build.VERSION.SDK_INT >= 23) {
return context.getColor(id);
} else {
return context.getResources().getColor(id);
}
}
context.getColor(int id)
@ColorInt
public final int getColor(@ColorRes int id) {
return getResources().getColor(id, getTheme());
}
context.getResources().getColor(int id);
@ColorInt
@Deprecated
public int getColor(@ColorRes int id) throws NotFoundException {
return getColor(id, null);
}