1.软键盘的使用
1.显示隐藏软键盘
获取系统服务类,让服务类来操作
private InputMethodManager utilInputMethodManager;
utilInputMethodManager = (InputMethodManager) MainActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
1.显示隐藏:
隐藏
utilInputMethodManager.hideSoftInputFromWindow(etTest.getWindowToken(),0);
显示
utilInputMethodManager.showSoftInput(etTest,0);
2.区别:
共同点:都是两个参数,都是editText 不同点:第一个是EditText,另一个是EditText.getWindowToken();
2.软键盘问题
1.软键盘遮挡键盘问题
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
3.软键盘封装类
键盘显示隐藏监听,键盘显示隐藏
public class UtilKeyboardStateObserver {
private static Activity activity;
private static final String TAG = UtilKeyboardStateObserver.class.getSimpleName();
public static UtilKeyboardStateObserver getKeyboardStateObserver(Activity activity) {
return new UtilKeyboardStateObserver(activity);
}
private static InputMethodManager utilInputMethodManager;
private View mChildOfContent;
private int usableHeightPrevious;
private OnKeyboardVisibilityListener listener;
public static void show(Activity activity, EditText et) {
utilInputMethodManager= (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
utilInputMethodManager.showSoftInput(et,0);
}
public static void hide(Activity activity, EditText et) {
utilInputMethodManager= (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
utilInputMethodManager.hideSoftInputFromWindow(et.getWindowToken(),0);
}
public void setKeyboardVisibilityListener(OnKeyboardVisibilityListener listener) {
this.listener = listener;
}
private UtilKeyboardStateObserver(Activity activity) {
FrameLayout content = (FrameLayout) activity.findViewById(android.R.id.content);
mChildOfContent = content.getChildAt(0);
mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
possiblyResizeChildOfContent();
}
});
}
private void possiblyResizeChildOfContent() {
int usableHeightNow = computeUsableHeight();
if (usableHeightNow != usableHeightPrevious) {
int usableHeightSansKeyboard = mChildOfContent.getRootView().getHeight();
int heightDifference = usableHeightSansKeyboard - usableHeightNow;
if (heightDifference > (usableHeightSansKeyboard / 4)) {
if (listener != null) {
listener.onKeyboardShow();
}
} else {
if (listener != null) {
listener.onKeyboardHide();
}
}
usableHeightPrevious = usableHeightNow;
Log.d(TAG,"usableHeightNow: " + usableHeightNow + " | usableHeightSansKeyboard:" + usableHeightSansKeyboard + " | heightDifference:" + heightDifference);
}
}
private int computeUsableHeight() {
Rect r = new Rect();
mChildOfContent.getWindowVisibleDisplayFrame(r);
Log.d(TAG,"rec bottom>" + r.bottom + " | rec top>" + r.top);
return (r.bottom - r.top);
}
public interface OnKeyboardVisibilityListener {
void onKeyboardShow();
void onKeyboardHide();
}
}
|