android set button background programmatically

前端 未结 8 727
天涯浪人
天涯浪人 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:46

    Old thread, but learned something new, hope this might help someone.

    If you want to change the background color but retain other styles, then below might help.

    button.getBackground().setColorFilter(ContextCompat.getColor(this, R.color.colorAccent), PorterDuff.Mode.MULTIPLY);
    
    0 讨论(0)
  • 2020-11-30 03:48

    R.color.red is an ID (which is also an int), but is not a color.

    Use one of the following instead:

    // If you're in an activity:
    Button11.setBackgroundColor(getResources().getColor(R.color.red));
    // OR, if you're not: 
    Button11.setBackgroundColor(Button11.getContext().getResources().getColor(R.color.red));
    

    Or, alternatively:

    Button11.setBackgroundColor(Color.RED); // From android.graphics.Color
    

    Or, for more pro skills:

    Button11.setBackgroundColor(0xFFFF0000); // 0xAARRGGBB
    
    0 讨论(0)
提交回复
热议问题