|
package com.iwan.random; |
|
|
|
import android.content.Context; |
|
import android.util.AttributeSet; |
|
import android.view.KeyEvent; |
|
import android.view.MotionEvent; |
|
import android.widget.Button; |
|
|
|
/* |
|
* Source: http://www.rochdev.com/2011/05/update-ui-when-holding-button.html |
|
* Modification: |
|
* On cancelling long press, instead of reference to parent activity, |
|
* call the OnCancelLongpressListener listener |
|
*/ |
|
|
|
public interface OnCancelLongpressListener { |
|
void onCancelLongpress(View v); |
|
} |
|
public class CounterButton extends Button { |
|
|
|
public CounterButton(Context context, AttributeSet attrs, int defStyle) { |
|
super(context, attrs, defStyle); |
|
} |
|
|
|
public CounterButton(Context context, AttributeSet attrs) { |
|
super(context, attrs); |
|
} |
|
|
|
public CounterButton(Context context) { |
|
super(context); |
|
} |
|
|
|
OnCancelLongpressListener onCancelLongpressListener; |
|
public void setOnCancelLongpressListener(OnCancelLongpressListener listener) { |
|
onCancelLongpressListener = listener; |
|
} |
|
|
|
private void cancelLongpressIfRequired(MotionEvent event) { |
|
if ((event.getAction() == MotionEvent.ACTION_CANCEL) |
|
|| (event.getAction() == MotionEvent.ACTION_UP)) { |
|
onCancelLongpressListener.onCancelLongpress(this); |
|
} |
|
} |
|
|
|
@Override |
|
public boolean onTouchEvent(MotionEvent event) { |
|
cancelLongpressIfRequired(event); |
|
return super.onTouchEvent(event); |
|
} |
|
|
|
@Override |
|
public boolean onTrackballEvent(MotionEvent event) { |
|
cancelLongpressIfRequired(event); |
|
return super.onTrackballEvent(event); |
|
} |
|
|
|
@Override |
|
public boolean onKeyUp(int keyCode, KeyEvent event) { |
|
if ((keyCode == KeyEvent.KEYCODE_DPAD_CENTER) |
|
|| (keyCode == KeyEvent.KEYCODE_ENTER)) { |
|
onCancelLongpressListener.onCancelLongpress(this); |
|
} |
|
return super.onKeyUp(keyCode, event); |
|
} |
|
} |