Android之控件保持在软键盘上面
16lz
2021-01-26
本文主要记录一些零碎的东西
软件盘弹出时,底部的控件在软键盘上面,即随着软键盘弹出而向上移动
activity非全屏时,使用RelativeLayout + ScrollView 可以很简单的实现,简单演示一下
<?xml version="1.0" encoding="utf-8"?>
可是全屏时失效了 avtivity全屏:
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
想法是监听到软键盘的弹出与消失,然后测量出软键盘的高度,底部需要移动的布局再做移动动画
Google API 有 https://developer.android.com/guide/topics/resources/runtime-changes.html#HandlingTheChange,监听配置变更,不过好像 然并卵。
思路还是想着监听软键盘的弹出与消失,查了一圈,发现SDK 不能提供任何有效的解决方案,只能换一个思路
不直接监听软键盘的事件,当软键盘显示变化时,会触发当前布局中View的全局布局变化。通过监听全局布局的变化就可以得知软键盘的状态使用ViewTreeObserver类,它是一个View视图树的观察者类。
想测量出软键盘的高度,需要用到View中提供的一个方法getWindowVisibleDisplayFrame(),此方法会返回该view所附着的窗口的可见区域大小。当软键盘显示时,窗口的可见区域大小会被压缩,当软键盘隐藏时,窗口的可见区域大小会还原。
先看看实现的效果:
private void showInputManager(EditText editText) { editText.setFocusable(true); editText.setFocusableInTouchMode(true); editText.requestFocus(); /** 目前测试来看,还是挺准的 * 原理:OnGlobalLayoutListener 每次布局变化时都会调用 * 界面view 显示消失都会调用,软键盘显示与消失时都调用 * */ mRootView.getViewTreeObserver().addOnGlobalLayoutListener(mLayoutChangeListener); InputMethodManager inputManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT); } ViewTreeObserver.OnGlobalLayoutListener mLayoutChangeListener = new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { //判断窗口可见区域大小 Rect r = new Rect(); // getWindowVisibleDisplayFrame()会返回窗口的可见区域高度 getWindow().getDecorView().getWindowVisibleDisplayFrame(r); //如果屏幕高度和Window可见区域高度差值大于整个屏幕高度的1/3,则表示软键盘显示中,否则软键盘为隐藏状态。 int heightDifference = WT.mScreenHeight - (r.bottom - r.top); boolean isKeyboardShowing = heightDifference > WT.mScreenHeight / 3; if(isKeyboardShowing){// D.i("slack","show..."+ r.bottom + " - " + r.top + " = " + (r.bottom - r.top) +","+ heightDifference); // bottomView 需要跟随软键盘移动的布局 // setDuration(0) 默认300, 设置 0 ,表示动画执行时间为0,没有过程,只有动画结果了 bottomView.animate().translationY(-heightDifference).setDuration(0).start(); }else{// D.i("slack","hide..."); bottomView.animate().translationY(0).start(); } } };
更多相关文章
- Android(安卓)布局单位转换
- android inflater的用法
- Android(安卓)WebView加载页面的输入框被软键盘遮挡的问题
- Android仿饿了么搜索功能
- Android(安卓)launcher3布局和结构
- 浅谈Android中常用的五种布局方式
- 用Eclipse编译android程序时,出现警告This text field does not
- Android入门:4种布局
- android自定义XML布局属性