Android:如何在软输入/键盘上捕获长按事件?

Sam*_*Cai 6 android android-input-method android-edittext

问题的简短版本:如何在Android中的软输入/键盘上捕获长按事件?

长版:在Android应用程序中,我们有一个多行EditText,我们希望有这样的行为:1.默认情况下,它显示一个DONE按钮,通过点击它,软输入/键盘将被关闭.2.如果用户长按DONE按钮,其行为将更改为ENTER按钮,EditText中将有一个新行.

对于需求#1,我在这里使用了解决方案:https://stackoverflow.com/a/12570003/4225326

对于需求#2,我遇到的阻塞问题是,如何捕获长按事件.我设置了onEditorActionListener,但捕获的事件为null:http://developer.android.com/reference/android/widget/TextView.OnEditorActionListener.html 我搜索了文档,长按相关的方法是针对硬键盘:http:http: //developer.android.com/reference/android/view/View.html#onKeyLongPress(int,android.view.KeyEvent),我找不到一个用于软输入/键盘.

感谢您查看此问题.

Cra*_*974 1

我自己找不到这个答案,所以我手动编写了解决方案。onPress()我在和onRelease()的事件上使用了计时器KeyboardView.OnKeyboardActionListener。这是重要的代码。为了简洁起见,省略了许多 TRY/CATCH。用英语来说,当按下一个键时,我将启动一个计时器,该计时器与长按事件通常等待的时间相同 ( ViewConfiguration.getLongPressTimeout()),然后在原始线程上执行长按事件。随后的按键释放和按键可以取消任何活动的计时器。

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
    }
Run Code Online (Sandbox Code Playgroud)