Here is my code
import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.Button;
public class MyLongPressCustomButton extends Button{
private InStock instock;
public MyLongPressCustomButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public MyLongPressCustomButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyLongPressCustomButton(Context context) {
super(context);
}
public void setSampleLongpress(InStock sl) {
instock = sl;
}
@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)) {
cancelLongpress();
}
return super.onKeyUp(keyCode, event);
}
private void cancelLongpressIfRequired(MotionEvent event) {
if ((event.getAction() == MotionEvent.ACTION_CANCEL)
|| (event.getAction() == MotionEvent.ACTION_UP)) {
cancelLongpress();
}
}
private void cancelLongpress() {
if (instock != null) {
instock.cancelLongPress();
}
}
}
I need to use for multi classes, now it only for InStock class, how to change my code for multi classes?
The cancelLongpress() method is undefined when i changed InStock to Activity.
Thanks in advance 🙂
You should use delegate pattern in this case.
Then use this delegate for your custom button
If you want to use this for many classes, just implement this interface. For example