Android check keyboard visible

Animating your keyboard (part 1)

New WindowInsets APIs for checking the keyboard (IME) visibility and size

New in Android 11 is the ability for apps to create seamless transitions between the on screen keyboard being opened and closed, and it’s all powered by lots of improvements to the WindowInsets APIs in Android 11.

Here you are two examples of it in action on Android 11. It has been integrated into the Google Search app, as well as the Messages app:

So let’s take a look at how you can add this sort of experience to your apps. There are three steps:

  1. First, we need to go edge-to-edge.
  2. The second step is for apps to start reacting to inset animations.
  3. And the third step is by apps taking control of and driving inset animations, if it makes sense for your app.

Each of these steps follow on from each other, so we’ll cover each in separate blog posts. In this first post, we’ll cover going edge-to-edge, and the related API changes in Android 11.

Going edge-to-edge

Last year we introduced the concept of going edge to edge, as a way for apps to make the most of the new gestural navigation in Android 10:

Gesture Navigation: Going edge-to-edge (I)

With Android Q, a new system navigation mode has been added, allowing the user to navigate back, and to the home screen…

As a quick re-cap, going edge to edge results in your app drawing behind the system bars, like you can see on the left.

To quote myself from last year:

By going edge-to-edge, apps will instead be laid out behind the system bars. This is to allow your app content to shine through to create a more immersive experience for your users.

So what has going edge to edge got to do with the keyboard?

Well going edge to edge is actually more than just drawing behind the status and navigation bars. It’s apps taking responsibility for handling those pieces of system UI which might overlap with the app.

The two obvious examples being the status bar and navigation bar, which we mentioned earlier. Then we have the on-screen-keyboard, or IME as it is sometimes referred to; it’s just another piece of system UI to be aware of.

How do apps go edge to edge?

If we flash back to our guidance from last year, going edge to edge is made up of 3 tasks:

  1. Change system bar colors
  2. Request to be laid out fullscreen
  3. Handle visual conflicts

We’re going to skip the first task, because nothing has changed there since last year. The guidance for steps 2 & 3 has been updated with some changes in Android 11. Let’s take a look.

#2: Request to be laid out fullscreen

For the second step, apps needed to use the systemUiVisibility API with a bunch of flags, to request to be laid out fullscreen:

Читайте также:  Cm browser ad blocker для андроид

If you were using this API and have updated your compile SDK version to 30, you’ll have seen that all of these APIs are now deprecated.

They’ve been replaced with a single function on Window called setDecorFitsSystemWindows() :

Instead of the many flags, you now pass in a boolean: false if apps want to handle any system window fitting (and thus go fullscreen).

We also have a Jetpack version of the function available in WindowCompat , which was released recently in androidx.core v1.5.0-alpha02 .

So that’s the 2nd step updated.

#3: Handling visual conflicts

Now let’s look at the third step: avoiding overlaps with the system UI, which can be summarised as using the window insets to know where to move content to, to avoid conflicts with the system UI. On Android, insets are represented by the WindowInsets class, and WindowInsetsCompat in AndroidX

If we take a look at WindowInsets before the updates from API 30, the most common inset type to use is the system window insets. These cover the status and navigation bars, and also the keyboard when it is open.

To use WindowInsets , you would typically add an OnApplyWindowInsetsListener to a view, and handle any insets which are passed to it:

Here we’re fetching the system window insets, and then updating the view’s padding to match, which is a very common use case.

There are a number of other inset types available, including the recently added gesture insets from Android 10:

Similar to the systemUiVisibility API, much of the WindowInsets APIs have been deprecated, in favor of new functions to query the insets for different types:

  • getInsets(type: Int) which will return the visible insets for the given types.
  • getInsetsIgnoringVisibility(type: Int) which returns the insets, regardless of whether they’re visible or not.
  • isVisible(type: Int) which returns true if the given type is visible.

We just mentioned ‘types’ a lot there. These are defined in the WindowInsets. Type class as functions, each returning an integer flag. You can combine multiple types, using a bitwise OR to query for combined types, which we’ll see in a minute.

All of these APIs have been backported to WindowInsetsCompat in AndroidX Core, so you can safely use them back to API 14 (see the release notes for more information).

So if we go back to our example from before, to update it to the new APIs, they become:

The IME type ⌨️

Now the keen eyed 👀 among may have been looking at this list of types, and been looking at one type in particular: the IME type.

Well we can finally answer this StackOverflow question, from over 10 years ago (fashionably late), about how to check the visibility of the keyboard. 🎉

How to check visibility of software keyboard in Android?

To get the current keyboard visibility, we can fetch the root window insets, and then call the isVisible() function, passing in the IME type.

Similarly if we want to find out the height, we can do that too:

If we need to listen to changes to the keyboard, we can use the normal OnApplyWindowInsetsListener , and use the same functions:

Hiding/showing the keyboard

Since we’re on a roll of answering StackOverflow questions, how about this one from 11 years ago, of how to close the keyboard.

How do you close/hide the Android soft keyboard?

Here we are going to introduce another new API in Android 11, called WindowInsetsController .

Apps can get access to a controller from any view, and then show or hide the keyboard by calling either show() or hide() , passing in the IME type:

Читайте также:  Можно ли прошит android

But hiding and showing the keyboard isn’t all that the controller can do…

WindowInsetsController

Earlier we said that some of the View.SYSTEM_UI_* flags have been deprecated in Android 11, replaced with a new API. Well there were a number of other View.SYSTEM_UI flags available, related to changing the system UI appearance or visibility, including:

  • View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
  • View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
  • View.SYSTEM_UI_FLAG_LAYOUT_STABLE
  • View.SYSTEM_UI_FLAG_LOW_PROFILE
  • View.SYSTEM_UI_FLAG_FULLSCREEN
  • View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
  • View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
  • View.SYSTEM_UI_FLAG_IMMERSIVE
  • View.SYSTEM_UI_FLAG_VISIBLE
  • View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
  • View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR

Similar to the others, these have also been deprecated too in API 30, replaced with APIs in WindowInsetsController .

Instead of going through the migration for all of these flags, we’ll cover a few common scenarios and see how to update them:

Immersive modes

Here you can see a drawing app, which hides the System UI to maximise the space available for drawing:

To implement that using WindowInsetsController we use the hide() and show() functions like before, but this time we pass in the system bars type:

The app also uses immersive mode, allowing the user to swipe the system bars back in once hidden. To implement this using WindowInsetsController we change the hide and show behaviour to BEHAVIOR_SHOW_BARS_BY_SWIPE :

Similarly, if you were using sticky immersive mode, this is implemented using the BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE instead:

Status bar content color

The next scenario is around the status bar content color. Here you see two apps:

On the left the app has a dark status bar background, with light content like the time and icons. But if we instead want a light status bar background with dark content, like the right, we can use WindowInsetsController too.

To do that, we can use the setSystemBarsAppearance() function, passing in the APPEARANCE_LIGHT_STATUS_BARS value:

If you instead want to set a dark status bar, by passing in 0 instead to clear the value.

Note: you could implement this in your theme instead, by setting the android:windowLightStatusBar attribute. This might be preferable if you know the value won’t change.

Similarly, the APPEARANCE_LIGHT_NAVIGATION_BARS flag is available which provides the same functionality for the navigation bars.

WindowInsetsController in AndroidX?

Unfortunately a Jetpack version of this API does not exist yet, but we are working on it. Stay tuned.

Going edge-to-edge: ✔️

So that’s the first step done. In the next blog post we’ll investigate the second step: apps reacting to inset animations.

Источник

How do I Detect if Software Keyboard is Visible on Android Device?

Posted by: admin November 16, 2017 Leave a comment

Is there a way in Android to detect if the software (a.k.a. “soft”) keyboard is visible on screen?

There is no direct way – see http://groups.google.com/group/android-platform/browse_thread/thread/1728f26f2334c060/5e4910f0d9eb898a where Dianne Hackborn from the Android team has replied. However, you can detect it indirectly by checking if the window size changed in #onMeasure. See How to check visibility of software keyboard in Android?.

This works for me. Maybe this is always the best way for all versions.

I created a simple class that can be used for this: https://github.com/ravindu1024/android-keyboardlistener. Just copy it in to your project and use as follows:

Very Easy

1. Put id on your root view

rootView is just a view pointing to my root view in this case a relative layout :

2. Initialize your root view in your Activity:

RelativeLayout rootView = (RelativeLayout) findViewById(R.id.addresses_confirm_root_view);
3. Detect if keyboard is opened or closed by using getViewTreeObserver()

It worked for me everytime.

It will return true, if software keyboard is visible.

You can use the callback result of showSoftInput() and hideSoftInput() to check for the status of the keyboard. Full details and example code at

Then wrote this method:

You may then use this to test all fields (EditText, AutoCompleteTextView, etc) that may have opened a softkeyboard:

Читайте также:  Кэш для trainz android

Addmittely not an ideal solution, but it gets the job done.

Try this code it’s really working if KeyboardShown is Shown then this function return true value….

In my case i had only one EditText to manage in my layout so i came up whit this solution.
It works well, basically it is a custom EditText which listens for focus and sends a local broadcast if the focus changes or if the back/done button is pressed.
To work you need to place a dummy View in your layout with android:focusable=»true» and android:focusableInTouchMode=»true» because when you call clearFocus() the focus will be reassigned to the first focusable view.
Example of dummy view:

Additional infos

The solution which detects the difference in layout changes doesn’t work very well because it strongly depends on screen density, since 100px can be a lot in a certain device and nothing in some others you could get false positives.
Also different vendors have different keyboards.

This was much less complicated for the requirements I needed. Hope this might help:

On the MainActivity:

The default primative boolean value for mKeyboardStatus will be initialized to false.

Then check the value as follows, and perform an action if necessary:

I had a similar problem. I needed to react to the Enter button on screen (which hid the keyboard). In this case you can subscribe to the OnEditorAction of the text view the keyboard was opend with – if you have multiple editable boxes, then subscribe to all of them.

In your Activity you have full control of the keyboard, so at no point will you face the problem whether the keyboard is opened or not, if you listen to all opening and closing events.

I did this by setting a GlobalLayoutListener, as follows:

There is a direct method to find this out. And, it does not require the layout changes.
So it works in immersive fullscreen mode, too.
But, unfortunately, it does not work on all devices. So you have to test it with your device(s).

The trick is that you try to hide or show the soft keyboard and capture the result of that try.
If it works correct then the keyboard is not really shown or hidden. We just ask for the state.

To stay up-to-date, you simply repeat this operation, e.g. every 200 milliseconds, using a Handler.

The implementation below does just a single check.
If you do multiple checks, then you should enable all the (_keyboardVisible) tests.

I did this as follows, but its relevet only if your goal is to close / open the keyboad.

close example: (checking if keyboard already closed, if not – closing)

In Android you can detect through ADB shell. I wrote and use this method:

Here is a workaround to know if softkeyboard is visible.

  1. Check for running services on the system using ActivityManager.getRunningServices(max_count_of_services);
  2. From the returned ActivityManager.RunningServiceInfo instances, check clientCount value for soft keyboard service.
  3. The aforementioned clientCount will be incremented every time, the soft keyboard is shown. For example, if clientCount was initially 1, it would be 2 when the keyboard is shown.
  4. On keyboard dismissal, clientCount is decremented. In this case, it resets to 1.

Some of the popular keyboards have certain keywords in their classNames:

  1. Google AOSP = IME
  2. Swype = IME
  3. Swiftkey = KeyboardService
  4. Fleksy = keyboard
  5. Adaptxt = IME (KPTAdaptxtIME)
  6. Smart = Keyboard (SmartKeyboard)

From ActivityManager.RunningServiceInfo, check for the above patterns in ClassNames.
Also, ActivityManager.RunningServiceInfo’s clientPackage=android, indicating that the keyboard is bound to system.

The above mentioned information could be combined for a strict way to find out if soft keyboard is visible.

Источник

Оцените статью