4

Change the ImageButton src

Here is the xml for the tag:

    <ImageButton
        android:layout_width="0dp"
        android:id="@+id/infobutton"
        android:layout_weight="1"
        android:src="@drawable/edit"
        android:scaleType="fitCenter"
        android:layout_height="60dp" />

This is what im doing to the button when it get pressed

        button.setBackgroundResource(R.drawable.save);

The ImageButton before pressed

enter image description here

Image after press:

enter image description here

I want the button to only have the save Picture and it beeing fitCenter and why doesnt the other src get replaced With the New src?

Kim Vu
  • 584
  • 9
  • 25
  • in xml you are setting source(Foreground) but on button press you are setting background. thats why – Akshay Bhat 'AB' Oct 26 '16 at 10:58
  • instead of `android:src="@drawable/edit"` try using `android:background="@drawable/edit"` in your `xml` – Logic Oct 26 '16 at 10:59
  • "setImageResource" instead of "setBackgroundResource" – YLS Oct 26 '16 at 10:59
  • Possible duplicate of [android Imagebutton change Image OnClick](http://stackoverflow.com/questions/12249495/android-imagebutton-change-image-onclick) – YLS Oct 26 '16 at 11:07

2 Answers2

8

Because android:src and android:background is the different attributes. You should use

button.setImageResource(R.drawable.save);
Sergey Nikitin
  • 807
  • 8
  • 23
1

your code is trying to change the background of the button. not its image. Those are two different things

((ImageButton) view).setImageResource(R.drawable.icon2);
Lucifer
  • 1,594
  • 2
  • 18
  • 32