indi mars
indi mars

Reputation: 133

how to use a drawable xml at runtime for a button

I two drawables xml files for a button. In layout file I set to first xml. This is my first drawable xml in drawable folder (setup.xml):--

<item
    android:state_pressed="true" >
    <shape>
        <corners android:radius="10dp" />
        <solid android:color="#406934"></solid>
    </shape>
</item>
<item
    android:state_focused="true" >
    <shape>
       <corners android:radius="10dp" />
       <solid android:color="#406934"></solid>
    </shape>
</item>

I am using it in my layout file as:-

<Button
    android:id="@+id/b_actionButton"
    android:text="@string/page_button_action_text"
    -------------
    android:background="@drawable/setup"
    style="@style/action_button" />

Now at runtime, I want to change the drawable to another xml(active_button.xml) file based on some condition.

I am using following code, but their is no change.

if (item.getTitle().equals("Stop ")) {
    StateListDrawable background = (StateListDrawable) holder.bActionButton.getBackground();
    background.selectDrawable(R.drawable.active_button);
}

Any help or pointers!!!

Upvotes: 1

Views: 612

Answers (2)

Nick Cardoso
Nick Cardoso

Reputation: 21753

Assuming @drawable/setup_alert_button and setup.xml are actually the same thing your setup.xml needs an item without and state (android:state_pressed="true" / android:state_focused="true", etc)

That default item should be the last one (the bottom one in the drawable). It will be used as default state and then state_enabled and state_pressed should contain your active drawable. Theres no need to do anything in the code.

If you really need to do it based on title just use

holder.bActionButton.setBackgroundResource(R.drawable.active_button);    

Upvotes: 0

IntelliJ Amiya
IntelliJ Amiya

Reputation: 75788

Courtesy to Sir,ρяσѕρєя K

Please use matches instead equals

    if (item.getTitle().matches("Stop"))
    {

    StateListDrawable background = (StateListDrawable) holder.bActionButton.getBackground();
    background.setBackgroundResource(R.drawable.active_button);
    }

Upvotes: 1

Related Questions