How to listen to the softkeyboard done button in android?

By | July 13, 2011

Instead of using a button on the view we can use the softkeyboard done button to trigger an action. The action can include calling another activity or retrieving the data from the EditText etc.

The main.xml contains an Edittext

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
	<TextView
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:text="@string/hello"
		/>
	<EditText android:layout_width="match_parent"
		android:singleLine="true"
		android:inputType="textNoSuggestions"
		android:layout_height="wrap_content"
		android:id="@+id/editText1">
			<requestFocus></requestFocus>
		</EditText>
</LinearLayout>

For listening to the keyboard event we need onKeyListener

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

public class TesstActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

		EditText text = (EditText) findViewById(R.id.editText1);
		text.setOnKeyListener(onSoftKeyboardDonePress);

    }

    private View.OnKeyListener onSoftKeyboardDonePress=new View.OnKeyListener()
    {
        public boolean onKey(View v, int keyCode, KeyEvent event)
        {
            if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)
            {
            	Toast.makeText(TesstActivity.this, "checking event", Toast.LENGTH_LONG).show();
            }
            return false;
        }
    };
}

4 thoughts on “How to listen to the softkeyboard done button in android?

  1. ishan

    onpreexecute(){}
    onpostexecute(){}

    doinbackground()
    {
    ……………..
    ………….
    …………
    x=50;
    name=”ttt”;
    age=20;

    }

    i want to know how can i access all values in doinbackground method ??

    Reply
  2. Raquel

    Hi,

    There’s a way to keep the keyboard shown after pressing the done key?

    Thanks.

    Reply
    1. James

      Raquel,

      That’s a strange requirement. In that case you can remove the ‘DONE’ key.

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *