Sunday, April 21, 2013

Android: EditText in ListView lose focus when the soft keyboard appears

Problem:
Using (numeric) EditText in ListView

1. tab on a EditText field
2. numeric keyboard show up
3. EditText lose focus
4. numeric keyboard switch to back to a regular keyboard


Workaround:
Use ScrollView + LinearLayout instead of ListView...

Ref:
android - When the soft keyboard appears, it makes my EditText field lose focus - Stack Overflow
android - Buggy ListView makes me sad - Stack Overflow

1 comment:

Matt said...

See the answer to a similar question here: http://forums.xamarin.com/discussion/comment/51259/#Comment_51259

You need to set the DescendantFocusability property of your ListView to "afterDescendants".

You can do this in the XML like this:

descendantFocusability="afterDescendants"

or in code like this:

listView.DescendantFocusability = DescendantFocusability.AfterDescendants;

You also need to set listView.ItemsCanFocus = true;

Also, you need to specify what is happening to the main window of your activity when the soft keyboard is shown. This is done by changing the WindowSoftInputMode attribute. You probably want to set it to AdjustPan so that your listview is not resized and thus GetView isn't called again. This is probably what is happening now when you hide the keyboard, GetView is called again and reset the original value in the EditText.

You can do this using the attribute WindowSoftInputMode = SoftInput.AdjustPan on your main activity class.