android开发:获取键盘的高度(实测真实有效)

android开发:获取键盘的高度(实测真实有效)

由于最近在做即时通讯,做类似于微信的点击键盘消失,弹出表情页面(表情页面的高度和键盘的高度一致),于是在网上看了好多android测键盘高度的代码,都多多少少有些问题,于是我自己进行重新编写,终于弄了一个比较ok的测量高度的代码。

public class Addfd extends Activity {
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.addfd);
            final Context context = getApplicationContext();
            final LinearLayout parentLayout = findViewById(R.id.parent);
            final View myLayout = getWindow().getDecorView();
            parentLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                private int statusBarHeight;

                @Override
                public void onGlobalLayout() {
                    Rect r = new Rect();  // 使用最外层布局填充,进行测算计算  
                    parentLayout.getWindowVisibleDisplayFrame(r);
                    int screenHeight = myLayout.getRootView().getHeight();
                    int heightDiff = screenHeight - (r.bottom - r.top);
                    if (heightDiff > 100) {  // 如果超过100个像素,它可能是一个键盘。获取状态栏的高度  
                        statusBarHeight = 0;
                    }
                    try {
                        Class c = Class.forName("com.android.internal.R$dimen");
                        Object obj = c.newInstance();
                        Field field = c.getField("status_bar_height");
                        int x = Integer.parseInt(field.get(obj).toString());
                        statusBarHeight = context.getResources().getDimensionPixelSize(x);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    int realKeyboardHeight = heightDiff - statusBarHeight;
                    Log.e("键盘", "keyboard height(单位像素) = " + realKeyboardHeight);
                }
            });
        }
    }

这是布局代码


    

        

            
        
    

 

你可能感兴趣的:(屏幕适配,技术总结)