1

When I click on an Android Button, it ripples nicely. I want to trigger the same effect, but programmatically.

Right now, I use performClick() and that works --- a click is registered and the button's onClick() code is called. However, there's no ripple/UI change. How can I make it so the ripple occurs when a perform a click programmatically?

Layout:

    <Button
        android:id="@+id/myButton"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:text="Button" />

Code:

findViewById(R.id.myButton).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Log.e("DEBUG", "Saw Click");
                }
            });

findViewById(R.id.myButton).performClick();
Log.e("DEBUG", "Attempted click");
Elliptica
  • 3,928
  • 3
  • 37
  • 68
  • https://stackoverflow.com/questions/27225014/how-to-trigger-ripple-effect-on-android-lollipop-in-specific-location-within-th – ADM Jun 07 '22 at 05:43
  • Thanks but that's not really the same thing. I'm not trying to trigger at a particular x,y location but rather just want to trigger the button's default ripple. I thought peformClick() should make it work the same as if a user had clicked manually, but it doesn't (at least not when it comes to ui effect) – Elliptica Jun 07 '22 at 05:50
  • If you just need the effect, perhaps for a tutorial screen, see: [How to trigger ripple effect on Android Lollipop, in specific location within the view, without triggering touches events?](https://stackoverflow.com/q/27225014/295004) – Morrison Chang Jun 07 '22 at 06:01

1 Answers1

3

The ability to create a ripple programmatically on an existing button can be done by calling:

myButton.setPressed(true);
myButton.setPressed(false);

Having the second statement after the first is what causes the ripple. If you only have the first, the button will lighten (like if a user presses on it and doesn't let go) but not return to normal.

You can then call

myButton.performClick(); 

like before.

It may be good to turn off the button sound as well, depending on if another button is triggering the call (in that case if you don't turn it off, you'll get the sound of two clicks in quick succession because performClick still makes a button clicking sound by default). Sound can be turned off using:

myButton.setSoundEffectsEnabled(false);

So the full sequence would be something like:

myButton.setSoundEffectsEnabled(false); // One time only is needed

myButton.setPressed(true);  // Whenever wanting to make a programmatic click
myButton.setPressed(false);
myButton.performClick(); 
Elliptica
  • 3,928
  • 3
  • 37
  • 68