监听键盘显示或隐藏事件的android键盘、事件、android

2023-09-06 09:29:30 作者:夏恋 ∞

我想事件的键盘显示或隐藏时发生听。在Android是这可能吗?我不是想弄清楚如果键盘被显示或隐藏,当我开始我的活动,我想监听事件。

I am trying to listen for events that occurs when the keyboard is shown or hidden. Is this possible in Android? I am not trying to figure out if the keyboard is shown or hidden when I start my activity, I would like to listen for events.

推荐答案

尝试下面code: -

Try below code:-

// from the link above
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);


    // Checks whether a hardware keyboard is available
    if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) {
        Toast.makeText(this, "keyboard visible", Toast.LENGTH_SHORT).show();
    } else if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES) {
        Toast.makeText(this, "keyboard hidden", Toast.LENGTH_SHORT).show();
    }
}

boolean isOpened = false;

 public void setListnerToRootView(){
    final View activityRootView = getWindow().getDecorView().findViewById(android.R.id.content); 
    activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {

            int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
            if (heightDiff > 100 ) { // 99% of the time the height diff will be due to a keyboard.
                Toast.makeText(getApplicationContext(), "Gotcha!!! softKeyboardup", 0).show();

                if(isOpened == false){
                    //Do two things, make the view top visible and the editText smaller
                }
                isOpened = true;
            }else if(isOpened == true){
                Toast.makeText(getApplicationContext(), "softkeyborad Down!!!", 0).show();                  
                isOpened = false;
            }
         }
    });
}

低于code,你必须扩展的LinearLayout。

for below code you have to extend LinearLayout.

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    final int proposedheight = MeasureSpec.getSize(heightMeasureSpec);
    final int actualHeight = getHeight();

    if (actualHeight > proposedheight){
        // Keyboard is shown
    } else {
        // Keyboard is hidden
    }

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

见下面的链接: -

see below link:-

Howto捕捉虚拟键盘显示/隐藏事件的Andr​​oid?

 
精彩推荐
图片推荐