Android Soft keyboard display and hide, so the operation is right

Source: Internet
Author: User

First, preface

If there is a need to use the input, there will usually be a need to automatically eject or close the soft keyboard needs. Opening Ming Yi, this article will talk about pop-up and the soft keyboard to close some of the details, will eventually be analyzed from the source code.

To operate a soft keyboard, you need to use the Inputmethodmanager, which is a system service that can be used to Context.getSystemService() get to it. Many of the key logic codes are implemented in Inputmethodmanagerservice.

Special Note: All the analysis of this article source code, are based on the Android 26 source code.

Second, the Operation Soft Keyboard 2.1 Inputmethodmanager

As mentioned earlier, want to operate a soft keyboard, need to use Inputmethodmanager, it is a system service, want to get it, can use getSystemService() , get to it.

After all, is the system service, when used for security, or to empty, avoid null pointers.

2.2 Display Soft Keyboard

In Inputmethodmanager, there are two methods showSoftInput() and showSoftInputFromInputMethod() , in fact, only showSoftInput() valid.

It has two overloaded methods, and usually we will use the method of its two parameters.

Here we only need to pass two parameters. It needs a view first, the use of a soft keyboard is to input, and the input needs to have to receive input view, here to receive input view, preferably a EditText (but this is not necessary).

The second parameter, flags, is a flag bit, as you can see from the document on the method signature above, that it receives 0 or show_inpyt_implicit two arguments, but in fact, it has a third argument and the other is show_forced.

Can see 1, 2 have special meaning, in fact, they do not affect the display, but in the hidden time, there will be some restrictions, these later look at the source of the time to say, generally no special need, we directly pass 0 is good.

Now, briefly summarize showSoftInput() the key points that the call will take effect:

1, the first parameter, preferably EditText or its subclasses.

Given that the soft keyboard is for input, EditText is a control that receives input. And this is not absolute, if not a EditText, you must ask this View has two attributes, respectively: android:focusable="true" and android:focusableInTouchMode="true" .

2. The first parameter must be focusable, and the focus is currently acquired.

EditText is allowed to get focus by default, but if there are multiple controls in the layout that can get the focus, you need to get the View we passed in to the focus in advance. You can use methods to get focus requestFocus() .

3. The layout must be loaded and completed.

In onCreate() , if an immediate call showSoftInput() is not in effect. If you want to eject the keyboard at the start of the page, you can either set properties on the Activity, android:windowSoftInputMode or do a lazy load, which View.postDelayed() is also a solution.

So finally, the complete display of the soft keyboard code is as follows.

2.3 Hiding the soft keyboard

Although the showSoftInput() method is effective, but to hide the soft keyboard, there is no corresponding hideSoftInput() method, but there is a hideSoftInputFromWindow() way to hide the soft keyboard.

Let's take a look at the signature of this method, which also has two methods to invoke.

It receives two parameters, the first parameter is a ibinder, you can pass a View.getWindowToken() Windowtoken object directly. And the second parameter, is to hide the logo of the soft keyboard, if there is no special requirements, the direct transfer of 0 is good.

Note here although in principle need to pass a previous pop-up keyboard pass time, pass the view of the Windowtoken, but the reality is that you only need to pass a present in the current layout viewtree, feel free to a view of the windowtoken on it.

This is the code that eventually hides the software.

2.4 Toggle Keyboard Pop-and-hide

In Inputmethodmanager, there is also a toggleSoftInput() method that, like its name, allows the soft keyboard to toggle between display and hide.

The method, receives two flags, respectively control show and hide time of the logo, their meaning and the previous introduction showSoftInput() and hideSoftInputFromWindow() consistent, so there is no special requirements, direct transfer 0 is good.

toggleSoftInput()The method does not require a View or windowtoken to be passed, so it does not have showSoftInput() some limitations, but it still needs to be called after the layout has been drawn.

Although this method is very limited, we will not use it. The main reason is that it is a switch method that does the opposite of the current state. This leads to many times when we cannot determine the current display state of the soft keyboard directly according to the method provided by Inputmethodmanager, so that the effect of invoking it cannot be determined.

Iii. Source Code Analysis 3.1 flag details

Some of the previous methods, all need to pass a flag value, the document is not described in detail, we will from the source point of view, to analyze the meaning of these flags.

Let's look at the showSoftInput() method first.

It will eventually call the mService.showSoftInput() method, the final source, you need to see the code in the Inputmethodmanagerservice. And showSoftInput() the method will eventually be called showCurrentInputLocked() .

The code for this method is very long, and we only care about flag-related code.

As you can see, flag affects two fields, mshowexplicitlyrequested and mshowforced, and show_forced is a bit stronger.

hideSoftInputFromWindow()method, and eventually the method in Inputmethodmanagerservice is called hideCurrentInputLocked() .

From DEBUG == true the Log that will be output, you can already see the meaning. This will be based on the display and hide the two flags passed, that is, if the flag is used incorrectly, it may lead to return false directly, so that the soft keyboard can not be hidden, the details of the control code is clear, not in the article repeated these details.

So this is why the previous mentioned, if there is no special requirements, direct transfer 0 is good, can circumvent this limitation.

3.2 How to tell if the soft keyboard pops up

Since the toggleSoftInput() current soft keyboard can be based on the state of different operations, then there must be a way to determine the status of the current soft keyboard.

Then we continue to follow toggleSoftInput() the method of source code.

The method is eventually called to the Inputmethodservice onToggleSoftInput() method.

In this method, the method is used to isInputViewShow() determine whether the current soft keyboard is in the display popup state. But we have no way to interact directly with Inputmethodservice, and we have no way to directly get the current keyboard display.

If you want to listen to the keyboard pop-up and the collection, you can use Viewtreeobserver.ongloballayoutlistener this monitoring, to listen to the layout adjustment, so as to determine the keyboard pop-up and hidden. These details have time to talk.

Iv. keyboardutils

Now that we know the details of how to pick up and eject the soft keyboard, let's write a helper class to solve the problem. So that you can get it.

Java and Kotlin versions are available here.

4.1 Java Edition
 Public classkeyboardutils { Public Static void Showkeyboard(View view) {Inputmethodmanager IMM = (inputmethodmanager) view.GetContext()                .Getsystemservice(Context.Input_method_service);if(IMM! =NULL) {view.Requestfocus(); Imm.Showsoftinput(View,0); }    } Public Static void Hidekeyboard(View view) {Inputmethodmanager IMM = (inputmethodmanager) view.GetContext()                .Getsystemservice(Context.Input_method_service);if(IMM! =NULL) {Imm.Hidesoftinputfromwindow(View.Getwindowtoken(),0); }    } Public Static void  Togglesoftinput(View view) {Inputmethodmanager IMM = (inputmethodmanager) view.GetContext()                .Getsystemservice(Context.Input_method_service);if(IMM! =NULL) {Imm.Togglesoftinput(0,0); }    }}
4.2 Kotlin Version
Objectkeyboardktutils{FunShowkeyboard(View:view) {ValIMM = view.Context.Getsystemservice(Context.Input_method_service) asInputmethodmanagerif(IMM! =NULL) {view.Requestfocus() Imm.Showsoftinput(View,0)}} FunHidekeyboard(View:view) {ValIMM = view.Context.Getsystemservice(Context.Input_method_service) asInputmethodmanager IMM?.Hidesoftinputfromwindow(View.Windowtoken,0)} FunTogglesoftinput(View:view) {ValIMM = view.Context.Getsystemservice(Context.Input_method_service) asInputmethodmanager IMM?.Togglesoftinput(0,0)    }}

Today, in the background of incense Ink Shadow Public, reply to " growth ". I will send you some of my study materials, including: Android Anti-compilation, algorithm, design mode, virtual machine, Linux, Kotlin, Python, crawler, Web project source code.

Recommended reading:

    • Talk about the shadows and stuff.
    • Use Statelistanimator to add an animation to your clicks!
    • Good code can speak for itself
    • 6 Simple tips on how to write clean Code
    • Handwriting your first Dalvik version of HelloWorld!

Android Soft keyboard display and hide, so the operation is right

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.