M Rajoy
M Rajoy

Reputation: 4084

Hide elements when keyboard shows up

If you take a look at how IFTTT and Tumblr work, you will see that when you click on the login form inputs and the keyboard shows up, the logo is removed with a cool animation.

I want to do something similar, so I've searched a bit about detecting soft keyboard showing/hiding events, but none of the solutions I found (like this or this) is reliable.

How can I achieve this behavior?

My login screen is somewhat crowded so I need to hide elements when the keyboard shows up or otherwise they wont fit for all possible screen configs.

Upvotes: 0

Views: 401

Answers (1)

kris larson
kris larson

Reputation: 30985

I had this same problem.

In my app, the home screen has an EditText for searching as well as a nice big logo. When the user presses the EditText to enter a search term, the soft keyboard would pop up and compress the layout such that using adjustResize looked just as bad as using adjustPan.

After doing some research on how to tell when the keyboard shows up and reading this rant from Dianne Hackborn telling us that we really shouldn't care when the keyboard shows up, I decided to rethink this and look at it as a layout problem. It was only if the height of the layout went below a certain threshold that I had a problem.

I created a subclass for the main layout with an override for onLayout() that would trigger a callback event when a) the layout height went from below threshold to above threshold and b) the height went from above threshold to below threshold. Depending on which way it goes, I would kick off an animation to either remove the logo or redisplay it.

I won't post that code here, because if I were to do it now, I would just use a ViewTreeObserver.OnGlobalLayoutListener to find out when the layout changed. It would be most similar to this answer, except that instead of testing the amount of height change, I would set a certain threshold and run the appropriate animation if the height crosses the threshold.

Upvotes: 1

Related Questions