How to change color of CompoundDrawable on Button?

前端 未结 4 1070
渐次进展
渐次进展 2020-12-16 05:01

I am trying to figure out how to change the color of icon which is in drawable left of button.

Below is the XML code I am using :

  
4条回答
  •  攒了一身酷
    2020-12-16 05:35

    I was searching for the problem that you have asked here, finally, I found a hack and not a solution in which I decided to have two drawables with my desired configuration and set them separately within the code when needed.

    Imagine that I want to change the drawable color to gray to show that it has been deactivated. here is the drawable for the normal condition: ic_email_black_18dp.xml

    
        
    
    
    

    you just want to change the fillColor, so here is the new XML file:ic_email_gray_18dp.xml

    
        
    
    
    

    now in your code, you can change the color of the drawable by totally substituting it with the new one:

            button.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
    
                            //Everything else that this button is supposed to do
    
                            button.setCompoundDrawablesWithIntrinsicBounds(
                                 R.drawable.ic_email_gray_18dp, //left
                                 0, //top
                                 0, //right
                                 0 //bottom
                                   );
    
                }
            });
    

    This solution sounds promising as the duplicated file takes almost no space and more than that you can do more customizations on the different states of the icon without the need to do lots of unnecessary boilerplate code (when you need to change more than a single color in the icon, etc).

提交回复
热议问题