android - Stellen Sie die Hintergrundfarbe programmgesteuert ein

original title: "android - Set Background color programmatically"


This question already has an answer here:

Diese Frage hat hier bereits eine Antwort: So stellen Sie die Hintergrundfarbe einer Ansicht ein 16 Antworten ...

Dies ist die Zusammenfassung nach der Übersetzung. Wenn Sie die vollständige Übersetzung anzeigen möchten, klicken Sie auf das Symbol "Übersetzen"

Alle Antworten
  • Translate

    I didn't understand your question ... what do you mean by "when i set every one of my colour"? try this (edit: "#fffff" in original answer changed to "#ffffff"


  • Translate

    you need to use getResources() method, try to use following code

    View someView = findViewById(;
    View root = someView.getRootView();


    getResources.getColor() is deprecated so, use like below

     root.setBackgroundColor(ContextCompat.getColor(this, R.color.white)); 

  • Translate

    You can use




  • Translate

    The previous answers are now deprecated, you need to use ContextCompat.getColor to retrieve the color properly:

    root.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.white));

  • Translate

    If you just want to use some of the predefined Android colors, you can use Color.COLOR (where COLOR is BLACK, WHITE, RED, etc.):


    Otherwise you can do as others have suggested with

    myView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.myCustomGreen));

    I don't recommend using a hex color directly. You should keep all of your custom colors in colors.xml.

  • Translate

    This must work:

    you must use getResources().getColor(R.color.WHITE) to get the color resource, which you must add in the colors.xml resource file

    View someView = findViewById(;

  • Translate

    If you save color code in the colors.xml which is under the values folder,then you should call the following:


    name means you declare in the <color/> tag.

  • Translate

    In my case it wasn't changing the color because I was setting the color in my xml resource.

    After delete the line that set the color it worked perfectly programmatically

    This is an example I did in a RecyclerView

    final Drawable drawable = ContextCompat.getDrawable(mContext, R.drawable.ic_icon).mutate();
    } else {