Espen
Espen

Reputation: 3727

Using colors in a selector xml

I want to set colors for clicking instead of images. Doing so doesn't give any errors except for force-closing at runtime. Is it even possible to do this or can selector only be used for images?

Code I'm trying below:

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_focused="true" android:state_pressed="true" android:background="#00C0FF" />
    <item android:state_focused="true" android:state_pressed="false" android:background="#0060FF" />
    <item android:state_focused="false" android:state_pressed="true" android:background="#00C0FF" />
    <item android:state_focused="false" android:state_pressed="false" android:background="#FFFFFF" />

</selector>

Upvotes: 2

Views: 1832

Answers (2)

Daren Robbins
Daren Robbins

Reputation: 2025

Not per the documentation

<item>
     Defines a drawable to use during certain states, as described by its attributes. Must be a child of a <selector> element.

    android:drawable
        Drawable resource. **Required.** Reference to a drawable resource.

You can create a simple shape drawable to hold the color

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#33FF33"/>
</shape>

Upvotes: 3

Squonk
Squonk

Reputation: 48871

Is it even possible to do this or can selector only be used for images?

No, this doesn't make any sense (to me at least). Without a 'drawable', how will it know exactly 'what' to set to state_focused and state_pressed?

Why not just create some single colour drawables (bitmaps for example) and provide those as the drawables for each item?

Upvotes: 1

Related Questions