当键盘要弹出时,我需要进行回调。我必须做一些动作才能显示它。有可能吗?
答案 0 :(得分:2)
将此添加到需要KeyboardListener的视图中:
public class MyView extends View {
private boolean isKeyboardVisible = false;
private boolean hasFocus = false;
/**
* Screen ratio to determine keypad height.
*/
public static final double SCREEN_RATIO = 0.15;
public void setOnKeyboardListener(OnKeyboardListener onKeyboardListener) {
this.mOnKeyboardListener = onKeyboardListener;
}
private OnKeyboardListener mOnKeyboardListener;
public interface OnKeyboardListener {
void onKeyboardOpen();
void onKeyboardClosed();
}
public MyView(Context context) {
super(context);
getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect r = new Rect();
getWindowVisibleDisplayFrame(r);
int screenHeight = getRootView().getHeight();
int keypadHeight = screenHeight - r.bottom;
if (keypadHeight > screenHeight * SCREEN_RATIO) {
// keyboard got opened
isKeyboardVisible = true;
if (mOnKeyboardListener != null) {
mOnKeyboardListener.onKeyboardOpen();
}
} else if (hasFocus && isKeyboardVisible) {
// keyboard got closed
hasFocus = false;
isKeyboardVisible = false;
if (mOnKeyboardListener != null) {
mOnKeyboardListener.onKeyboardClosed();
}
} else {
// keyboard is closed
}
}
});
setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (!hasFocus) {
hasFocus = true;
isKeyboardVisible = false;
}
return false;
}
});
}
}
在您的活动中:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyView view = new MyView(getBaseContext());
view.setOnKeyboardListener(new MyView.OnKeyboardListener() {
@Override
public void onKeyboardOpen() {
}
@Override
public void onKeyboardClosed() {
}
});
}