Search code examples
javaandroiddrawablexml-drawable

Drawable resource file - Changing Image


Long Description:

So I want the resting image to be different depending on circumstances. As soon as the user gains (in my case) currency, I want it to check to see whether he has enough to purchase. If he has enough I want the button to change colors as to visually tell the user he has enough to buy this upgrade. Every time his currency value changes I will call upon this function. Though as life is not perfect I can't combine java code in my xml and I have no clue how to call upon it.

Summary:

My question is how do I change @drawable/button through my mainActivity

Example of what I want to happen:

aFunction(){
    if(whatever){
            <item android:drawable="@drawable/buttonclick"    android:state_pressed="true"></item>
            <item android:drawable="@drawable/button"></item>
            }
            else
            <item android:drawable="@drawable/buttongray"></item>
}

Solution

  • In your xml:

    <item android:drawable="@drawable/button"></item>
    <item android:drawable="@drawable/buttonclick" android:state_pressed="true"></item>
    <item android:drawable="@drawable/buttongray" android:state_enabled="false"></item>
    

    and in your JAVA code:

    if(whatever){
        button.setEnabled(true);
    } else {
        button.setEnabled(false);
    }