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

前端 未结 16 1210
暗喜
暗喜 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:20

    Nebojsa's solution almost worked for me. When I clicked inside a multi-line EditText it knew the keyboard was displayed, but when I started typing inside the EditText, the actualHeight and proposedHeight were still the same so it did not know they keyboard was still displayed. I made a slight modification to store the max height and it works fine. Here is the revised subclass:

    public class CheckinLayout extends RelativeLayout {
    
        private int largestHeight;
    
        public CheckinLayout(Context context, AttributeSet attributeSet) {
            super(context, attributeSet);
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            inflater.inflate(R.layout.checkin, this);
        }
    
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            final int proposedheight = MeasureSpec.getSize(heightMeasureSpec);
            largestHeight = Math.max(largestHeight, getHeight());
    
            if (largestHeight > proposedheight)
                // Keyboard is shown
            else
                // Keyboard is hidden
    
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }
    

提交回复
热议问题