Submit form with virtual keyboard

Updated in Android

In the usual case a form in Android application is built with input fields and a submit button. Usually the user inputs some values to the input fields and presses the submit button and gets some feedback based on that.

This tutorial shows how to submit the form without the need to press the submit button. That is, the user can submit the form straight from the virtual keyboard.

Basics

The form submitting is achieved by listening to the user presses with OnEditorActionListener. The example below includes an Activity with a simple form which is submitted when the user presses the done button on the keyboard.

Example

package com.tanelikorri.android.keyboardsubmit;

import android.os.Bundle;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class KeyboardSubmitActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        EditText pwField = findViewById(R.id.main_password);

        pwField.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {

                // Check if done button was pressed
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    handleLogin();
                }

                return false;
            }
        });
    }

    /**
     * Handle login when done button has been pressed
     */
    private void handleLogin() {
        Toast.makeText(this, "Handling login!", Toast.LENGTH_LONG).show();
    }
}

In the above example an action listener is added to the password field with setOnEditorActionListener. The listener listens to the keyboard action key presses and if done button is pressed then the listener calls the handleLogin method. All available keyboard actions are listed in the EditorInfo class, the link is in the bottom of the page.

The setOnEditorActionListener is quite handy tool and it can be used for other scenarios as well. For example you could check that the form fields are filled correctly (or at all) with it.

Screenshots

Text input Done pressed

Source code

Source code for the whole example project is available here

Further reading