Edittext在項(xiàng)目十分常見(jiàn),當(dāng)用到搜索功能時(shí),進(jìn)入搜索頁(yè)面需要自動(dòng)彈出軟鍵盤,點(diǎn)擊搜索,就要將軟鍵盤關(guān)閉,這里就是我的軟鍵盤工具類,實(shí)現(xiàn)的2個(gè)功能:
1.軟鍵盤的打開(kāi)與關(guān)閉
2.判斷當(dāng)前軟鍵盤是否打開(kāi)
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 {
/**
* 自動(dòng)彈軟鍵盤
*
* @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);
//請(qǐng)求獲得焦點(diǎn)
et.requestFocus();
//調(diào)用系統(tǒng)輸入法
InputMethodManager inputManager = (InputMethodManager) et
.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(et, 0);
}
});
}
}, 200);
}
/**
* 自動(dòng)關(guān)閉軟鍵盤
* @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);
}
}
/**
* 打開(kāi)關(guān)閉相互切換
* @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);
}
}
}
}