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:
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));
}
But then, I get an error at "setBackground()".
So, how would you deal with it?
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.
maybe you can try the following:
setBackgroundResource(R.drawable.img_wstat_tstorm);
Correct as of 15th August 2018
Use the support libraries
Drawable drawable = ResourcesCompat.getDrawable(getResources(), drawableRes, null);
ViewCompat.setBackground(layout, drawable);
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);
}
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));
//Java
view.setBackground(ActivityCompat.getDrawable(context, R.drawable.bg))
//Kotlin
view.background = ActivityCompat.getDrawable(context, R.drawable.bg)
Use this:
myView.background = ContextCompat.getDrawable(context, R.id.my_drawable)
This is correct in my case
Solve this problem
imageView.setBackgroundResource(images[productItem.getPosition()]);
Correct as of 23th November 2018
Kotlin:
view.background = resources.getDrawable(R.drawable.ic_image,theme)
If you include the Theme parameter.
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
BitmapDrawable background = new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.mipmap.Nome_imgem));
getSupportActionBar().setBackgroundDrawable(background);
Related
Button setTextAppearance(Context context, int resid) is deprecated
and setTextAppearance(int resid) - only available for API level 23
What should I use instead?
Deprecated means that support will be dropped for it sometimes in the future, but it is still working as expected. On older APIs, there is no alternative, since the new setTextAppearance(int resid) got only released with API level 23.
If you want to be safe for a long time, you can use the following code:
if (Build.VERSION.SDK_INT < 23) {
yourButton.setTextAppearance(context, resid);
} else {
yourButton.setTextAppearance(resid);
}
This code prefers the new version on phones with API level 23 or higher, but uses the old one when the API level 23 one isn't available.
I am going to say the same this as #Daniel Zolnai. But do not make the check Build.VERSION>SDK_INT < 23 in all the places in your code. Put this in one place, so it will be easy for you to remove this in the future or make changes to it. So how to do it? I will do this for the yourButton case.
Never use Button or any other view provided by android just like that. I say this, because in the future you will need to tweak something and hence it's better to have your own MyButton or something of that sort. So create MyButton extends Button.
Inside MyButton, put the below code:
public void setTextAppearance(Context context, int resId) {
if (Build.VERSION.SDK_INT < 23) {
super.setTextAppearance(context, resId);
} else {
super.setTextAppearance(resId);
}
}
This way you can always use setTextAppearance without needing to worry about checking for BUILD versions. If in future, you plan to remove this whole thing, then you have to refactor in just one place. This is a bit of work, but in the long run, this will help you a lot and will reduce some maintanance nightmares.
Can anyone tell me the right way of using getDrawable() , I recall last time I used it was just fine with one parameter, but now I am getting this method is deprecated error, anyone? Bellow is the snippet I am trying to use
private void toggleUi() {
ImageView imageView = (ImageView) findViewById(R.id.silent_icon);
Drawable silentImage;
if(silent) {
silentImage = getResources().getDrawable(R.drawable.silent_on);
} else {
silentImage = getResources().getDrawable(R.drawable.silent_off);
}
imageView.setImageDrawable(silentImage);
}
Will be glad if anyone can help thanks.
Since API 22 you should call ContextCompat.getDrawable(context, R.drawable.***) instead of getResources().getDrawable(R.drawable.***).
You can see the documentation of ContextCompat from the support library for more details.
I want to change the background of my framelayout (which holds all my pages!) by:
FrameLayout fl = (FrameLayout)findViewById(R.id.container);
fl.setBackground(getResources().getDrawable(R.drawable.juraquiz_app_background));
but apparently I cant. Is there a way to do it, so its compatible with APIs lower than 16?
for API's lower that 16 you can use setBackgroundDrawable
Use different methods for different APIs:
final Drawable drw = getResources().getDrawable(R.drawable.juraquiz_app_background);
if(android.os.Build.VERSION.SDK_INT < 16)
{
fl.setBackgroundDrawable(drw);
}
else
{
fl.setBackground(drw);
}
You will need to add an annotation to your method (or to your class, if you prefer) to get rid of Lint warnings:
#SuppressLint("NewApi")
I have my app that requires SDK 9+ with code containing setBackgroundDrawable() which is API level 16. I did not get any error while coding or building the apk. but I got about 50 reports of this error happening in google analytics and a few reports in my developers console.
When I run the lint checker It also doesn't warn me. I am using eclipse. Is there a reason why it doesn't fail to compile like usually when you add a method that's not supported by the minimum API or is it simply an eclipse bug?
First of all you get no error when building since you probably are building with SDK 16+ and the method is there. But if you install the apk to a 2.1 Android phone it will throw a MethodNotFound Exception. So in the future ALWAYS install your apk on a min-target device to see if you didn't forget something. Min-Target basically is only a filter for the PLAY store (and for lint warnings, etc.)
AFAIK moving from imageView.setBackground(...) to imageView.setBackgroundDrawable(...) was just an api style design choice. So if you look at the source of Android SDK 18 you will see:
/**
* 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);
}
So for now its absolutely irrelevant if you use one or the other - but of course this COULD change (but it's unlikely it does in the future since it would break nearly every app done before SDK 16) - basically it's fine to use setBackground() even on SDK 18+
So if you want to be on the future-proof but ugly side you could use a version fork depicted by the other answers
if(Build.VERSION.SDK_INT >= 16) {
//new code
} else {
//deprecated code
}
Just one thing, and maybe this is a personal style preference, I would not suppress Lint warnings with annotations like this:
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
I like to keep the warnings since maybe later if I want to refactor/move to higher SDK I could easily get rid of these ugly switches.
Update:
Google's v4 support library contains helper classes for sdk boiler plate code. In this instance you would use:
ViewCompat.setBackground(view,drawable);
which handles the SDK check for you.
Seems to be a bug in eclipse or your eclipse is not working perfectly. But you can try project clean and try. But code wise you can try something like this:
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
public void setImage(ImageView imageView, BitmapDrawable bd) {
if(Build.VERSION.SDK_INT > 16) {
imageView.setBackground(bd);
} else {
imageView.setBackgroundDrawable(bd);
}
}
You can call this function along with ImageView and bitmap drawable.
I want to set background drawable of a view. There are two methods for this (as far as I see): setBackground and setBackgroundDrawable.
When I use setBackground, it says it has been added in API level 16 but my project's min SDK version is 7. I assume it's not going to work on anything below 16, am I right? But when I use setBackgroundDrawable, it says it's deprecated.
What am I supposed to use?
It's deprecated but it still works so you could just use it. But if you want to be completly correct, just for the completeness of it... You'd do something like following:
int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
setBackgroundDrawable();
} else {
setBackground();
}
For this to work you need to set buildTarget api 16 and min build to 7 or something similar.
You can use setBackgroundResource() instead which is in API level 1.
seems that currently there is no difference between the 2 functions, as shown on the source code (credit to this post) :
public void setBackground(Drawable background) {
//noinspection deprecation
setBackgroundDrawable(background);
}
#Deprecated
public void setBackgroundDrawable(Drawable background) { ... }
so it's just a naming decision, similar to the one with fill-parent vs match-parent .
i know this is an old question but i have a similar situation ,and my solution was
button.setBackgroundResource( R.drawable.ic_button );
Drawable d = button.getBackground();
and then you can play with the "Drawable", applying color filters, etc
Use ViewCompat.setBackground(view, background);
you could use setBackgroundResource() instead i.e. relativeLayout.setBackgroundResource(R.drawable.back);
this works for me.
Using Android studio 1.5.1 i got the following warnings:
Call requires API level 16 (current min is 9): android.view.View#setBackground
and the complaints about deprecation
'setBackgroundDrawable(android.graphics.drawable.Drawable)' is deprecated
Using this format, i got rid of both:
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
//noinspection deprecation
layout.setBackgroundDrawable(drawable);
} else {
layout.setBackground(drawable);
}
Now you can use either of those options. And it is going to work in any case.
Your color can be a HEX code, like this:
myView.setBackgroundResource(ContextCompat.getColor(context, Color.parseColor("#FFFFFF")));
A color resource, like this:
myView.setBackgroundResource(ContextCompat.getColor(context,R.color.blue_background));
Or a custom xml resource, like so:
myView.setBackgroundResource(R.drawable.my_custom_background);
Hope it helps!
This works for me: View view is your editText, spinner...etc. And int drawable is your drawable route example (R.drawable.yourDrawable)
public void verifyDrawable (View view, int drawable){
int sdk = Build.VERSION.SDK_INT;
if(sdk < Build.VERSION_CODES.JELLY_BEAN) {
view.setBackgroundDrawable(
ContextCompat.getDrawable(getContext(),drawable));
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
view.setBackground(getResources().getDrawable(drawable));
}
}
Use setBackgroundResource(R.drawable.xml/png)
I also had this problem, but I made a workaround using a ImageView.
Try using a RelativeLayout and add a ImageView inside it (width and height: fill_parent, scaleType: center).
Also make sure the imageview is the first element inside the RelativeLayout, so it will act as background.
You can also do this:
try {
myView.getClass().getMethod(android.os.Build.VERSION.SDK_INT >= 16 ? "setBackground" : "setBackgroundDrawable", Drawable.class).invoke(myView, myBackgroundDrawable);
} catch (Exception ex) {
// do nothing
}
EDIT: Just as pointed out by #BlazejCzapp it is preferable to avoid using reflection if you can manage to solve the problem without it. I had a use case where I was unable to solve without reflection but that is not case above. For more information please take a look at http://docs.oracle.com/javase/tutorial/reflect/index.html