android 解决setbackgrounddrawable过时



今天,简单讲讲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 Attributes
Parameters

resid 



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过时就讲完了。


就这么简单。

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值