对于安卓的软键盘的显示隐藏,查了好多资料,得出一个结论,就是Google并没有提供接口来直接判断键盘是否是显示状态。
刚好项目中遇到这个问题,目前解决了,就贡献出来给Androider。
我的思路是通过重写父布局来监听布局变化,然后判断可视区域来判定软件盘是否是显示状态
废话不多说,直接上代码,代码中解释,没几行,目前测试没问题
通过重写布局的
onMeasure方法来确定当前布局是否有变化。有变化的话去判断可视区域,继而得出软键盘当前是否是显示状态
代码如下:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if ((isKeyboardShown(this))) {
//在这做你要做的操作
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
下面这个方法是用来判断当前键盘是否显示
private boolean isKeyboardShown(View rootView) {
//自己确定键盘的高度,自己可修改
final int softKeyboardHeight = 100;
Rect r = new Rect();
rootView.getWindowVisibleDisplayFrame(r);
DisplayMetrics dm = rootView.getResources().getDisplayMetrics();
int heightDiff = rootView.getBottom() - r.bottom;
return heightDiff > softKeyboardHeight * dm.density;
}
好了,代码就这么多,下面贴上完整代码
/**
* Created by onlykk on 2016/9/5.
*/
public class IgoneKeybordFrameLayout extends FrameLayout {
public IgoneKeybordFrameLayout(Context context) {
super(context);
}
public IgoneKeybordFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public IgoneKeybordFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (isKeyboardShown(this)) {
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
private boolean isKeyboardShown(View rootView) {
final int softKeyboardHeight = 100;
Rect r = new Rect();
rootView.getWindowVisibleDisplayFrame(r);
DisplayMetrics dm = rootView.getResources().getDisplayMetrics();
int heightDiff = rootView.getBottom() - r.bottom;
return heightDiff > softKeyboardHeight * dm.density;
}
}