Rich
Rich

Reputation: 36836

Android: Visual version of Button.performClick

I know that I can trigger the OnClickListener.onClick of a Button manually in code by calling performClick, but that doesn't seem to make it visually appear as it's been clicked. I'm looking for a way to manually make a button appear as if it's been clicked. Do I need to manually change the background drawable and invalidate (and then change it back again on a Handler.postDelayed call), or is there a more framework-y way of doing this?

EDIT

I know how to make the button have different drawables to appear pressed when the user initiates the press. The question is this:

Is there a simple way to make a button appear pressed programmatically when not physically pressed by the user?

SOLUTION

I just subclassed Button and made the button aware of it's normal background as a StateListDrawable and the Drawable that is used as the pressed state. I expose a method that manually sets the background to the "pressed" drawable, and I use Handler.postAtTime to have it return to it's normal background so it can be used as a regular button again when I'm done.

Upvotes: 4

Views: 1488

Answers (2)

Kirill Rakhman
Kirill Rakhman

Reputation: 43841

Although this question is very old, I figured I'll still answer it. You don't need to subclass the View. First call performClick(), visual cue won't last long, but then you can set the button's pressed state via view.setPressed(true); and then reset it a couple of milliseconds later like this.

handler.postDelayed(new Runnable() {

    @Override
    public void run() {
        view.setPressed(false);
    }
}, 100);

Upvotes: 4

Anju
Anju

Reputation: 9479

Ya, you have to create 2 drawables. One for pressed state and other for normal state.

Then you will have to create an xml like:

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

Place this xml inside your drawable folder. You can also add focused state as

android:state_focused="true"

Then inside your layout which is used by your activity, give inside your button tag:

android:background="@drawable/your xml file name"

Upvotes: 0

Related Questions