Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawable states with colors (not drawables)

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

like image 361
Addev Avatar asked Nov 26 '11 20:11

Addev


People also ask

What is a colordrawable?

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.

What is an example of state list drawable?

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.

What is a drawable resource?

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.

What is a statelistdrawable?

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.


1 Answers

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").

like image 167
goto10 Avatar answered Oct 12 '22 02:10

goto10