6

I want to put an image as background of a Layout.

First I am creating a drawable : Drawable d = Drawable.createFromPath("pathToImageFile");

In API level 8 layout.setBackground( d ) is not supported AND layout.setBackgroundDrawable( d ) is deprecated so I need to use

layout.setBackgroundResource(resourceID)

how can I get resourceID of a dynamically generated drawable.I am using this method :

Drawable d = Drawable.createFromPath("pathToImageFile");

to create a drawable.

ZZeyaNN
  • 538
  • 8
  • 13

4 Answers4

2

Hi use the following method

public void setBackgroundDrawable (Drawable background) 

by calling

imageView.setBackgroundDrawable(drawable);

Added in API level 1

EDIT: try this method

@SuppressWarnings("deprecation")
    private void setRes(ImageView iv,Drawable drawable){
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
            iv.setBackground(drawable);
        else
            iv.setBackgroundDrawable(drawable);
    }
dinesh sharma
  • 3,312
  • 1
  • 22
  • 32
  • This method is deprecated can I use it ?? In eclipse it is showing with a strike in code. – ZZeyaNN Dec 18 '13 at 09:21
  • this method is depricated in api level 16 up to API level 15 it will work grt – dinesh sharma Dec 18 '13 at 09:23
  • Thanks alot. I was also thinking of this method. But still the strike mark in eclipse is not going away. even after using `@SuppressWarnings("deprecation")` and `@SuppressLint("NewApi")` – ZZeyaNN Dec 18 '13 at 10:14
  • 1
    it will show strike make because you may have updated the android sdk above 15 level so don't worry about that. – dinesh sharma Dec 18 '13 at 10:56
0

Use setBackground(Drawable background) method. http://developer.android.com/reference/android/view/View.html#setBackground(android.graphics.drawable.Drawable)

Shashika
  • 1,151
  • 1
  • 9
  • 21
0

For API 1-15 use

view.setBackgroundDrawable(drawable);

For API 16 & above use

viw.setBackground(drawable);
CR Sardar
  • 921
  • 2
  • 17
  • 32
0

As explained in the POST by @hasanghaforian,

You can get the resource ID using the "getIdentifier" with the following code:

int resID = getResources().getIdentifier("org.anddev.android.testproject:drawable/bug", null, null);

OR

int resID = getResources().getIdentifier("bug", "drawable", "org.anddev.android.testproject");      

where,

bug.png is the file in "/res/drawable/".

Then you can use layout.setBackgroundResource(resID).

Community
  • 1
  • 1
sjain
  • 23,126
  • 28
  • 107
  • 185
  • as we are dynamically creating **drawable** we don't know it's name, which in this case is "bug". – ZZeyaNN Dec 18 '13 at 10:25