今天,简单讲讲android如何解决
setbackgrounddrawable过时的问题。
之前,自己也讲了一些函数的过时的替代函数,昨天,自己在代码里又发现了setbackgrounddrawable过时,于是自己在网上查找了资料,最终解决了问题。这里记录一下。
setBackgroundDrawable()在API 16(4.1)已经过时了
4.1之后有两种方法可以代替:
a、使用setBackgroundResource替代
setBackgroundDrawable
换为
setBackgroundResource
即可。
且传入的参数直接是resource的id,无需再去通过ID获得View,更加方便。
附上对应的API的解释:
void android.view.View.setBackgroundResource(int resid) public void setBackgroundResource (int resid)Added inAPI level 1 Set the background to a given resource. The resource should refer to a Drawable object or 0 to remove the background. Related XML AttributesParametersresid |
b、使用setBackground替代
例如:
textView.setBackgroundResource(R.drawable.icon);
textView.setBackground(ContextCompat.getDrawable(this, R.drawable.icon));
setBackgroundResource方法在内部还是调用的setBackground方法,而setBackground内部调用的还是setBackgroundDrawable方法
setBackground源码:
public void setBackground(Drawable background) {
//noinspection deprecation
setBackgroundDrawable(background);//这里
}
setBackgroundResource源码:
@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和setBackgroundResource都可以替代setbackgrounddrawable,但是setBackground是从API 16以后才有的,之前没有这个函数。所以最好使用setBackgroundResource,这个方法是从Api 1开始就有,所以就不用担心了。
如有需要使用setBackground,需要判断API的版本,其实也很简单:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { setBackground(drawable); } else { setBackgroundDrawable(drawable); }
对于API大于或等于16 的 android 版本,使用setBackground,对于API小于16的版本,使用setBackgroundDrawable。
android 解决setbackgrounddrawable过时就讲完了。
就这么简单。