Question

I have an image button with the following xml:

    <ImageButton
      android:id="@+id/imageButton1"
      android:contentDescription="@string/button_click1"
      android:layout_width="200dp"
      android:layout_height="100dp"
      android:layout_margin="20dp"
      android:src="@drawable/button_default" />

Now I want to dynamically change the image source from loading a file. I know the right way is to use

 this.button.setImageDrawable(this.default_source);

The problem is I want to make sure two things: 1. The new image should be in the same place as before replacing. 2. If the newly loaded image is not 200dp * 100dp, I want automatically scale the image not cutting it. Any idea how to do this?

Thanks a lot!!!

Was it helpful?

Solution

Put the following xml attribute into your ImageButton xml...

android:scaleType="fitXY"

as below...

<ImageButton
      android:id="@+id/imageButton1"
      android:contentDescription="@string/button_click1"
      android:layout_width="200dp"
      android:layout_height="100dp"
      android:layout_margin="20dp"
      android:scaleType="fitXY"
      android:src="@drawable/button_default" />
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top