So my sdk goes from 15 to 21 and when I call setBackgroundDrawable()
, Android Studio tells me that it\'s deprecated.
I thought of going around it using:
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));
Correct as of 23th November 2018
Kotlin:
view.background = resources.getDrawable(R.drawable.ic_image,theme)
If you include the Theme parameter.
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.
Correct as of 15th August 2018
Use the support libraries
Drawable drawable = ResourcesCompat.getDrawable(getResources(), drawableRes, null);
ViewCompat.setBackground(layout, drawable);
//Java
view.setBackground(ActivityCompat.getDrawable(context, R.drawable.bg))
//Kotlin
view.background = ActivityCompat.getDrawable(context, R.drawable.bg)