2

我试图捕捉从屏幕上移除键盘的事件,我正在使用以下代码:

    searchTextField.setOnEditorActionListener(new OnEditorActionListener()
    {
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
        {

            System.out.println("ACTION ID " + actionId);

            if(actionId == EditorInfo.IME_ACTION_DONE)
            {
                System.out.println("ACTION DONE!!!!!!!!!!");
                return true;
            }

            return false;
        }

   searchTextField.setOnFocusChangeListener( new View.OnFocusChangeListener()
    {
        public void onFocusChange(View v, boolean hasFocus) 
        {
              if (hasFocus)
                  System.out.println("HAS FOCUS");
              else
                  System.out.println("FOCUS LOST");
        }
    });

但不幸的是,它不起作用。onEditorAction只是从来没有打电话,无论我是开始编辑还是完成。关于onFocusChange方法,它只是在键盘启动时第一次调用。当键盘下降或第二次上升时,它不会被调用。谁能解释我做错了什么?

4

1 回答 1

1

我在活动 rootView 上使用 GlobalLayoutListener 来检查键盘是隐藏还是可见:

它的工作原理如下:

final View activityRootView = findViewById(R.id.activityRoot);
    activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
            if (heightDiff > 100) { // if more than 100 pixels, its probably a keyboard...
                ... do something here
            }
         }
    });
于 2013-03-04T14:34:23.430 回答