I want to give a view a background color with the following behavior: The background should be green while the view is pressed and black otherwise.
This selector works
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/green" android:state_pressed="true"/>
<item android:drawable="@drawable/black"/>
</selector>
But for doing that I need to create a nine patch 3x3 file with the desired color. How can I reach the same behavior but giving the color code rather a drawable?
Thanks
A specialized Drawable that fills the Canvas with a specified color. Note that a ColorDrawable ignores the ColorFilter. It can be defined in an XML file with the <color> element. The color to use. Creates a new black ColorDrawable. Creates a new ColorDrawable with the specified color.
For example, a Button widget can exist in one of several different states (pressed, focused, or neither) and, using a state list drawable, you can provide a different background image for each state.
A drawable resource is a general concept for a graphic that can be drawn to the screen. Drawables are used to define shapes, colors, borders, gradients, etc. which can then be applied to views within an Activity. This is typically used for customizing the view graphics that are displayed within a particular view or context.
A StateListDrawable is a drawable object defined in XML that uses several different images to represent the same graphic, depending on the state of the object.
Just use the color. From the docs:
A color resource can also be used as a drawable in XML. For example, when creating a state list drawable, you can reference a color resource for the android:drawable attribute (android:drawable="@color/green").
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With