Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why android InputMethodManager.showSoftInput() returns false?

Recently while developing an app, I faced an issue. I have searched a lot on google but couldn't find any solution. In the end I came across this Android issue tracker

To explain my issue, I have made a sample App.

Basic Working of my Sample App

  1. I have a screen, which has an EditText, a Button and a RelativeLayout.
  2. Width and Height of RelativeLayout is 0px. It is just a view to move focus away from EditText.
  3. When App is launched focus is on RelativeLayout, not on EditText(so that there is not blinking cursor in it.)
  4. When a user clicks on Button I just move focus to RelativeLayout using requestFocus() call on RelativeLayout.
  5. When user taps on EditText, keyboard comes up. I can enter text in that.

What I want to achieve

  1. If I change orientation of phone when keyboard is visible then after orienation changes, keyboard should stay.
  2. If keyboard is visible and some other activity comes on top of it for e.g. alarm, facebook chat heads, opening something from notification area, locking unlocking device, etc.. then on returning back to sample app keyboard should be visible.

How I am achieving this

  1. In onSaveInstanceState(), I check if focus is on EditText then put a boolean variable in Bundle.
  2. In onStop(), I am setting a one boolean flag wasEditing = true.
  3. In onRestoreInstanceState(), I checked if Bundle has flag value set in onSaveInstanceState(). If yes then I am make wasEditing = true.
  4. In onResume(), I check this wasEditing and if it is true, I request focus for EditText.
  5. After that I call imm.showSoftInput(mEditText, InputMethodManager.SHOW_IMPLICIT,resultRec)

Where I am getting problem
Sometimes after executing this call, Keyboard is not visible in few cases, like during orientation change.
When I put logs I have found this function is returning false
But if I make this showSoftInput() call with some delay of 100ms using mEditText.postDelayed() in onResume() everything works fine.

Question In what cases this function returns false and why delay is working?

Note Although I have solved my problem using delay, but I still want to know why it is behaving like that.

like image 366
Vipin Sharma Avatar asked Apr 30 '14 05:04

Vipin Sharma


1 Answers

This is a problem I ran into today as well. Of my 8 android devices only 1 has the problem and it's running Android 4.0.4.

The problem was fixed by adding

mEditText.requestFocus();
mEditText.requestFocusFromTouch();

before calling mEditText.showSoftInput(...)

You'll see the resultcode from showSoftInput is now true. I noticed that after the mEditText.requestFocus() the isFocused() was still false. Probably a bug in Android 4.0 and perhaps 4.1.

like image 136
Jeroen Ost Avatar answered Sep 21 '22 23:09

Jeroen Ost