How to capture the “virtual keyboard show/hide” event in Android?

前端 未结 16 1410
暗喜
暗喜 2020-11-22 07:23

I would like to alter the layout based on whether the virtual keyboard is shown or not. I\'ve searched the API and various blogs but can\'t seem to find anything useful.

16条回答
  •  梦如初夏
    2020-11-22 08:02

    Based on the Code from Nebojsa Tomcic I've developed the following RelativeLayout-Subclass:

    import java.util.ArrayList;
    
    import android.content.Context;
    import android.util.AttributeSet;
    import android.widget.RelativeLayout;
    
    public class KeyboardDetectorRelativeLayout extends RelativeLayout {
    
        public interface IKeyboardChanged {
            void onKeyboardShown();
            void onKeyboardHidden();
        }
    
        private ArrayList keyboardListener = new ArrayList();
    
        public KeyboardDetectorRelativeLayout(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }
    
        public KeyboardDetectorRelativeLayout(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public KeyboardDetectorRelativeLayout(Context context) {
            super(context);
        }
    
        public void addKeyboardStateChangedListener(IKeyboardChanged listener) {
            keyboardListener.add(listener);
        }
    
        public void removeKeyboardStateChangedListener(IKeyboardChanged listener) {
            keyboardListener.remove(listener);
        }
    
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            final int proposedheight = MeasureSpec.getSize(heightMeasureSpec);
            final int actualHeight = getHeight();
    
            if (actualHeight > proposedheight) {
                notifyKeyboardShown();
            } else if (actualHeight < proposedheight) {
                notifyKeyboardHidden();
            }
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    
        private void notifyKeyboardHidden() {
            for (IKeyboardChanged listener : keyboardListener) {
                listener.onKeyboardHidden();
            }
        }
    
        private void notifyKeyboardShown() {
            for (IKeyboardChanged listener : keyboardListener) {
                listener.onKeyboardShown();
            }
        }
    
    }
    

    This works quite fine... Mark, that this solution will just work when Soft Input Mode of your Activity is set to "WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE"

提交回复
热议问题