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");
CodePudding user response:
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();