Wednesday, 11 September 2013

Capturing the keyboard action in the edit text

The edit text is an text field in the layout which is used to enter the text such as name, email address or password.

By default the enter key in our soft keyboard is used to enter a new line to the edit text. But it could be customized to set a specific action such as done or next.

To do so, the edit text must be customized in a special way and handled in the java file.

Here is an example of using the enter key as the finish(done) action.

XML:
<EditText
android:id="@+id/editText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Press on the done button"
android:hint="Press on the done button"
        android:imeOptions="actionDone"
android:ems="10"
android:singleLine="true"
/>

The main part is "android:imeOptions", which set the done button to the enter key.

Java:
EditText editText = (EditText)findViewById(R.id.editText);
editText.setOnEditorActionListener(new EditText.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView tv, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
Toast.makeText(context, "You have entered " + tv.getText(), Toast.LENGTH_LONG).show();
return true;
}
return false;
}
});

The source code could be found here:

No comments:

Post a Comment