android 对软键盘的显示和消失监听

1.首先在配置文件中添加
android:windowSoftInputMode="adjustResize"  意思是activity会根据软键盘的显示和消失始终调节布局的大小
2.
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);

        rl.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int heightDiff = rl.getRootView().getHeight() - rl.getHeight();
                if (heightDiff > dpToPx(MainActivity.this, 200)) { // if more than 200 dp, it's probably a keyboard...
                    // ... do something here
                    Log.d("TAG","aaaa");//显示
                }else {
                    Log.d("TAG","bbbb");//消失

                }
            }
        });
    }
//    COMPLEX_UNIT_DIP
    public static float dpToPx(Context context, float valueInDp) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDp, metrics);
    }
3.这时候进入程序会发现输入法会自动弹出,是应为exidtext自动获取了焦点,在父布局添加如下代码
android:focusable="true"
android:focusableInTouchMode="true"

4.现在就可以完美的监听软键盘的显示和消失了

你可能感兴趣的:(android 对软键盘的显示和消失监听)