目录
- 1、getResources().getColor()
- 2、getResources().getDrawable()
- 3、imageView.setBackgroundDrawable()
- 4、viewPager.setOnPageChangeListener()
概述
为了提高代码的整洁和性能,那些过时的方法最好还是不要使用了,Google都给我们提供有替代方法。如下持续更新中... ...
1、getResources().getColor()
过时方法:
getResources().getColor(R.color.colorAccent);
替代方法:
ContextCompat.getColor(this, R.color.colorAccent);
说明:源码对 23 版本前后做的兼容
@ColorInt
public static int getColor(@NonNull Context context, @ColorRes int id) {
return VERSION.SDK_INT >= 23 ?
context.getColor(id) :
context.getResources().getColor(id);
}
2、getResources().getDrawable()
过时方法:
getResources().getDrawable(R.drawable.ic_launcher_background);
替代方法:
ContextCompat.getDrawable(this, R.drawable.ic_launcher_background);
说明:源码是对16、21、以及21之后版本做的兼容。
@Nullable
public static Drawable getDrawable(@NonNull Context context, @DrawableRes int id) {
if (VERSION.SDK_INT >= 21) {
return context.getDrawable(id);
} else if (VERSION.SDK_INT >= 16) {
return context.getResources().getDrawable(id);
} else {
Object var3 = sLock;
int resolvedId;
synchronized(sLock) {
if (sTempValue == null) {
sTempValue = new TypedValue();
}
context.getResources().getValue(id, sTempValue, true);
resolvedId = sTempValue.resourceId;
}
return context.getResources().getDrawable(resolvedId);
}
}
3、imageView.setBackgroundDrawable()
过时方法:
Drawable drawable = ContextCompat.getDrawable(this,
R.drawable.ic_launcher_background);
imageView.setBackgroundDrawable(drawable);
替代方法:
imageView.setBackgroundResource(R.drawable.ic_launcher_background);
说明:源码对 setBackgroundDrawable 做了一定维护
@RemotableViewMethod
public void setBackgroundResource(@DrawableRes int resid) {
if (resid != 0 && resid == mBackgroundResource) {
return;
}
Drawable d = null;
if (resid != 0) {
d = mContext.getDrawable(resid);
}
setBackground(d);
mBackgroundResource = resid;
}
setBackground() 方法
public void setBackground(Drawable background) {
//noinspection deprecation
setBackgroundDrawable(background);
}
viewPager.setOnPageChangeListener()
过时方法:
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { })
替换方法:
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {})
说明:两种用法相同,只是还没有研究到替换的优点在哪里