2

I want to change my button background at RUNTIME

I know how to add a custom background to a button, but

  • How can I change it to borderlessButtonStyle? in the xml was easy, I used:

    style="?android:attr/borderlessButtonStyle")
    
  • How can I switch back to the default background? The following is not what I want (apperantly it is not the default used in Jelly Bean)

    changeableButton.setBackgroundResource(android.R.drawable.btn_default);
    

    Thanks for your help

Tünde
  • 885
  • 4
  • 11
  • 24

3 Answers3

5

I actually found a solution

You can save the initial background of your button in a Drawable object

Drawable d = button.getBackground();

Now you can modify your button's background as you wish

button.setBackgroundResource(R.drawable.custom_button);

Than you can modify it back

button.setBackgroundDrawable(d);
Tünde
  • 885
  • 4
  • 11
  • 24
0

does this work? changeableButton.setBackground(null);

Dediqated
  • 901
  • 15
  • 35
  • Yeah I thought so already, I couldn't test it first. what about `bt.setBackgroundResource(0);`? still no background? – Dediqated Apr 02 '13 at 14:46
  • I googled a bit and I'm afraid this is not possible, what you actually want to do is remove the previous style applied in the XML. Styles can't be applied programmatically.. see : http://stackoverflow.com/a/2016344/1323666 `Generally you can't change styles programmatically; you can set the look of a screen, or part of a layout, or individual button in your XML layout using themes or styles. Themes can, however, be applied programmatically.` – Dediqated Apr 02 '13 at 15:10
  • Ok, and what about the default background? – Tünde Apr 02 '13 at 19:21
  • I just find the solution for the default background: Drawable d = b.getBackground(); than you can do this b.setBackgroundDrawable(d); – Tünde Apr 03 '13 at 07:07
  • great! what is it? I'm sorry I couldn't help you – Dediqated Apr 03 '13 at 07:09
  • Drawable d = b.getBackground(); b.setBackgroundDrawable(d); – Tünde Apr 03 '13 at 07:10
  • You should add this as an answer and mark it as answer. Then others looking for a solution to the same problem can be helped. I'm glad you found it yourself ;) – Dediqated Apr 03 '13 at 07:13
0

There is a simple answer to this problem:

button.setBackgroundResource(R.drawable.backround);

you can also change back to your default backround by using an if statement and repeating the above statement by just changing the "backround" resource to your default resource. Btw thanks for A2A.