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

前端 未结 16 1509
暗喜
暗喜 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 08:17

    If you want to handle show/hide of IMM (virtual) keyboard window from your Activity, you'll need to subclass your layout and override onMesure method(so that you can determine the measured width and the measured height of your layout). After that set subclassed layout as main view for your Activity by setContentView(). Now you'll be able to handle IMM show/hide window events. If this sounds complicated, it's not that really. Here's the code:

    main.xml

       
       
            
            

    Now inside your Activity declare subclass for your layout (main.xml)

        public class MainSearchLayout extends LinearLayout {
    
        public MainSearchLayout(Context context, AttributeSet attributeSet) {
            super(context, attributeSet);
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            inflater.inflate(R.layout.main, this);
        }
    
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            Log.d("Search Layout", "Handling Keyboard Window shown");
    
            final int proposedheight = MeasureSpec.getSize(heightMeasureSpec);
            final int actualHeight = getHeight();
    
            if (actualHeight > proposedheight){
                // Keyboard is shown
    
            } else {
                // Keyboard is hidden
            }
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }
    

    You can see from the code that we inflate layout for our Activity in subclass constructor

    inflater.inflate(R.layout.main, this);
    

    And now just set content view of subclassed layout for our Activity.

    public class MainActivity extends Activity {
    
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            MainSearchLayout searchLayout = new MainSearchLayout(this, null);
    
            setContentView(searchLayout);
        }
    
        // rest of the Activity code and subclassed layout...
    
    }
    

提交回复
热议问题