4

I cannot seem to change the background image of my image button. Heres the code i'm currently trying to use:

ImageButton imgButton = (ImageButton) findViewById(R.id.showSportsButton);
imgButton.setBackgroundResource(R.drawable.tab2_selected);

However this seem to be placing the new image on top of the old image leaving me with 2 images overlapping each other.

Does anyone know why this is??

Welton122
  • 1,101
  • 2
  • 13
  • 28
  • I guess you'll have to use `.setImageResource` inherited from [`ImageView`](http://developer.android.com/reference/android/widget/ImageView.html#setImageResource%28int%29) – zapl Sep 04 '13 at 11:01
  • `please add imgButton.setImageResource(null); imgButton.setImageResource(R.drawable. tab2_selected);` – dipali Sep 04 '13 at 11:13
  • What's the old image - the default one, meaning the grey (for example, depending of the Theme) imagE? – g00dy Sep 04 '13 at 11:14

4 Answers4

10

For solving this question you should implement

imgButton.setImageResource(R.drawable. tab2_selected);
likeitlikeit
  • 5,563
  • 5
  • 42
  • 56
Oleg Gordiichuk
  • 15,240
  • 7
  • 60
  • 100
1

Use this method:

imgButon.setBackground(getActivity().getDrawable(R.drawable.your_icon));
ryan_le
  • 69
  • 1
  • 8
0

in xml file, <Button> write: android:backgroud="@drawable/your_file"

Dmitry
  • 1,499
  • 3
  • 12
  • 10
0

Make sure you are on same activity. If you are changing background of different activity first create the constructor then use object to change button.

Activity obj= new activity();
obj.imgButton.setBackgroundResource(R.drawable.tab2_selected);

and also check that oncreate() method has void return type if you are using only findviewbyid.

Maximilian Ast
  • 3,369
  • 12
  • 36
  • 47
Akash Arora
  • 71
  • 1
  • 14