I want to implement my own method when the user longpresses the backspace key (KEYCODE_DEL
) in softkeypad in android.
So far I have done the following, But it's not working.
public class CustomEditText extends EditText{
private Random r = new Random();
private CustomEditText e = null;
public CustomEditText(Context context, AttributeSet attrs, int defStyle){
super(context, attrs, defStyle);
}
public CustomEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomEditText(Context context) {
super(context);
}
public void setEditText()
{
e = (CustomEditText)findViewById(R.id.edit_phone_number);
}
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
return (InputConnection) new ZanyInputConnection(super.onCreateInputConnection(outAttrs),
true);
}
private class ZanyInputConnection extends InputConnectionWrapper {
public ZanyInputConnection(InputConnection target, boolean mutable) {
super(target, mutable);
}
@Override
public boolean sendKeyEvent(KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN
&& event.getKeyCode() == KeyEvent.KEYCODE_DEL) {
// This is never called . So i do not know when the user pressed
// and unpressed the backspace key.
// return false;
}
return super.sendKeyEvent(event);
}
@Override
public boolean deleteSurroundingText(int beforeLength, int afterLength)
{
//This is getting called when user press and unpress the backspace
if (beforeLength >= 1 && afterLength == 0) {
return sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL))
&& sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL));
}
return super.deleteSurroundingText(beforeLength, afterLength);
}
}
}
Here when I press the backspace on softKeypad sendKeyEvent
is not called but deleteSurroundingText
gets called.
For longpress detection I wanted to get the KeyEvent.ACTION_DOWN
event on backspace and KeyEvent.ACTION_UP event
on backspace and if the time difference between these two events is more than 1/2 seconds I will assume it's a longpress.
Since both KeyEvent.ACTION_DOWN
and KeyEvent.ACTION_UP
are coming in sendKeyEvent
method . But sendKeyEvent
is never called.
So I do not know how do I do it.
Please help if you have any other approach to do it.
editPhoneNumberText.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// You can identify which key pressed buy checking keyCode value
// with KeyEvent.KEYCODE_
if (keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN) {
// this is for backspace
Logger.log("Thhis is what i need");
}
return false;
}
});