aboutsummaryrefslogtreecommitdiff
path: root/core/core/src/main/java/androidx/core/view/SoftwareKeyboardControllerCompat.java
blob: dee46e13d7978645f048ef9b175213546bc9f7b9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
/*
 * Copyright 2023 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package androidx.core.view;

import static android.os.Build.VERSION.SDK_INT;

import android.content.Context;
import android.view.View;
import android.view.WindowInsets;
import android.view.WindowInsetsController;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Provide controls for showing and hiding the IME.
 * <p>
 * This class provides the implementation for {@link WindowInsetsControllerCompat#show(int)} and
 * {@link WindowInsetsControllerCompat#hide(int)} for the {@link WindowInsetsCompat.Type#ime()}.
 * <p>
 * This class only requires a View as a dependency, whereas {@link WindowInsetsControllerCompat}
 * requires a Window for all of its behavior.
 */
public final class SoftwareKeyboardControllerCompat {

    private final Impl mImpl;

    public SoftwareKeyboardControllerCompat(@NonNull View view) {
        if (SDK_INT >= 30) {
            mImpl = new Impl30(view);
        } else if (SDK_INT >= 20) {
            mImpl = new Impl20(view);
        } else {
            mImpl = new Impl();
        }
    }

    @RequiresApi(30)
    @Deprecated
    SoftwareKeyboardControllerCompat(@NonNull WindowInsetsController windowInsetsController) {
        mImpl = new Impl30(windowInsetsController);
    }

    /**
     * Request that the system show a software keyboard.
     * <p>
     * This request is best effort. If the system can currently show a software keyboard, it
     * will be shown. However, there is no guarantee that the system will be able to show a
     * software keyboard. If the system cannot show a software keyboard currently,
     * this call will be silently ignored.
     */
    public void show() {
        mImpl.show();
    }

    /**
     * Hide the software keyboard.
     * <p>
     * This request is best effort, if the system cannot hide the software keyboard this call
     * will silently be ignored.
     */
    public void hide() {
        mImpl.hide();
    }

    private static class Impl {
        Impl() {
            //private
        }

        void show() {
        }

        void hide() {
        }
    }

    @RequiresApi(20)
    private static class Impl20 extends Impl {

        @Nullable
        private final View mView;

        Impl20(@Nullable View view) {
            mView = view;
        }

        @Override
        void show() {
            // We'll try to find an available textView to focus to show the IME
            View view = mView;

            if (view == null) {
                return;
            }

            if (view.isInEditMode() || view.onCheckIsTextEditor()) {
                // The IME needs a text view to be focused to be shown
                // The view given to retrieve this controller is a textView so we can assume
                // that we can focus it in order to show the IME
                view.requestFocus();
            } else {
                view = view.getRootView().findFocus();
            }

            // Fallback on the container view
            if (view == null) {
                view = mView.getRootView().findViewById(android.R.id.content);
            }

            if (view != null && view.hasWindowFocus()) {
                final View finalView = view;
                finalView.post(() -> {
                    InputMethodManager imm =
                            (InputMethodManager) finalView.getContext()
                                    .getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(finalView, 0);

                });
            }
        }

        @Override
        void hide() {
            if (mView != null) {
                ((InputMethodManager) mView.getContext()
                        .getSystemService(Context.INPUT_METHOD_SERVICE))
                        .hideSoftInputFromWindow(mView.getWindowToken(),
                                0);
            }
        }
    }

    @RequiresApi(30)
    private static class Impl30 extends Impl20 {

        @Nullable
        private View mView;

        @Nullable
        private WindowInsetsController mWindowInsetsController;

        Impl30(@NonNull View view) {
            super(view);
            mView = view;
        }

        Impl30(@Nullable WindowInsetsController windowInsetsController) {
            super(null);
            mWindowInsetsController = windowInsetsController;
        }

        @Override
        void show() {
            if (mView != null && SDK_INT < 33) {
                InputMethodManager imm =
                        (InputMethodManager) mView.getContext()
                                .getSystemService(Context.INPUT_METHOD_SERVICE);

                // This is a strange-looking workaround by making a call and ignoring the result.
                // We don't use the return value here, but isActive() has the side-effect of
                // calling a hidden method checkFocus(), which ensures that the IME state has the
                // correct view in some situations (especially when the focused view changes).
                // This is essentially a backport, since an equivalent checkFocus() call was
                // added in API 32 to improve behavior and an additional change in API 33:
                // https://issuetracker.google.com/issues/189858204
                imm.isActive();
            }
            WindowInsetsController insetsController = null;
            if (mWindowInsetsController != null) {
                insetsController = mWindowInsetsController;
            } else if (mView != null) {
                insetsController = mView.getWindowInsetsController();
            }
            if (insetsController != null) {
                insetsController.show(WindowInsets.Type.ime());
            } else {
                // Couldn't find an insets controller, fallback to old implementation
                super.show();
            }
        }

        @Override
        void hide() {
            WindowInsetsController insetsController = null;
            if (mWindowInsetsController != null) {
                insetsController = mWindowInsetsController;
            } else if (mView != null) {
                insetsController = mView.getWindowInsetsController();
            }
            if (insetsController != null) {
                final AtomicBoolean isImeInsetsControllable = new AtomicBoolean(false);
                final WindowInsetsController.OnControllableInsetsChangedListener listener =
                        (windowInsetsController, typeMask) -> isImeInsetsControllable.set(
                                (typeMask & WindowInsetsCompat.Type.IME) != 0);
                // Register the OnControllableInsetsChangedListener would synchronously
                // callback current controllable insets. Adding the listener here to check if
                // ime inset is controllable.
                insetsController.addOnControllableInsetsChangedListener(listener);
                if (!isImeInsetsControllable.get() && mView != null) {
                    final InputMethodManager imm = (InputMethodManager) mView.getContext()
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    // This is a backport when the app is in multi-windowing mode, it cannot
                    // control the ime insets. Use the InputMethodManager instead.
                    // TODO(b/280532442): Fix this in the platform side.
                    imm.hideSoftInputFromWindow(mView.getWindowToken(), 0);
                }
                insetsController.removeOnControllableInsetsChangedListener(listener);
                insetsController.hide(WindowInsets.Type.ime());
            } else {
                // Couldn't find an insets controller, fallback to old implementation
                super.hide();
            }
        }
    }
}