Sunday, September 19, 2010

Android – set a focus and show soft keyboard experiments

Today I was playing with virtual keyboard and setting focus on a control (only with EditText for moment).  Here follows a short recap of my findings.

To force focus via layout:

<EditText android:id="@+id/event_title_textbox"
    android:layout_width="fill_parent" android:layout_height="wrap_content"
    android:hint="@string/event_title_hint">
    <requestFocus />
</EditText>

To focus programmatically:

...
titleTextBox = (EditText)findViewById(R.id.event_title_textbox);
titleTextBox.requestFocus();
...
 

To cause a virtual keyboard to be shown on focus (source: http://stackoverflow.com/questions/2403632/android-show-soft-keyboard-automatically-when-focus-is-on-an-edittext). Make sure to clear that requestFocus element used in the layout above, as otherwise it will not show unless it looses focus and gains it again.

titleTextBox.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            parentActivity
                    .getWindow()
                    .setSoftInputMode(
                            WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }
    }
});
titleTextBox.requestFocus();

Another way to setup a keyboard to appear is through the manifest:

...
<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".Main"
              android:label="@string/app_name"
              android:windowSoftInputMode="stateVisible"
              >
...

When experimenting I was not actually getting what I wanted until I realized I should have an emulator device with no hardware keyboard:

image

This is it for my discoveries. Happy coding to You!

Post a Comment