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!

5 comments:

Unknown said...

Hey...thanks...

I tried everything mentioned in every blog but in vain. Removing requestFocus as in your blog helped.

BR,
Pulkit

usman said...

Hi,

That was really helpful. Solved my problem that i was trying to resolve for around 2 Hours :)

Thanks.

Anonymous said...

Thank you thank you thank you!

I was crushing my head to figure out why I couldn't see the soft keyboard, even after trying every method on the web! Thanks to your post, I figured it was the AVD containing a hardware keyboard. Very non intuitive. Thanks again.

Anonymous said...

It is worth checking how your AVD handles Touch Mode as described in

http://developer.android.com/reference/android/view/View.html

I had this problem until I realised that my AVD assumes non-Touch until I clicked on the screen. Then it flips to Touch Mode and shows the soft input keyboard

Anonymous said...

thanks a bunch! queuing off onFocusChanged was the key