Saturday, March 24, 2012

Android: Show soft keyboard with EditText on android

So you wish to show or hide virtual (soft) keyboard in your Android app.

You are executing action that places focus into the EditText field.

You the need to bring up a soft keyboard on your android (or emulator).

Note:
EditTexts are focusable while the system is in 'touch mode'.
The first click event focuses the control, while the second click event actually fires the OnClickListener. If you disable touch-mode focus with:
(xml) View attribute
1
android:focusableInTouchMode
OR
(java)
1
freeText.setFocusableInTouchMode(false);

Then OnClickListener should fire as expected.
--- o --- o --- o --- o --- o --- o --- o ---

To launch the keyboard requires the following additional code:

xml:
------
1
2
3
4
5
6
7
8
9
<EditText android:id="@+id/freeText"
android:layout_width="@dimen/freeTextBox_width"
android:layout_height="@dimen/freeTextBox_height"
android:layout_weight="1"
android:inputType="textShortMessage|textAutoCorrect|textCapSentences|textMultiLine"
android:imeOptions="actionSend|flagNoEnterAction"
android:maxLines="4"
android:maxLength="2000"
android:hint="@string/compose_hint"/>


Notice the imeOptions: actionSend|flagNoEnterAction:
The tell you android to apply the SEND button action to the EditText and not to accept ENTER on soft keyboard.

Java:
-------
1
2
3
final TextView freeText = (TextView)findViewById(R.id.freeText);

freeText.setFocusableInTouchMode(true);

FIRST POSSIBILTY USING THE setOnClickListener:
----------------------------------------------
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
freeText.setOnClickListener(new OnClickListener() {
   
 public void onClick(View v) {
  // Set keyboard
  InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
    // Lets soft keyboard trigger only if no physical keyboard present
    imm.showSoftInput(freeText, InputMethodManager.SHOW_IMPLICIT);
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
   }
  });

SECOND POSSIBILTY USING THE setOnFocusChangeListener:
-----------------------------------------------------
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
freeText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
      public void onFocusChange(View v, boolean hasFocus) {
          if (hasFocus) {
//              getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
           getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
          } else if (!hasFocus) {
           getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
          }
      }
  });

You do not need to use both...they can be implemented for other use.


Jud Luck...


1 comment:

  1. Great post...thanx, you saved me some time tonight.
    :-)

    ReplyDelete