Show/Hide Soft Keyboard event in Fragment

前端 未结 2 876
予麋鹿
予麋鹿 2021-01-19 06:21

There are a lot of posts about finding a show/hide soft keyboard event. I find myself in a situation where I need to change an icon based on the soft key status, in a fragme

2条回答
  •  盖世英雄少女心
    2021-01-19 06:47

    Sadly but true - android do not have native on software keyboard show event.

    One the way handle fact that keyboard is hidden is to check entered symbols and back button press (for example textEdit will receive even back button) - but it is not flexible enough solution.

    Another the possible solutions is: Override onMeasure in activity and then notify observers (pattern Observer) - for example fragments. Fragment should subscribe and unsubscribe himself onPause onResume events. Something like that for activity code:

    private class DialogActivityLayout extends LinearLayout {
    
            public DialogActivityLayout(Context context, AttributeSet attributeSet) {
                super(context, attributeSet);
                LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                inflater.inflate(R.layout.activity_dialog, this);
            }
    
            @Override
            protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
                final int proposedHeight = MeasureSpec.getSize(heightMeasureSpec);
                final int actualHeight = getHeight();
    
                /* Layout loaded */
                if (actualHeight == 0 || proposedHeight == actualHeight) {
                    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
                    return;
                }
    
                if (proposedHeight > actualHeight) {
                    DialogActivity.this.onKeyboardHide();
                } else {
                    DialogActivity.this.onKeyboardShow();
                }
                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            }
        }
    

    I'm not sure but as I remember it works only for LinearLayout and of course activity should have adjustResize flag set (programmatically or in manifeset)

    Another (I thing better approach) is to as here with globalTree observer

    SoftKeyboard open and close listener in an activity in Android?

提交回复
热议问题