Android does not natively provide a good way to listen to a soft keyboard, but when we actually apply it, there are many places where we need to optimize the UI for a soft keyboard.
The following is a good way to sort out, you can use.
However, it is important to note that, since the use of viewtreeobserver to monitor, so each layout has changed, will trigger, so listner inside if there is a way to change the layout, you should be careful not to get into the infinite trigger loop, At this point you need to add some tag value to circumvent, this can refer to the code comment
public class Softkeyboardutil {public static final String TAG = "Softkeyboardutil"; public static void Observesoftkeyboard (activity activity, final Onsoftkeyboardchangelistener listener) {final View Decorview = Activity.getwindow (). Getdecorview (); Decorview.getviewtreeobserver (). Addongloballayoutlistener (New Viewtreeobserver.ongloballayoutlistener () {@Over Ride public void Ongloballayout () {rect rect = new Rect (); Decorview.getwindowvisibledisplayframe (rect); int displayheight = Rect.bottom-rect.top; int height = decorview.getheight (); Boolean hide = (double) displayheight/height > 0.8; if (log.isloggable (tag, log.debug)) {LOG.D (tag, "decorview Display hight =" + displayheight); LOG.D (TAG, "decorview hight =" + height); LOG.D (TAG, "softkeyboard visible =" +!hide); } Listener.onsoftkeyboardchange (Height-displayheight,!hide); } }); }/** * note:if you change layout in this method, maybe this method would repeat because the Viewtreeobserver.onglo Ballayoutlistener would repeat so maybe you need does some handle (Ex:add some flag to avoid repeat) in this callback * * Example: * * private int previousheight =-1; private void Setupkeyboardlayoutwhenedit () {Softkeyboardutil.observesoftkeyboard (this, new Onsoftkeyboardchangelistener () {* * @Override public void onsoftkeyboardchange (int softkeybardheight, Boolean VI sible) {if (previousheight = = softkeybardheight) {return;} previousheight = Softkeybardheight;//code for Change layout } }); } * * */public interface Onsoftkeyboardchangelistener {void Onsoftkeyboardchange (int soft Keybardheight, Boolean visible); }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Android Soft keyboard monitor (monitor height, whether or not to display)