android set button background programmatically

前端 未结 8 725
天涯浪人
天涯浪人 2020-11-30 02:57

I would like to know how to set the button color programatically? I have coded the following but fails:

Button11.setBackgroundColor(R.color.red);
         


        
8条回答
  •  离开以前
    2020-11-30 03:30

    I have found that Android Studio gives me a warning that getColor() is deprecated when trying to do this:

    Button11.setBackgroundColor(getResources().getColor(R.color.red))
    

    So I found doing the method below to be the simple, up-to-date solution:

    Button11.setBackgroundColor(ContextCompat.getColor(context, R.color.red))
    

    You want to avoid hard-coding in the color argument, as it is considered bad code style.

    Edit: After using setBackgroundColor() with my own button, I saw that the internal button padding expanded. I couldn't find any way of changing it back to having both height and width set to "wrap_content". Maybe its a bug.

    Source: https://stackoverflow.com/a/32202256/6030520

提交回复
热议问题