如何在android自定义InputMethodService上使用回车键进行搜索?

Joh*_*ohn 6 keyboard android keyevent android-softkeyboard android-input-method

我想用我的Android自定义键盘用enter键搜索,但它不起作用.
我已经映射了密钥,我只需要在搜索文本字段上触发"搜索操作",就像在Google上搜索一样.

我尝试使用此代码来触发搜索操作,但它不起作用:

ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER));
Run Code Online (Sandbox Code Playgroud)

这是我覆盖enter键事件的方法:

public class Keyboard extends InputMethodService
    implements KeyboardView.OnKeyboardActionListener {

@Override
public void onStartInputView(EditorInfo info, boolean restarting) {
    super.onStartInputView(info, restarting);

    setInputView(onCreateInputView());

    switch (EditorInfo.IME_MASK_ACTION | EditorInfo.IME_FLAG_NO_ENTER_ACTION) {

        case EditorInfo.IME_ACTION_SEARCH:
            Toast.makeText(this, "test", Toast.LENGTH_SHORT).show();
            //Action Search
            break;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的xml布局是:

<?xml version="1.0" encoding="UTF-8"?>
<android.inputmethodservice.KeyboardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/keyboard"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:keyPreviewHeight="60dp"
    android:keyPreviewOffset="12dp"
    android:keyPreviewLayout="@layout/preview"
    android:visibility="visible"/>
Run Code Online (Sandbox Code Playgroud)

我的布局中没有任何EditText可供设置android:imeOptions="actionSearch".

Ric*_* A. 1

您必须映射您的按键并覆盖回车键,然后将搜索代码放入其中。

@Override
public void onKey(int primaryCode, int[] keyCodes) {     
    switch(primaryCode){

        case android.inputmethodservice.Keyboard.KEYCODE_DONE:
            ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER));
            break;
    break;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您没有自定义 keyCode,您可以在此处此处查看一些。