Прошло много времени с тех пор, как вы спросили, но у меня была та же проблема. Как уже упоминалось Эстелем, проблема с ключевыми слушателями заключается в том, что они работают только с аппаратными клавиатурами. Чтобы сделать это с помощью IME (программная клавиатура) , решение немного сложнее.
Единственный метод, который мы на самом деле хотим переопределить, это sendKeyEvent
в классе EditText
InputConnection
. Этот метод вызывается, когда ключевые события происходят в IME. Но чтобы переопределить это, нам нужно реализовать собственный EditText
, который переопределяет метод onCreateInputConnection
, оборачивая объект InputConnection
по умолчанию в прокси-класс! : |
Звучит сложно, но вот самый простой пример, который я мог придумать:
public class ZanyEditText extends EditText {
private Random r = new Random();
public ZanyEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public ZanyEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ZanyEditText(Context context) {
super(context);
}
public void setRandomBackgroundColor() {
setBackgroundColor(Color.rgb(r.nextInt(256), r.nextInt(256), r
.nextInt(256)));
}
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
return 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) {
ZanyEditText.this.setRandomBackgroundColor();
// Un-comment if you wish to cancel the backspace:
// return false;
}
return super.sendKeyEvent(event);
}
}
}
Строка с вызовом setRandomBackgroundColor
- это место, где происходит мое специальное действие возврата. В этом случае меняется цвет фона EditText
.
Если вы накачиваете это из XML, не забудьте использовать полное имя пакета в качестве тега:
<cc.buttfu.test.ZanyEditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/somefield"
></cc.buttfu.test.ZanyEditText>