Android. Change the background color of a FrameLayout from code

22,378

Solution 1

You should not use frameLayoutBalance.setBackgroundColor(R.color.green);

setBackgroundColor required a Color (i.e. its value as describe by Chirag Raval) not a color resources.

use this frameLayoutBalance.setBackgroundColor(getResources().getColor(R.color.green));

Solution 2

Use this code frameLayoutBalance.setBackgroundColor(Color.parseColor("#00aacc"));

Share:
22,378
Allan Spreys
Author by

Allan Spreys

Updated on December 19, 2020

Comments

  • Allan Spreys
    Allan Spreys over 3 years

    I'm trying to change the background color of a FramyLayout. The color is changing, but to the wrong one.

    However it is working fine if I do it through the XML.

    Here is my res/values/colors.xml code

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <color name="grey">#888888</color>
        <color name="white">#FFFFFF</color>
        <color name="red">#ffff3448</color>
        <color name="green">#ff408c3a</color>
    </resources>
    

    Here is how it looks like if I make changes in the XML Colors changed correctly

    And that's what is happening if I try to do it with the code

     FrameLayout frameLayoutBalance = (FrameLayout)view.findViewById(R.id.frameLayoutBalance);
     frameLayoutBalance.setBackgroundColor(R.color.green);
    

    Colors changed incorrectly

  • Allan Spreys
    Allan Spreys over 11 years
    Hi there! Thanks a lot for a fast response. Even though your code is working and can be used as a workaround, I'm afraid it can't be used as a solution. It is always a best practice to do not hardcore any values as if they change I will need to go through all code and change it manually everywhere.
  • User
    User over 11 years
    frameLayoutBalance.setBackgroundColor(getResources().getColo‌​r(R.color.red));