Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Workaround for setBackgroundDrawable on android?

Tags:

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.

like image 374
Alexis Avatar asked Oct 25 '12 14:10

Alexis


1 Answers

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.

like image 98
keyboardsurfer Avatar answered Nov 09 '22 08:11

keyboardsurfer