不推荐使用setBackgroundDrawable()

Mak*_*oto 74 android deprecated deprecation-warning

所以我的sdk从15到21,当我打电话时setBackgroundDrawable(),Android Studio告诉我它已被弃用.

我想过用它来绕过它:

int sdk = android.os.Build.VERSION.SDK_INT;

if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
    layout.setBackgroundDrawable(getResources().getDrawable(R.drawable.img_wstat_tstorm));
} else {
    layout.setBackground(getResources().getDrawable(R.drawable.img_wstat_tstorm));
}
Run Code Online (Sandbox Code Playgroud)

但是,我在"setBackground()"收到错误.

那么,你会如何应对呢?

Ale*_*x K 94

这是一个有趣的话题.显然,你做这件事的方式是正确的.它实际上只是一个命名决定的变化.正如这个答案指出的那样,setBackground()只需来电setBackgroundDrawable():

public void setBackground(Drawable background) {
    //noinspection deprecation
    setBackgroundDrawable(background);
}

@Deprecated
public void setBackgroundDrawable(Drawable background) { ... }
Run Code Online (Sandbox Code Playgroud)

您可以查看此主题以获取有关所有这些的更多信息.

  • 你应该注意``setBackground()`对于API16之前不起作用,替代方案可以是`setBackgroundResource` (19认同)

hed*_*hog 23

也许你可以尝试以下方法:

setBackgroundResource(R.drawable.img_wstat_tstorm);
Run Code Online (Sandbox Code Playgroud)


Joa*_*huk 17

这很有趣,因为该方法已被弃用,但如果您查看Android源代码,您会发现:

   /**
     * Set the background to a given Drawable, or remove the background. If the
     * background has padding, this View's padding is set to the background's
     * padding. However, when a background is removed, this View's padding isn't
     * touched. If setting the padding is desired, please use
     * {@link #setPadding(int, int, int, int)}.
     *
     * @param background The Drawable to use as the background, or null to remove the
     *        background
     */
    public void setBackground(Drawable background) {
        //noinspection deprecation
        setBackgroundDrawable(background);
    }
Run Code Online (Sandbox Code Playgroud)


Stu*_*ell 10

正确截至2018年8月15日

使用支持库

Drawable drawable = ResourcesCompat.getDrawable(getResources(), drawableRes, null);
ViewCompat.setBackground(layout, drawable);
Run Code Online (Sandbox Code Playgroud)


Dav*_*ams 5

因为getResources()。getDrawable()接受一个id(int)而不是drawable作为参数,所以出现错误。尝试这个:

layout.setBackground(getResources().getDrawable(R.id.img_wstat_tstorm));


Mal*_*ngh 5

用这个:

myView.background = ContextCompat.getDrawable(context, R.id.my_drawable)
Run Code Online (Sandbox Code Playgroud)