当我们弹出一个Dialog时候,如果这个Dialog需要输入数据,然后确定后又需要关闭输入法,一般系统的hide,跟show方法总会有各种问题,最霸道的解决方法就是写一个定时器,定时弹出或者关闭输入法。
import java.util.Timer; import java.util.TimerTask; import android.content.Context; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; public class InputTools { //隐藏虚拟键盘 public static void HideKeyboard(View v) { InputMethodManager imm = ( InputMethodManager ) v.getContext( ).getSystemService( Context.INPUT_METHOD_SERVICE ); if ( imm.isActive( ) ) { imm.hideSoftInputFromWindow( v.getApplicationWindowToken( ) , 0 ); } } //显示虚拟键盘 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 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 TimerHideKeyboard(final View v) { Timer timer = new Timer(); timer.schedule(new TimerTask(){ @Override public void run() { InputMethodManager imm = ( InputMethodManager ) v.getContext( ).getSystemService( Context.INPUT_METHOD_SERVICE ); if ( imm.isActive( ) ) { imm.hideSoftInputFromWindow( v.getApplicationWindowToken( ) , 0 ); } } }, 10); } //输入法是否显示着 public static boolean KeyBoard(EditText edittext) { boolean bool = false; InputMethodManager imm = ( InputMethodManager ) edittext.getContext( ).getSystemService( Context.INPUT_METHOD_SERVICE ); if ( imm.isActive( ) ) { bool = true; } return bool; } }