How to search with enter key on android custom InputMethodService?
Asked Answered
I

2

7

I want to search with my android custom keyboard with the enter key, but it does not work.
I've already mapped the keys, I just need to trigger the "search action" on a search text field, just like searching on google.

I tried this code for triggering the search action, but it doesn't work:

ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER));

Here is my method for overwriting the enter key event:

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;
    }
}

My xml layout is:

<?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"/>

I don't have any EditText in my layout to set android:imeOptions="actionSearch".

Inductance answered 3/3, 2016 at 18:54 Comment(0)
C
1

You have to map your keys and overwrite the enter key press, then put your search code inside.

@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;
    }
}

In case you don't have custom keyCode you can see some here and here.

Claudieclaudina answered 3/3, 2016 at 19:3 Comment(1)
Code worked. but i don't have any EditText. in xml i have <android.inputmethodservice.KeyboardView/>Inductance
J
1

try his code

 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;
        }
    });
Jana answered 15/3, 2016 at 4:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.