Как установить цвет с помощью .setBackgroundColor(); с цветом из values/colors.xml

В Android я пытаюсь установить цвет из res/values/colors.xml

Использование title.setBackgroundColor()

В настоящее время я могу установить его с помощью: title.setBackgroundColor(Color.GREEN);

Однако я хотел бы сослаться на цвет из .xml

Когда я использую:

title.setBackgroundColor(R.color.white);

ссылаясь на:

<color name="white">#FFFFFF</color>

Студия Andriod сообщает:

Should pass resolved color instead of resource id here: `getResources().getColor(R.color.white)` less... (⌘F1) 
This inspection looks at Android API calls that have been annotated with various support annotations (such as RequiresPermission or UiThread) and flags any calls that are not using the API correctly as specified by the annotations.  Examples of errors flagged by this inspection:
Passing the wrong type of resource integer (such as R.string) to an API that expects a different type (such as R.dimen).
Forgetting to invoke the overridden method (via super) in methods that require it
Calling a method that requires a permission without having declared that permission in the manifest
Passing a resource color reference to a method which expects an RGB integer value.
...and many more.  For more information, see the documentation at http://developer.android.com/tools/debugging/annotations.html

person codepurveyor    schedule 21.04.2018    source источник
comment
Возможный дубликат Как установить цвет фона представления   -  person ADM    schedule 21.04.2018
comment
попробуйте установить title.setBackgroundColor(ContextCompat.getColor(context, R.color.white));   -  person Devil10    schedule 21.04.2018


Ответы (5)


Перейдите в res->values->color.xml и напишите код, как показано ниже:

цвета.xml

<resources>
    <color name="name_color">#3F51B5</color>
</resources>

И установить:

title.setBackgroundResource(R.color.name_color);

введите здесь описание изображения

person Augusto    schedule 21.04.2018

В вашем xml-файле:

<color name="newcolor">#FF00</color>

и использовать

title.setBackgroundResource(R.color.newcolor);
person manhtuan21    schedule 21.04.2018

Вам нужно использовать ContextCompat.getColor(getContext(), R.color.green). Это даст вам цвет, который вы хотите, по идентификатору, который вы передаете. В конце:

title.setBackgroundColor(ContextCompat.getColor(getContext, R.color.green));
person Ian Rehwinkel    schedule 21.04.2018

Вы можете попробовать в Xamarin

SomeView.SetBackgroundResource(Resource.Color.justRed);
person Sheriff    schedule 18.06.2020

Просто добавьте это

title.setBackground(getResources().getColor(R.color.yourcolor));

or

title.setBackgroundResource(R.color.yourColor);
person ali farooq    schedule 21.04.2018