项目需求,亲测可用。
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
}
}
}
});
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);
}