您的位置:首页 > 其它

工具类-虚拟键盘相关大全

2016-04-25 11:44 190 查看
工具类-虚拟键盘相关大全

1.监听输入隐藏及其高度。(可用于edittext被遮挡时候滑动调整的距离)

2.显示隐藏软键盘,强制显示软键盘

1.监听虚拟键盘隐藏及其高度

public static interface OnSoftKeyBoardVisibleListener{
void onSoftKeyBoardVisible(boolean isVisible,int displayHight,int hight);
}
/**监听软键盘状态
* @param activity
* @param listener
*/
public static void addOnSoftKeyBoardVisibleListener(Activity activity, final OnSoftKeyBoardVisibleListener listener) {
final View decorView = activity.getWindow().getDecorView();
decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
private boolean sLastVisiable;
@Override
public void onGlobalLayout() {
Rect rect = new Rect();
decorView.getWindowVisibleDisplayFrame(rect);
int displayHight = rect.bottom - rect.top;
int hight = decorView.getHeight();
boolean visible = (double) displayHight / hight < 0.8;

//                Log.d("rex", "DecorView display hight = " + displayHight);
//                Log.d("rex", "DecorView hight = " + hight);
//                Log.d("rex", "softkeyboard visible = " + visible);

if(visible != sLastVisiable){
listener.onSoftKeyBoardVisible(visible,displayHight,hight);
}
sLastVisiable = visible;
}
});


2.显示隐藏软键盘,强制显示软键盘

/**
* 隐藏软键盘
* @param activity
*/
public static void hideInput(Activity activity) {
View view = activity.getWindow().peekDecorView();
if (view != null) {
InputMethodManager inputmanger = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}

//强制显示或者关闭系统键盘
public static void KeyBoard(final EditText txtSearchKey,final String status)
{

Timer timer = new Timer();
timer.schedule(new TimerTask(){
@Override
public void run()
{
InputMethodManager m = (InputMethodManager)
txtSearchKey.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if(status.equals("open"))
{
m.showSoftInput(txtSearchKey,InputMethodManager.SHOW_FORCED);
}
else
{
m.hideSoftInputFromWindow(txtSearchKey.getWindowToken(), 0);
}
}
}, 300);
}

//显示虚拟键盘
public static void ShowKeyboard(View v)
{
InputMethodManager imm = ( InputMethodManager ) v.getContext( ).getSystemService( Context.INPUT_METHOD_SERVICE );

imm.showSoftInput(v,InputMethodManager.SHOW_FORCED);

}
//隐藏虚拟键盘
public static void HideKeyboard(View v)
{
InputMethodManager imm = ( InputMethodManager ) v.getContext( ).getSystemService( Context.INPUT_METHOD_SERVICE );
if ( imm.isActive( ) ) {
imm.hideSoftInputFromWindow( v.getApplicationWindowToken( ) , 0 );
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: