Android: setting layout background using image path

I want to put the image as the background layout .

First I create drawable: Drawable d = Drawable.createFromPath("pathToImageFile");

In API Level layout.setBackground( d ) not supported AND layout.setBackgroundDrawable( d ) deprecated , so I need to use

layout.setBackgroundResource(resourceID)

how can I get the resourceID of a dynamically generated drawable.I use this method:

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

to create portable.

+6
source share
4 answers

Hi, use the following method

 public void setBackgroundDrawable (Drawable background) 

causing

 imageView.setBackgroundDrawable(drawable); 

Added to 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); } 
+2
source

For API 1-15 use

 view.setBackgroundDrawable(drawable); 

For API 16 and above, use

 viw.setBackground(drawable); 
0
source

As explained in POST by @hasanghaforian,

You can get the resource identifier using 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) .

0
source

All Articles