15

I have downloaded an image at runtime. Now I want to set it as a background for RelativeLayout. Does it possible?

Onik
  • 19,396
  • 14
  • 68
  • 91
Vivek
  • 4,170
  • 6
  • 36
  • 50

4 Answers4

23

Check out the setBackgroundDrawable, or maybe createFromPath in the Drawable class.

   RelativeLayout rLayout = (RelativeLayout) findViewById (R.id.rLayout);
   Resources res = getResources(); //resource handle
   Drawable drawable = res.getDrawable(R.drawable.newImage); //new Image that was added to the res folder

    rLayout.setBackground(drawable);
SteD
  • 13,909
  • 12
  • 65
  • 76
  • 1
    Yeah, you could use the createFromPath to create a Drawable object from the path where your newly downloaded image will resides in – SteD Feb 06 '11 at 18:58
5

Instead use:

View lay = (View) findViewById(R.id.rLayout);
lay.setBackgroundResource(R.drawable.newImage);

This works because R.drawable.newImage refers to an integer. So you could do:

int pic = R.drawable.newImage;
lay.setBackgroundResource(pic);
ByteHamster
  • 4,884
  • 9
  • 38
  • 53
Melvin Miller
  • 51
  • 1
  • 1
2

Try this for Xamarin.Android (Cross Platform) -

RelativeLayout relativeLayout = new RelativeLayout (this);

OR

RelativeLayout relativeLayout = (RelativeLayout)FindViewById (Resource.Id.relativeLayout);

AND

relativeLayout.SetBackgroundDrawable (Resources.GetDrawable (Resource.Drawable.imageName));
Confuse
  • 5,646
  • 7
  • 36
  • 58
Nitin V. Patil
  • 185
  • 2
  • 2
0

In the onCreate function:

RelativeLayout baseLayout = (RelativeLayout) this.findViewById(R.id.the_layout_id);

Drawable drawable = loadImageFromAsset();

if(drawable != null){
    baseLayout.setBackground(drawable);
    Log.d("TheActivity", "Setting the background");
}

The image loading method:

public Drawable loadImageFromAsset() {

    Drawable drawable;

    // load image
    try {

        // get input stream
        InputStream ims = getAssets().open("images/test.9.png");

        //Note: Images can be in hierarical 

        // load image as Drawable
        drawable = Drawable.createFromStream(ims, null);

    }
    catch(IOException ex) {
        Log.d("LoadingImage", "Error reading the image");
        return null;
    }

    return drawable;
}

The open method:

> public final InputStream open (String fileName, int accessMode)
> 
> Added in API level 1 Open an asset using an explicit access mode,
> returning an InputStream to read its contents. This provides access to
> files that have been bundled with an application as assets -- that is,
> files placed in to the "assets" directory.
> 
> fileName --- The name of the asset to open. This name can be hierarchical.
> 
> accessMode --- Desired access mode for retrieving the data.
> 
> Throws IOException
The Demz
  • 7,066
  • 5
  • 39
  • 43