setbackgrounddrawable过时的代替方法

【问题】

如下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求解-CSDN论坛-CSDN.NET-中国最大的IT技术社区

改为:

statusView.setBackground(resources.getDrawable(R.drawable.status_question));

结果却又提示:

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

3.再改为:

statusView.setBackgroundResource(R.drawable.status_question);

就可以了:

setbackgrounddrawable过时的代替方法_第1张图片

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
  • android:background
Parameters

resid 

你可能感兴趣的:([Android基础知识])