Tags

, , , , , , , , ,

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));
Advertisement