Programmatically change drawableLeft of Button

2019-03-20 03:47发布

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??

5条回答
戒情不戒烟
2楼-- · 2019-03-20 03:59

Try this:

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

Reference

查看更多
甜甜的少女心
3楼-- · 2019-03-20 04:00

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);
        }
    }
});
查看更多
ゆ 、 Hurt°
4楼-- · 2019-03-20 04:05

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

查看更多
男人必须洒脱
5楼-- · 2019-03-20 04:14

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]);
查看更多
爱情/是我丢掉的垃圾
6楼-- · 2019-03-20 04:15

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?

查看更多
登录 后发表回答