怎么让软键盘弹出时,部分控件上移

之前写注册页面的时候,UI同学给我提了个意见,让弹出软键盘时候,左上角的标题“注册”不动,中间内容往上移动,效果这样
怎么让软键盘弹出时,部分控件上移
怎么让软键盘弹出时,部分控件上移
经过查阅资料和多方实践,解决方法如下

1、先要设置页面软键盘模式,这样每次软键盘弹出后布局高度会减少软键盘的高度

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN
                | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

2、找出内容view,在每次布局为软键盘弹出减小高度时监听,改变内容view

mVContent = findViewById(android.R.id.content);

ViewTreeObserver.OnGlobalLayoutListener mLsnrLayout =
            new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout () {

                    Rect rect = new Rect();
                    mVContent.getWindowVisibleDisplayFrame(rect);
                    int height = rect.height();

                    boolean isImmShow = height < UcApp.sHeightPx;
                    if ( isImmShow != mIsImmShow ) {
                        mIsImmShow = isImmShow;

                        mUbtnCommit.setVisibility(isImmShow ? View.INVISIBLE : View.VISIBLE);
                    }
                }
            };

mVContent.getViewTreeObserver().addOnGlobalLayoutListener(mLsnrLayout);

XML格式是这样的,标题我是在基类上设置加上的
怎么让软键盘弹出时,部分控件上移

    <!--注册布局-->
    <android.support.constraint.ConstraintLayout
        android:id="@+id/cl_register"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:visibility="visible">
public void setTitle (String txt) {

    if ( null == mTvTitle ) {

        mTvTitle = new TextView(UcApp.sCtx);
        ((FrameLayout) getWindow().getDecorView()).addView(mTvTitle);
        ViewUtils.inst(mTvTitle)
                .setMargins(119, 54, 0, 0)
                .setTextSize(42);
        mTvTitle.setTypeface(Typeface.DEFAULT_BOLD);
        mTvTitle.setTextColor(ComUtils.getClr(R.color.white_f2f2f2_60));
    }

    mTvTitle.setText(txt);
}

就是设置了margin

因为内容布局是竖直居中的,标题是margin写死的,所以布局高度变了以后内容移动标题不动。

希望这篇文章能帮助大家,大佬勿喷~

猜你喜欢

转载自blog.51cto.com/14311106/2392521