Android: how to record a long event on soft input / keyboard?

Short version of the question: how can I capture a long press event on a soft input / keyboard in Android?

Long version: In the Android application, we have a multi-line EditText, and we want to have this behavior: 1. By default, it shows the DONE button, clicking on it, soft input / keyboard will be closed. 2. If the user presses the DONE button for a long time, his behavior will be changed to the ENTER button, and there will be a new line in EditText.

For requirement # 1, I used the solution here: https://stackoverflow.com/a/212618/

For requirement # 2, the blocking question I have is how to record a long press event. I set onEditorActionListener, but the captured event is null: http://developer.android.com/reference/android/widget/TextView.OnEditorActionListener.html I was looking for a document, long press method for a hard keyboard: http://developer.android. com / reference / android / view / View.html # onKeyLongPress (int , android.view.KeyEvent), I cannot find one for soft input / keyboard.

Thanks for looking at this question.

+6
source share
1 answer

I could not find this answer myself, so I manually coded the solution. I used a timer in the onPress() and onRelease() events of the KeyboardView.OnKeyboardActionListener . Here is the important code. Many TRY / CATCHes have been omitted for brevity. In English, when a key is pressed, I start a timer that waits the same moment that it usually expects to wait for a long click ( ViewConfiguration.getLongPressTimeout() ), and then ViewConfiguration.getLongPressTimeout() long click event in the source stream. Subsequent keystrokes and keystrokes can cancel any active timer.

 public class MyIME extends InputMethodService implements KeyboardView.OnKeyboardActionListener { : : private Timer timerLongPress = null; : : @Override public void onCreate() { super.onCreate(); : : timerLongPress = new Timer(); : : } @Override public void onRelease(final int primaryCode) { : : timerLongPress.cancel(); : : } @Override public void onPress(final int primaryCode) { : : timerLongPress.cancel(); : : timerLongPress = new Timer(); timerLongPress.schedule(new TimerTask() { @Override public void run() { try { Handler uiHandler = new Handler(Looper.getMainLooper()); Runnable runnable = new Runnable() { @Override public void run() { try { MyIME.this.onKeyLongPress(primaryCode); } catch (Exception e) { Log.e(MyIME.class.getSimpleName(), "uiHandler.run: " + e.getMessage(), e); } } }; uiHandler.post(runnable); } catch (Exception e) { Log.e(MyIME.class.getSimpleName(), "Timer.run: " + e.getMessage(), e); } } }, ViewConfiguration.getLongPressTimeout()); : : } public void onKeyLongPress(int keyCode) { // Process long-click here } 
0
source

Source: https://habr.com/ru/post/979479/


All Articles