10

I'm using a Button

<Button
        android:id="@+id/zoom"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/trans"
        android:drawableLeft="@drawable/left_img"
        android:fontFamily="arial"
        android:text="My Name is "
        android:textSize="50sp" />

and changing its text color with :

zoom.setTextColor(Color.parseColor("voilet"));

but not able to understand how to change its image??

Cœur
  • 37,241
  • 25
  • 195
  • 267
dashh
  • 261
  • 3
  • 6
  • 17
  • take a look at http://developer.android.com/guide/topics/ui/controls/button.html#CustomBackground to style your button – Eluvatar Aug 16 '13 at 16:29
  • set like this button.setBackground(R.drawable.ic_launcher); inside the onclick listener. – Aravin Aug 16 '13 at 16:32
  • Possible duplicate of [How to programatically set drawableLeft on Android button?](http://stackoverflow.com/questions/4502605/how-to-programatically-set-drawableleft-on-android-button) – Varun Sep 15 '16 at 22:27

5 Answers5

41

Try this:

int imgResource = R.drawable.left_img;
button.setCompoundDrawablesWithIntrinsicBounds(imgResource, 0, 0, 0);

Reference

Tulio
  • 955
  • 6
  • 12
12

The safest way to set the left drawable without changing the values of the other drawables (top, right, and bottom):

Drawable[] drawables = textViewExample.getCompoundDrawables();
textViewExample.setCompoundDrawablesWithIntrinsicBounds(leftDrawable, drawables[1], drawables[2], drawables[3]);
Jordan
  • 551
  • 3
  • 11
2

To do this, you can use the

setCompoundDrawables(...);

method. Be aware that comes with TextView, not Button.

This is how to use it:

Drawable img = getContext().getResources().getDrawable( R.drawable.yourimage);
img.setBounds( 0, 0, 60, 60 );  // set the image size
txtVw.setCompoundDrawables( img, null, null, null );

Taken from: How to programmatically set drawableLeft on Android button?

Community
  • 1
  • 1
Philipp Jahoda
  • 50,880
  • 24
  • 180
  • 187
0

I recomend that instead of using a button you use an Imageview and add an onclick listener to it. That way you can just do Imageview.setbitmap(bitmap) and create a bitmap from one of your drawables

Cam Connor
  • 1,231
  • 2
  • 25
  • 40
0

just follow this code i hope it's really helpful for you..

boolean isIconChange;
button.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {
        isIconChange = !isIconChange;
        if(isIconChange){
           button.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like, 0, 0, 0);
           button.setTextColor(Color.BLACK);
        } else {
           button.setCompoundDrawablesWithIntrinsicBounds(R.drawable.dislike, 0, 0, 0);
           button.setTextColor(Color.RED);
        }
    }
});
Ravi Makvana
  • 2,872
  • 2
  • 24
  • 38