Reputation: 146
I am trying to implement a "button" that temporarily changes background on clicking and long-clicking. I implemented a "drawable/selector":
<?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/key_pressed" />
<item
android:drawable="@drawable/key_unpressed" />
</selector>
I also captured the long-click event to change the background to something else:
@Override
public boolean onLongClick(View view) {
view.setBackground(getDrawable(R.drawable.key_long_pressed));
return true;
}
Doing this makes the background stick and won't revert back. If I comment out "setBackground()", the release button works.
Ideas?
I still do want to change the background on a long click.
Upvotes: 1
Views: 87
Reputation: 108
If I understand your intention correctly then you wold like to change the background once the user presses the button and change it back to normal once the user releases the button. To solve this you have two option (IMHO):
Option 1 (simple, fast):
Add a ripple effect which uses standard Android mechanisms. See answer to this question: Add ripple effect to my button with button background color?
Option 2 (more overhead, takes longer, requires coding):
Android calls onLongClick()
when the user releases the button, thus at the end of the long click.
A long click is defined as the time (configurable) between the motion events ACTION_DOWN
and ACTION_UP
, thus button pressed and button released. Thus your function gets called on ACTION_UP
and never called a second time (Android does not call the function on ACTION_DOWN
), thus the background color does not revert back.
If you like to change the background then you need to implement and set a GestureDetector
and handle the ACTION_DOWN
and ACTION_UP
in your code. You may use GestureDetector.SimpleOnGestureListener
and override only those motion events that your code needs.
In GestureDetector.SimpleOnGestureListener.onDown()
your code sets the background, on
GestureDetector.SimpleOnGestureListener.onLongPress()
revert the background color. Be aware that this background change would also appear on all other button actions as well because every button action starts with onDown
. You need to revert to normal color for other actions as well.
Upvotes: 0
Reputation: 763
Delete this code
@Override
public boolean onLongClick(View view) {
view.setBackground(getDrawable(R.drawable.key_long_pressed));
return true;
}
and put this lin to the button on XML
android:background="@drawable/key_long_pressed"
Upvotes: 1