user529543
user529543

Reputation:

android generate resource on the fly

I would like to generate a pressend button design and load it on the fly.

The static version it is an xml:

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

    <!-- selected state -->
    <item android:drawable="@drawable/bt_back_pressed" android:state_pressed="true" android:state_selected="false"/>
    <item android:drawable="@drawable/bt_back_pressed" android:state_pressed="false" android:state_selected="true"/>
    <item android:drawable="@drawable/bt_back_pressed" android:state_pressed="true" android:state_selected="true"/>
    <!-- unselected state (default) -->
    <item android:drawable="@drawable/bt_back_normal"/>

</selector>

which is located in the /res/drawable folder. When I want to use it just a line of the code:

android:background="@drawable/bt_back"

Now, the current project loads the design for the button from the server side, let it be the bt_back_normal.png loaded from www.somehost.com/some/resource/bt_back_normal.png.

It would be nice if I could get an API to generate the "pressed" version ( some darker) and link it at events chain to show, when needed.

Right now there is no visual effect, when the user press the button.

How can I generate that xml equivalent on the fly? -generate a pressed version and set to show when needed.

Thanks.

Upvotes: 0

Views: 431

Answers (3)

Alex Curran
Alex Curran

Reputation: 8828

I think you're looking for the StateListDrawable class. You can create these in code, add states to it (e.g. your downloaded pressed png file) and then set it to your button with button.setBackgroundDrawable(stateList).

Upvotes: 1

Cruceo
Cruceo

Reputation: 6824

This is kind of a workaround for that, but you could just override the OnClickListener for the button, and change the background of the button inside there. ie.

final Button button = (Button)findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {          
        public void onClick(View v) {
            button.setBackgroundDrawable(R.drawable.button_pressed);
        }
    });

EDIT:

I didn't realize you wanted to change the states; thought you just wanted to show it was pressed. In that case, use StateListDrawable: http://developer.android.com/reference/android/graphics/drawable/StateListDrawable.html

Upvotes: 1

Dmitry Guselnikov
Dmitry Guselnikov

Reputation: 1046

No, you can't do this on the fly. If you wanna use dynamically generated pressed drawables you should implement OnTouchListener and set needed background inside of it.

Upvotes: 1

Related Questions