Set background programmatically by an xml file

Alaoui Ghita picture Alaoui Ghita · Feb 21, 2012 · Viewed 7.4k times · Source

I have one ImageButton in my xml layout like that :

<ImageButton android:id="@+id/tabsButton"
    android:background="@drawable/button" android:layout_height="48dp"       
    android:layout_width="48dp"></ImageButton>

as you can see, I set the background of my ImageButton here :

   android:background="@drawable/button"

where button is an xml file that I placed in the drawable folder, below is the code of button.xml :

 <?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:state_pressed="true"
    android:drawable="@drawable/duscrollover" /> <!-- pressed -->
    <item android:drawable="@android:color/transparent" /> <!-- default -->
 </selector>

until now, every thing is ok and works fine, but now I want to set the background of my ImageButton programmatically in my on create, so I did just this :

View myView  = findViewById(R.id.tabsButton);
myView.setBackgroundResource(R.drawable.button);

But, it don't recognize button in myView.setBackgroundResource(R.drawable.button) So how can get the reference to an xml file witch is placed in drawable folder ?

Thanks in advance

Answer

DunClickMeBro picture DunClickMeBro · Feb 21, 2012

Are you getting an error where it can't find the resource? If so, try cleaning the project and rerunning.