Workaround for setBackgroundDrawable on android? - android

The setBackgroundDrawable() method of the View class in is now deprecated in android SDK API level 16.
The new method is setBackground() but of course it's only available in API 16.
How can I workaround it if I want my application to be compatible with previous API levels ? (at least API 14)
The goal is to eliminate any warnings and an #SupressWarnings is not a solution for me.

The usual way is this one:
if (android.os.Build.VERSION.SDK_INT >= 16)
setBackground(...);
else
setBackgroundDrawable(...);
On the other hand you could use reflections:
try {
Method setBackground = View.class.getMethod("setBackground", Drawable.class);
setBackground.invoke(myView, myDrawable);
} catch (NoSuchMethodException e) {
setBackgroundDrawable(myDrawable);
}
IMO a warning is better than having to catch an exception and an unnecessary reflection.

You can use
viewobj.setBackgroundResource(drawble_object);

Setting bitmap to ImageView.
ImageView imageView = (ImageView) findViewById(R.id.imageSlice4);
imageSlice4.setBackground(new BitmapDrawable(getResources(), slicedImagesArrayList.get(3)));

Related

Android getDrawable() Deprecated / How To use Android getDrawable()

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.

Getting resource ID from bitmap/drawable in android

I have a bitmap drawable image to be displayed in ImageView, below is my code:
BitmapDrawable bitmapGrass = (BitmapDrawable)
getResources().getDrawable(R.drawable.grass);
bitmapGrass.setTileModeX(TileMode.REPEAT);
I want to set that bitmap as background for ImageView, like this:
ImageView bgGrass = (ImageView) findViewById(R.id.image_grass);
bgGrass.setBackground(bitmapGrass);
Now the problem is, the method setBackground() is added in API level 16, but I want my app to support API level 4. I know I can use this code:
bgGrass.setBackgroundDrawable(bitmapGrass);
But the method setBackgroundDrawable() is deprecated. The other way to set the background is using the method setBackgroundResource(int), but the required parameter is integer (not drawable).
Is there any way to implement that bitmap without using deprecated method, perhaps converting the bitmap drawable into resource?
Thanks!
Actually it's fine to call setBackgroundDrawable though it's deprecated in newer platforms. you can check the sdk level at runtime and call the specific method:
if(Build.VERSION.SDK_INT >= 16) {
//call setBackground()
} else {
//call settBackgroundDrawable()
}

Call requests min level of 16

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")

setBackground vs setBackgroundDrawable (Android)

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

How to turn off CalendarView in a DatePicker?

On my settings screen I have a date picker widget. In the designer in Eclipse, it shows as I want (3 spinners for D-M-Y) but when I test on my device, I get a rather odd view with a side spinner on the left and a calendar on the right. Never seen this before(!) but doing some research I think I'm seeing the "CalendarView".
I found that I should be able to set a "calendarViewShown" property to false- but my XML throws an error with this. I found another question on here that suggested the API level was to blame (my minSDKLevel is 7, but I'm targetting 11 so I can get the action bar button rather than the oldskool menu).
So I thought I'd try setting it in code:
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= 11)
minDateSelector.setCalendarViewShown = false;
But again, this fails- setCalendarViewShown isn't found. But the docs here say it should exist.
Any ideas?!
If you are targeting a later version of the API, you can use the following XML (no need to write Java code) in your <DatePicker>:
android:calendarViewShown="false"
The method in DatePicker
public void setCalendarViewShown (boolean shown)
exists starting with API 11. If you minSdkLevel = 7 the compiler does not recognize this as a valid method - the method does not exist on android 2.3 or 2.2. The best way is to solve this is using reflection. Something like this should work properly:
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= 11) {
try {
Method m = minDateSelector.getClass().getMethod("setCalendarViewShown", boolean.class);
m.invoke(minDateSelector, false);
}
catch (Exception e) {} // eat exception in our case
}
I made it work with the following XML configuration:
android:datePickerMode="spinner"
android:calendarViewShown="false"
Only the following configuration didn't work for me:
android:calendarViewShown="false"
In those cases I use
import android.os.Build;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void someThing() {
[...]
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
minDateSelector.setCalendarViewShown(false);
}
}
I think the readability is better than using reflection and the style is better than catch and ignore exceptions. Of course the reflection thing is also working.
I had the same problem as you, I couldn't make the change appear via XML.
You are on the right track, try changing your last line to:
minDateSelector.setCalendarViewShown(false);

Categories

Resources