Ruchir Baronia Ruchir Baronia - 7 months ago 12
Java Question

Why cant I write text?

I have been trying to get this to work for the last three hours, and I need your help now. I simply want to record the text from my editText when the user clicks "done":

e.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {

Log.v(TAG, "KEYCODE: " +keyCode);
Toast.makeText(MainActivity.this, "" +keyCode, Toast.LENGTH_SHORT).show();

if ((keyCode == EditorInfo.IME_ACTION_DONE) && (event.getAction() == KeyEvent.ACTION_DOWN)) {

Log.v(TAG, "DONE!");
Toast.makeText(MainActivity.this, "" +e.getText(), Toast.LENGTH_LONG).show();

return false;
}
return false;
}
});


Here is the XML:

<EditText
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_alignBottom="@+id/textView4"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_toRightOf="@+id/textView4"
android:layout_toEndOf="@+id/textView4"
android:imeOptions="actionDone"
android:inputType="text"

/>


The problem is that my
onKey
is not even displaying any toasts, and I am unable to get the user input when they click done. I have tried changing so many things in my if statement, but now even the
onKey
is not getting called. What am I doing wrong?

Thanks for taking the time to answer my question :)

Answer

Why your code is not working is answered in the docs.

Key presses on soft input methods are not required to trigger the methods in this listener, and are in fact discouraged to do so. The default android keyboard will not trigger these for any key to any application targetting Jelly Bean or later, and will only deliver it for some key presses to applications targetting Ice Cream Sandwich or earlier.

If you are trying to get the user input when they click done, you can try something like

e.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            Toast.makeText(MainActivity.this, e.getText(), Toast.LENGTH_SHORT).show();
            return true;
        }
        return false;
    }
});