Edittext在项目十分常见,当用到搜索功能时,进入搜索页面需要自动弹出软键盘,点击搜索,就要将软键盘关闭,这里就是我的软键盘工具类,实现的2个功能:
1.软键盘的打开与关闭
2.判断当前软键盘是否打开
import android.app.Activity;
import android.content.Context;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import java.util.Timer;
import java.util.TimerTask;
public class KeybordUtil {
/**
* 自动弹软键盘
*
* @param context
* @param et
*/
public static void showSoftInput(final Context context, final EditText et) {
new Timer().schedule(new TimerTask() {
@Override
public void run() {
((Activity) context).runOnUiThread(new Runnable() {
@Override
public void run() {
et.setFocusable(true);
et.setFocusableInTouchMode(true);
//请求获得焦点
et.requestFocus();
//调用系统输入法
InputMethodManager inputManager = (InputMethodManager) et
.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(et, 0);
}
});
}
}, 200);
}
/**
* 自动关闭软键盘
* @param activity
*/
public static void closeKeybord(Activity activity) {
InputMethodManager imm = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null) {
imm.hideSoftInputFromWindow(activity.getWindow().getDecorView().getWindowToken(), 0);
}
}
/**
* 打开关闭相互切换
* @param activity
*/
public static void hideKeyboard(Activity activity) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isActive()) {
if (activity.getCurrentFocus().getWindowToken() != null) {
imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
}