import android
.app
.Activity
;
import android
.content
.Context
;
import android
.graphics
.Rect
;
import android
.view
.View
;
import android
.view
.ViewTreeObserver
;
import android
.view
.inputmethod
.InputMethodManager
;
import android
.widget
.EditText
;
public class KeyBoardUtils {
int screenHeight6
;
View rootView
;
Activity mContext
;
int virtualKeyboardHeight
;
int screenHeight
;
public static void toggleKeybord(EditText mEditText
, Context mContext
)
{
InputMethodManager imm
= (InputMethodManager
) mContext
.getSystemService(Context
.INPUT_METHOD_SERVICE
);
imm
.toggleSoftInput(0,InputMethodManager
.HIDE_NOT_ALWAYS
);
}
public static void openKeybord(EditText mEditText
, Context mContext
)
{
InputMethodManager imm
= (InputMethodManager
) mContext
.getSystemService(Context
.INPUT_METHOD_SERVICE
);
imm
.showSoftInput(mEditText
, InputMethodManager
.SHOW_FORCED
);
}
public static void closeKeybord(EditText mEditText
, Context mContext
)
{
InputMethodManager imm
= (InputMethodManager
) mContext
.getSystemService(Context
.INPUT_METHOD_SERVICE
);
imm
.hideSoftInputFromWindow(mEditText
.getWindowToken(), 0);
}
public KeyBoardUtils(Activity context
) {
this.mContext
= context
;
screenHeight
= mContext
.getResources().getDisplayMetrics().heightPixels
;
screenHeight6
= screenHeight
/ 6;
rootView
= mContext
.getWindow().getDecorView();
}
public void setOnKeyboardChangeListener(final KeyboardChangeListener listener
) {
rootView
.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
rootView
.post(new Runnable() {
@Override
public void run() {
Rect rect
= new Rect();
rootView
.getWindowVisibleDisplayFrame(rect
);
int heightDifference
= screenHeight
- rect
.bottom
;
if (heightDifference
< screenHeight6
) {
virtualKeyboardHeight
= heightDifference
;
if (listener
!= null
) {
listener
.onKeyboardHide();
}
} else {
if (listener
!= null
) {
listener
.onKeyboardShow(heightDifference
- virtualKeyboardHeight
);
}
}
}
});
}
});
}
public interface KeyboardChangeListener {
void onKeyboardShow(int keyboardHight
);
void onKeyboardHide();
}
}
转载请注明原文地址:https://tech.qufami.com/read-8257.html