How do I detect if software keyboard is visible on Android Device or not?

前端 未结 30 1430
情书的邮戳
情书的邮戳 2020-11-22 10:59

Is there a way in Android to detect if the software (a.k.a. \"soft\") keyboard is visible on screen?

30条回答
  •  心在旅途
    2020-11-22 11:32

    I used this as a basis: http://www.ninthavenue.com.au/how-to-check-if-the-software-keyboard-is-shown-in-android

    /**
    * To capture the result of IMM hide/show soft keyboard
    */
    public class IMMResult extends ResultReceiver {
         public int result = -1;
         public IMMResult() {
             super(null);
    }
    
    @Override 
    public void onReceiveResult(int r, Bundle data) {
        result = r;
    }
    
    // poll result value for up to 500 milliseconds
    public int getResult() {
        try {
            int sleep = 0;
            while (result == -1 && sleep < 500) {
                Thread.sleep(100);
                sleep += 100;
            }
        } catch (InterruptedException e) {
            Log.e("IMMResult", e.getMessage());
        }
        return result;
    }
    }
    

    Then wrote this method:

    public boolean isSoftKeyboardShown(InputMethodManager imm, View v) {
    
        IMMResult result = new IMMResult();
        int res;
    
        imm.showSoftInput(v, 0, result);
    
        // if keyboard doesn't change, handle the keypress
        res = result.getResult();
        if (res == InputMethodManager.RESULT_UNCHANGED_SHOWN ||
                res == InputMethodManager.RESULT_UNCHANGED_HIDDEN) {
    
            return true;
        }
        else
            return false;
    
    }
    

    You may then use this to test all fields (EditText, AutoCompleteTextView, etc) that may have opened a softkeyboard:

        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        if(isSoftKeyboardShown(imm, editText1) | isSoftKeyboardShown(imm, autocompletetextview1))
            //close the softkeyboard
            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
    

    Addmittely not an ideal solution, but it gets the job done.

提交回复
热议问题