setbackgrounddrawable过时的代替方法

本文讨论了在Android开发中遇到的一个废弃方法问题,具体是关于如何更新`setBackgroundDrawable`方法为`setBackgroundResource`以避免警告。通过实例演示了从Drawable到资源ID的变化,并解释了API级别的依赖关系。文章提供了从废弃方法到正确解决方案的详细步骤,包括XML属性的使用和API版本的考虑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【问题】

如下android代码:

Drawable statusQuestionDrawable = resources.getDrawable(R.drawable.status_question);
   statusView.setBackgroundDrawable(statusQuestionDrawable);

结果提示:

The method setBackgroundDrawable(Drawable) from the type View is deprecated

【解决过程】

1.很明显是该函数被废弃了。

但是换成啥,目前不知道。

2.参考:

The method setBackgroundDrawable(Drawable) from the type View is deprecated求解-优快云论坛-youkuaiyun.com-中国最大的IT技术社区

改为:

<span style="color:#008080">statusView.setBackground(resources.getDrawable(R.drawable.status_question));</span>

结果却又提示:

Call requires API level 16 (current min is 14): android.widget.TextView#setBackground

3.再改为:

<span style="color:#008080">statusView.setBackgroundResource(R.drawable.status_question);</span>

就可以了:

change from setBackgroundDrawable to setBackgroundResource

4.后来看到:

eclipse – Android – set layout background programmatically – Stack Overflow

android – Deprecated method, but replacing method requires higher api – Stack Overflow

其中解释的更清楚。

【总结】

当出现:

The method setBackgroundDrawable(Drawable) from the type View is deprecated

时,把:

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 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

谭祖爱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值