Saturday, July 14, 2012

Show Android soft keyboard programatically

One of my app is an English-to-Thai dictionary, so I want to show the soft keyboard when the user starts the program.

The problem is that if the code is called from onCreate(), sometime the soft keyboard won't show.  I guess internally something is not quite ready.  Anyway, it is easily fixed by delay it a bit.  In the code below, et is my EditText, in which they user will type the word, so my code looks like this:
et.postDelayed(new Runnable() {
    public void run() {
        InputMethodManager keyboard = (InputMethodManager)
        getSystemService(Context.INPUT_METHOD_SERVICE);
        keyboard.showSoftInput(et, 0);
    }
}, 200);
This code delays the execution of displaying soft keybaord for 200ms.  There must be another more elegant way, but this code works fine for all Android devices I tested, so it stays.

No comments:

Post a Comment