0

Basically I created a background.xml to add the background image to preserve the aspect ratio. Then I set the background of the ImageView to @drawable/background.

How could I change the background image from the Activity?

In activity_main.xml:

<ImageView
            android:scaleType="centerCrop"
            android:layout_width="fill_parent"
            android:layout_height="200dp"
            android:id="@+id/imageView1"
            android:layout_alignTop="@+id/scrollView"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:background="@drawable/background"
            android:src="@drawable/gradient"/>

In background.xml:

<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:gravity="fill"
    android:src="@drawable/image" />

@drawable/image is the actual .jpg file

N J
  • 27,217
  • 13
  • 76
  • 96
Orane
  • 2,223
  • 1
  • 20
  • 33
  • 1
    Why you have a background.xml? Just set `android:background="@drawable/image` in ImageView can work – Ellie Zou Jun 29 '15 at 07:17
  • http://spearhend.blogspot.in/2012/04/load-android-drawable-from-xml.html see if this works. – user765 Jun 29 '15 at 07:19
  • why **android:background**?? i bet you mean **android:src**??? – pskink Jun 29 '15 at 07:22
  • @EllieZou I did it this way because using @drawable/image straight screws up the aspect ration of the image. Do you know a way to preserve the aspect ratio of the background image? – Orane Jun 29 '15 at 07:22
  • @pskink I did it this way because I want a gradient over the image. so the src is the drawable gradient – Orane Jun 29 '15 at 07:23
  • no no no, **don't** do that, in that case use `setImageDrawable()` with a `LayerDrawable` – pskink Jun 29 '15 at 07:24
  • @pskink thats a pretty good suggestion. Sounds like it would work. Let me try it out. – Orane Jun 29 '15 at 07:32
  • @Orane Did you ever try `android:scaleType`? – Ellie Zou Jun 29 '15 at 07:39
  • @pskink why is it wrong to set images on the background? – Ivo Jun 29 '15 at 07:45
  • @IvoBeckers because it doesn't keep aspect ratio well – pskink Jun 29 '15 at 07:47
  • @EllieZou `android:scaleType` only applies to the foreground image. Im trying to change the background image. @pskink had something with the `` but I still need to figure out how to change an individual image. Im going to try this solution http://stackoverflow.com/questions/8018435/android-how-to-change-a-layer-list-drawable – Orane Jun 29 '15 at 07:47

1 Answers1

0

You can just set imageview programmatically like this

ImageView image;
//initialization
image.setImageResource(int);

// where int is resource like R.drawable.something

shreyash mashru
  • 301
  • 2
  • 9