Android: 设置状态栏透明EditText被软键盘遮挡

847 阅读1分钟

项目集成环信,将其状态栏设置为透明,出现的问题就是当EditText获取到焦点没有随着软键盘上移被它遮挡住了,参考此文解决了问题Android沉浸式状态栏与EditText问题

在Activity的onCreate方法中的setContentView后面加上如下代码:

private View viewContent;
private int usableHeightPrevious;
private ViewGroup.LayoutParams frameLayoutParams;

@Override
protected void onCreate(Bundle arg0) {
    super.onCreate(arg0);
    setContentView(R.layout.activity_chat);

    viewContent = findViewById(android.R.id.content);
    if (viewContent != null) {
        viewContent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            public void onGlobalLayout() {
                possiblyResizeChildOfContent();
            }
        });
        frameLayoutParams = viewContent.getLayoutParams();
    }
}

/**
 * 如果两次高度不一致,将计算的可视高度设置成视图的高度
 */
private void possiblyResizeChildOfContent() {
    //计算视图可视高度
    Rect r = new Rect();
    viewContent.getWindowVisibleDisplayFrame(r);
    int usableHeightNow = r.bottom;

    if (usableHeightNow != usableHeightPrevious) {
        frameLayoutParams.height = usableHeightNow;
        viewContent.requestLayout();//请求重新布局
        usableHeightPrevious = usableHeightNow;
    }
}