3

(java/xml for android 2.1 or higher)

I'm creating button using style:

<style name="MainButton">
    <item name="android:textColor">#000000</item>
    <item name="android:text">test</item>
    <item name="android:drawableRight">@drawable/ic_launcher</item>
    <item name="android:drawablePadding">10dip</item>
    <item name="android:paddingLeft">10dip</item>
</style>

I know that I can change text (from my java code), for example like this:

Button but = (Button)findViewById(R.id.button2);
    but.setText(Html.fromHtml("<b>" + "title" + "</b>" +  "<br />" + 
            "<small>" + "description" + "</small>" + "<br />" + 
            "<small>" + "DateAdded" + "</small>"));

And it looks very well, but How can I change my drawable object inside of that button from my java code?

I dont want to use "button.setBackgroundResource();" method.

Any ideas? :>

  • See this: http://stackoverflow.com/questions/4919703/how-to-set-property-androiddrawabletop-of-a-button-at-runtime – Shade Mar 08 '13 at 12:02
  • thanks m8 for quick answer but I belive that I put my ask in wrong words. I want to comlitely change my drawable object (edit) – user2148208 Mar 08 '13 at 12:10

4 Answers4

0

make another xml with the same attributes but change '@drawable/' resource. and on the onclick method set the background resources of the button to this new xml

0

I think you want a custom selector

Create a custom selector and set it as a drawable resouce in xml.

Example:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" 
        android:drawable="@drawable/cell_top_selected" />
    <item android:drawable="@drawable/cell_top" />
</selector>

and

use this statements

yourbutton.setSelected(true)  // for selection image
yourbutton.setSelected(false) // for alternate image

if you don't want this to

   I dont want to use "button.setBackgroundResource();" method.

If you don't want to use setBackGround Resouce then

Take a TextView instead, Super class of Button is TextView, by default TextView don't have any background drawable resource.

Pragnani
  • 20,075
  • 6
  • 49
  • 74
0
    button.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom);

You can either use resource ids or drawables

Badr Ghatasheh
  • 968
  • 2
  • 7
  • 19
0

If I have understood the question correctly and I am assuming you want to completely change the button and draw your own then you will have to create your own Button. This can be done by creating a new class and then extending it with Button and then override the onDraw() method of the View class. Here in this method you can draw what ever you like i.e. background, text, borders..etc.

For example

class NewButton extends Button{
    protected void onDraw (Canvas canvas){
    //Draw here
    }
}

I hope this helps.

user_CC
  • 4,686
  • 3
  • 20
  • 15