ab11
ab11

Reputation: 20090

Android: how to draw an ImageButton using the pressed state drawable for the focused state

I am trying to achieve an effect where, once pressed, an ImageButton draws with the "pressed" orange background until it loses focus (something else is touched).

StateListDrawable seems intended for this situation, because it would allow me to define how the background should be drawn for the focused state. And it would be great if I could simply define that the background should be drawn with the pressed drawable, for the focused state. However, I see no way to reference the default "pressed" drawable.

Any advice on how I can achieve this effect?

Upvotes: 1

Views: 3666

Answers (3)

Eric Woodruff
Eric Woodruff

Reputation: 6410

This is what worked for me in the Holo Dark theme of my app, but it doesn't have the rounded edges that I would like.

res/drawable/image_button_background.xml:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/holo_blue_dark" android:state_pressed="true"/>
</selector>

Use as:

android:background="@drawable/image_button_background"

Upvotes: 0

FoamyGuy
FoamyGuy

Reputation: 46856

Look inside the drawables folder inside the android SDK. You can find all of the nine patch images it uses by default. The ones you want are likely called btn_pressed, btn_focused etc. Or something similar. You can technically refer to them by id in your project but I believe it is suggested that you copy them into your project, because the IDs are not garunteed to stay the same.

Upvotes: 1

Franco
Franco

Reputation: 7475

if i understand your question maybe can help you

i do the same task defining a xml background selector, that contains drawables for each state, this file is more extensive because you can define drawables, shapes, etc... The most important feature is that you can set any drawable or shape you want...

here i defined my background selector... and i call it selector.xml and saved into drawable folder.

<?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_selected="true" android:drawable="@drawable/shape_7"/>
        <item android:state_pressed="true" android:drawable="@drawable/shape_7" />
        <item android:state_pressed="false" android:drawable="@drawable/shape_6" />
    </selector>

later when i build the ImageButton i attach the selector mentioned above... (you can do programatically or in your xml layout)

ImageButton imageButton = new ImageButton(this);
imageButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.selector));

or the xml way

<ImageView
    android:background="@drawable/selector"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="4px"
    android:src="@drawable/switch_icon"/>

cheers

Upvotes: 5

Related Questions