【问题标题】:How to search with enter key on android custom InputMethodService?如何在android自定义InputMethodService上使用回车键进行搜索?
【发布时间】:2016-06-17 06:38:49
【问题描述】:

我想使用我的 android 自定义键盘和 enter 键进行搜索,但它不起作用。
我已经映射了键,我只需要在搜索文本字段上触发“搜索操作”,就像在谷歌上搜索一样。

我尝试了这段代码来触发搜索操作,但它不起作用:

ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_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;
    }
}

我的 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"/>

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

【问题讨论】:

    标签: android keyboard android-softkeyboard keyevent android-input-method


    【解决方案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;
        }
    }
    

    如果您没有自定义 keyCode,您可以看到一些 herehere

    【讨论】:

    • 代码有效。但我没有任何 EditText。在 xml 我有
    【解决方案2】:

    试试他的代码

     public boolean onKey(View v, int keyCode, KeyEvent event) {
                // If the event is a key-down event on the "enter" button
                if ((event.getAction() == KeyEvent.ACTION_DOWN)
                        && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    // do ur stuff
                    return true;
                }
                return false;
            }
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-04
      相关资源
      最近更新 更多