Reference: http://toughcoder.net/blog/2015/10/09/android-trick-detect-soft-keyboard-show-slash-hide/
1 PackageXiamai.testidea;2 3 Importandroid.app.Activity;4 ImportAndroid.graphics.Rect;5 ImportAndroid.os.Bundle;6 ImportAndroid.util.DisplayMetrics;7 ImportAndroid.view.View;8 ImportAndroid.view.ViewGroup;9 ImportAndroid.view.ViewTreeObserver;Ten One /** A * Created by Administrator on 2016/6/15. - */ - Public classBaseactivityextendsActivity the { - PrivateOnkeyboardlistener KeyboardListener; - Private BooleanKeyboardvisible =false; - PrivateViewtreeobserver.ongloballayoutlistener Globallayoutlistener =NewViewtreeobserver.ongloballayoutlistener () + { - @Override + Public voidongloballayout () A { at if(Keyboardisvisible (Getrootview ())) - { - if(!keyboardvisible) - { -Keyboardvisible =true; - keyboardlistener.onkeyboardshow (); in } - } to Else + { - if(keyboardvisible) the { *Keyboardvisible =false; $ Keyboardlistener.onkeyboardhidden ();Panax Notoginseng } - } the } + }; A the PublicView Getrootview () + { - return((ViewGroup) Findviewbyid (Android. r.id.content)). Getchildat (0); $ } $ - protected voidSetonkeyboardlistener (Onkeyboardlistener keyboardlistener) - { the This. KeyboardListener =KeyboardListener; - Getrootview (). Getviewtreeobserver (). Addongloballayoutlistener (Globallayoutlistener);Wuyi } the - Private Booleankeyboardisvisible (View rootview) Wu { - Final intSoftkeyboardheight = 100; AboutRect r =NewRect (); $ Rootview.getwindowvisibledisplayframe (r); -Displaymetrics DM =rootview.getresources (). Getdisplaymetrics (); - intHeightdiff = Rootview.getbottom ()-R.bottom; - returnHeightdiff > Softkeyboardheight *dm.density; A } + the Public InterfaceOnkeyboardlistener - { $ voidonkeyboardshow (); the voidOnkeyboardhidden (); the } the}
View Code
1 PackageXiamai.testidea;2 3 ImportAndroid.os.Bundle;4 ImportAndroid.util.Log;5 6 /**7 * Created by Administrator on 2016/7/11.8 */9 Public classKeyboardtestactivityextendsbaseactivityTen ImplementsBaseactivity.onkeyboardlistener One { A @Override - protected voidonCreate (Bundle savedinstancestate) - { the Super. OnCreate (savedinstancestate); - Setcontentview (r.layout.root_activity); -Setonkeyboardlistener ( This); - } + - @Override + Public voidonkeyboardshow () A { atLOG.E ("KeyboardEvent", "Keyboard Open"); - } - - @Override - Public voidOnkeyboardhidden () - { inLOG.E ("KeyboardEvent", "Keyboard Off"); - } to}
View Code
Android Monitor soft keyboard to be closed and open