android 键盘弹起 UI上移

private ViewTreeObserver.OnGlobalLayoutListener mLayoutChangeListener;
private boolean mIsSoftKeyboardShowing = false;

@Override
public void onCreate(Bundle saveBundleInstance){
    super.onCreate(saveBundleInstance);
    setContentView(R.layout.login_activity);

    mLayoutChangeListener = new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            //判断窗口可见区域大小
            Rect r = new Rect();
            getWindow().getDecorView().getWindowVisibleDisplayFrame(r);

            Point point = new Point();
            getWindowManager().getDefaultDisplay().getSize(point);
            final int screenHeight = point.y;

            //如果屏幕高度和Window可见区域高度差值大于整个屏幕高度的1/3,则表示软键盘显示中,否则软键盘为隐藏状态
            int heightDifference = screenHeight - r.bottom;

            Log.i(TAG, "the keyboard height is " + heightDifference);

            boolean isKeyboardUp = heightDifference > (screenHeight - r.top)/3;
            if (isKeyboardUp && ! mIsSoftKeyboardShowing){
                Log.i(TAG, "keyboard up");
                mIsSoftKeyboardShowing = true;
                adjustLayoutDependKeyboard(true, heightDifference);
            }else if(!isKeyboardUp && mIsSoftKeyboardShowing){
                Log.i(TAG, "keyboard down");
                mIsSoftKeyboardShowing = false;
                adjustLayoutDependKeyboard(false, heightDifference);
            }
        }
    };

    //设置一个监听,用于捕获键盘的弹出
    getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(mLayoutChangeListener);
}

/**
 * 设置中间布局
 * @param isVisible
 * @param keyboardHeight
 */
void adjustLayoutDependKeyboard(boolean isVisible, int keyboardHeight){
    LinearLayout middleLayout = (LinearLayout) findViewById(R.id.middle_layout);
    FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) middleLayout.getLayoutParams();
    if (isVisible){
        params.gravity = Gravity.BOTTOM;
        params.bottomMargin = 10+keyboardHeight;
    }else{
        params.gravity = Gravity.CENTER;
        params.bottomMargin = 0;
    }

    middleLayout.setLayoutParams(params);
}

@Override
public void onDestroy(){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN){
        getWindow().getDecorView().getViewTreeObserver().removeOnGlobalLayoutListener(mLayoutChangeListener);
    }else{
        getWindow().getDecorView().getViewTreeObserver().removeGlobalOnLayoutListener(mLayoutChangeListener);
    }
    super.onDestroy();

}

参考文献:http://blog.csdn.net/ccpat/article/details/46730771

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值