Computer/Android

android softkeyboard capture

알찬돌삐 2015. 1. 13. 10:31

안드로이드에서 소프트키보드가 오픈될 경우 이 이벤트를 캡쳐하지 못해서.

현재 윈도우의 최대 높이와 해당 액티비티의 최대 높이를 계산해서 차이나는 높이를 가지고 소프트키보드가 열려있는지 아닌지 확인하는 소스.


출처 : http://stackoverflow.com/questions/4312319/howto-capture-the-virtual-keyboard-show-hide-event-in-android


boolean isOpened = false;

 public void setListenerToRootView(){
    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;
            }
         }
    });
}