Alexis
Alexis

Reputation: 16829

Workaround for setBackgroundDrawable on 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.

Upvotes: 5

Views: 7734

Answers (3)

Sanjeev Kumar
Sanjeev Kumar

Reputation: 303

Setting bitmap to ImageView.

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

Upvotes: 0

Ben Weiss
Ben Weiss

Reputation: 17922

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.

Upvotes: 15

Partha Ranjan Nayak
Partha Ranjan Nayak

Reputation: 577

You can use

viewobj.setBackgroundResource(drawble_object);

Upvotes: 3

Related Questions