Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save gurpreet-/4122033d49da08c211926d1a1a23cf98 to your computer and use it in GitHub Desktop.
Save gurpreet-/4122033d49da08c211926d1a1a23cf98 to your computer and use it in GitHub Desktop.
Detect when the Android soft keyboard is shown or hidden
/*
* Copyright (c) Terl Tech Ltd • 29/06/18 14:03 • goterl.com
*
* 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.
*/
/**
* This file shows how to use RxJava/RxAndroid to
* detect when the keyboard is opened or closed.
* The source code here can also be used in an Activity. This
* is certainly by no means the only way you can do this, there's
* also a method involving attaching a global view tree observer.
* The following code is inspired by a few answers in the thread
* https://stackoverflow.com/q/4745988/3526705.
*/
public class SomeFragment extends Fragment {
// Subscribe to this from anywhere.
private PublishSubject<Boolean> publishKeyBoardOpen = PublishSubject.create();
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
// First get the bottom of the window
final int defBottom = getBottomOfWindow();
// Setup a loop that detects when the
// bottom changes
Disposable keyBoardIntervalDisposable =
Observable.interval(1000, 100, TimeUnit.MILLISECONDS)
.observeOn(Schedulers.io())
.subscribe(aLong -> {
// On every 100 milliseconds, get the bottom
// of the window again. If it's changed
// then the keyboard has most likely pushed
// the bottom of the view up.
int newBottom = getBottomOfWindow();
publishKeyBoardOpen.onNext(defBottom != newBottom);
});
// Now, we can subscribe to the PublishSubject
// and receive changes
Disposable keyboardDetector = publishKeyBoardOpen
.distinctUntilChanged()
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(isOpen -> {
if (isOpen) {
onKeyBoardOpen();
} else {
onKeyBoardClosed();
}
});
}
public int getBottomOfWindow() {
Rect rect = new Rect();
Window window = getActivity().getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(rect);
return rect.bottom;
}
@Override
public void onDestroy() {
super.onDestroy();
// Remember to dispose of all the Disposables here!
// You may need to use CompositeDisposable for this.
// Or put all the Disposables into fields and call
// .dispose() on each of them.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment