android, attributes, color, color drawable, custom-ui, drawable, hidden, mozilla, resources, themes
Sometimes apps would need creating
ColorDrawable in Java instead of using an XML. Usually, these colors are specified in
colors.xml. And the corresponding code to create such a drawable would look like,
<!-- ... in res/values/colors.xml ... --> <resources> <color name="background_color">#FF00FF00</color> </resources>
// ... in some java file ... something.setBackground(new ColorDrawable(getResources().getColor(R.color.background_color)));
The other way round is to create a
ShapeDrawable with the required color.
<!-- ... in res/drawable/background_color.xml ... --> <shape android:shape="rectangle"> <solid android:color="#FF00FF00"> </shape>
Actually, Android has a better and shorter way of creating such drawables! Instead of specifying a color and using it, we can directly create a <drawable>.
<!-- ... in res/values/colors.xml --> <resources> <!-- note: this uses "drawable" instead of "color" --> <drawable name="background_color">#FF00FF00</drawable> </resources>
And this can be used in Java as,
// ... in some java file ... // note: it's referred as R.drawable and not R.color. something.setBackground(getResources().getDrawable(R.drawable.background_color));
Cyril Mottier (@cyrilmottier) said:
The actual XML tag to use to create a ColorDrawable is . But it has some issues pre-HC because it doesn’t respect its bounds (see my “Mastering Android Drawables” talk – https://speakerdeck.com/cyrilmottier/mastering-android-drawables).
The fact your is recognized as a ColorDrawable is because Android treats colors pretty differently from other Drawables. Indeed, whenever you try to Resources#getDrawable(int), the system will first check if the value you are trying to load is a color. In that case it will automatically create a ColorDrawable for you.
As a consequence I’m pretty sure the using and a getDrawable(R.color.background_color) would perfectly work. (Not tested though).
Sriram Ramani said:
Yup. Resources#loadDrawable() will try to find if its a color, and will return a ColorDrawable(value.data). (value.data is the color value here).
Also, Resources#getDrawable(R.color.background_color) will fail as its not a drawable resource, but a color resource. This is exactly where my code snippet will help.
And oh, I can see my code in your slide deck. The “@color/highlight” part 😀