How to capture the “virtual keyboard show/hide” event in Android?

前端 未结 16 1383
暗喜
暗喜 2020-11-22 07:23

I would like to alter the layout based on whether the virtual keyboard is shown or not. I\'ve searched the API and various blogs but can\'t seem to find anything useful.

16条回答
  •  温柔的废话
    2020-11-22 07:57

    Not sure if anyone post this. Found this solution simple to use!. The SoftKeyboard class is on gist.github.com. But while keyboard popup/hide event callback we need a handler to properly do things on UI:

    /*
    Somewhere else in your code
    */
    RelativeLayout mainLayout = findViewById(R.layout.main_layout); // You must use your root layout
    InputMethodManager im = (InputMethodManager) getSystemService(Service.INPUT_METHOD_SERVICE);
    
    /*
    Instantiate and pass a callback
    */
    SoftKeyboard softKeyboard;
    softKeyboard = new SoftKeyboard(mainLayout, im);
    softKeyboard.setSoftKeyboardCallback(new SoftKeyboard.SoftKeyboardChanged()
    {
    
        @Override
        public void onSoftKeyboardHide() 
        {
            // Code here
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        // Code here will run in UI thread
                        ...
                    }
                });
        }
    
        @Override
        public void onSoftKeyboardShow() 
        {
            // Code here
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        // Code here will run in UI thread
                        ...
                    }
                });
    
        }   
    });
    

提交回复
热议问题