Android – Fixed: “Android: Detecting focus/pressed color”

android

I'm trying to detect the focus/pressed color for button and other elements.
This is needed because I'm developing new components and it's important that those look as part of platform.
Those colors are ORANGE on android sdk and GREEN on HTC SenseUI.
If I could detect that color my component will look as part of platform on both version.

Does anyone knows how to do this?


It's possible to create "selector" which uses custom image for default state and platform default for focus/selection.

To do this follow the steps:
1) create xml file with selector in "res/drawable" (e.g. "red_button.xml"):

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true"
        android:drawable="@android:drawable/btn_default" >
    </item>

    <item android:state_focused="true"
        android:drawable="@android:drawable/btn_default" >
    </item>

    <item 
        android:drawable="@drawable/btn_default_red" >
    </item>
</selector>

2) from folder "…/android-sdk-mac/platforms/android-1.5/data/res/drawable/" take picture "btn_default_pressed.9.png" and change color as you like (I needed to change it to red and for this GIMP is enough).

3) place altered picture in "res/drawable" (e.g. with name "btn_default_red.9.png")

4) define button:

<Button
    android:id="@+id/info_button"
    android:layout_width="wrap_content" 
    android:layout_height="37dip"
    android:layout_marginTop="1dip"
    android:background="@drawable/red_button"
    android:text="[Info]" />

That's all.

This is result:
alt text http://img200.imageshack.us/img200/1349/custombutton.png

Best Answer

I had this problem too. As already stated, the problem is that the backgrounds aren't simple colors, they're Drawables that could take on all kinds of appearances. However, I found a work-around that may help. If your custom component looks something like an existing one, e.g. a Button or ListView entry, you can just steal their background/selector and set that as the background for your custom component. E.g., in your custom component constructor:

  setBackgroundDrawable(new Button(context).getBackground());

or for a background more suitable for list-like components:

  setBackgroundDrawable(new ListView(context).getSelector());

You may want to optimise that code somewhat, but you get the idea.

Related Topic