Friday, March 23, 2012

How to listen to the softkeyboard done button in android?


How to listen to the softkeyboard done button in android?


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
?
Drag and copy the code
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
<?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
?
Drag and copy the code
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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;
        }
    };
}

No comments: