您的位置:首页 > 移动开发 > Android开发

Android监听软键盘弹出与收起

2015-12-22 22:47 429 查看
项目需求,亲测可用。

1. 在EditText的父控件加上

android:focusable="true"
android:focusableInTouchMode="true"


2. 设置初始化标志位,免得其他调用干扰

editText = (EditText) view.findViewById(R.id.editText);
editText.setOnFocusChangeListener(new View.OnFocusChangeListener()
{
public void onFocusChange(View v, boolean hasFocus)
{
if (hasFocus)
{
init = true;
}
}
});


3.  监听界面调整事件

rootLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener()
{
public void onGlobalLayout()
{
if (init)
{
if (isKeyboardShown(editText.getRootView()))
{
// Do something when keyboard is shown
}
else
{
// Do something when keyboard is hidden
}
}
}
});


4. 判断事件

private boolean isKeyboardShown(View rootView)
{
final int SOFT_KEYBOARD_HEIGHT_DP_THRESHOLD = 128;

Rect r = new Rect();
rootView.getWindowVisibleDisplayFrame(r);
int heightDiff = rootView.getBottom() - r.bottom;

return heightDiff > ViewUtils.dpToPixel(SOFT_KEYBOARD_HEIGHT_DP_THRESHOLD);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: