setBackgroundDrawable() deprecated

空扰寡人 提交于 2019-11-27 20:57:49
Alex K

It's an interesting topic. The way you are doing it is correct, apparently. It is actually just a naming decision change. As this answer points out, setBackground() just calls setBackgroundDrawable():

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

@Deprecated
public void setBackgroundDrawable(Drawable background) { ... }

You can see this thread for more information about all of this.

hedgehog

maybe you can try the following:

setBackgroundResource(R.drawable.img_wstat_tstorm);

It's funny because that method is deprecated, but if you look at the Android Source Code you'll find this:

   /**
     * 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);
    }

Correct as of 15th August 2018

Use the support libraries

Drawable drawable = ResourcesCompat.getDrawable(getResources(), drawableRes, null);
ViewCompat.setBackground(layout, drawable);

You are getting an error because getResources().getDrawable() takes an id (int) not a drawable as its argument. Try this:

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

This is correct in my case Solve this problem

 imageView.setBackgroundResource(images[productItem.getPosition()]);
//Java
view.setBackground(ActivityCompat.getDrawable(context, R.drawable.bg))

//Kotlin 
view.background = ActivityCompat.getDrawable(context, R.drawable.bg)

I'm using a minSdkVersion 16 and targetSdkVersion 23 The following is working for me, it uses ContextCompat.getDrawable(context, R.drawable.drawable);

Instead of using: layout.setBackground(getResources().getDrawable(R.drawable.img_wstat_tstorm));

Rather use:

layout.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.img_wstat_tstorm));

getActivity() is used in a fragment, if calling from a activity use this

Correct as of 23th November 2018

Kotlin:

view.background = resources.getDrawable(R.drawable.ic_image,theme)

If you include the Theme parameter.

Vando Sep
BitmapDrawable background = new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.mipmap.Nome_imgem));
        getSupportActionBar().setBackgroundDrawable(background);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!