How to automatically hide the keyboard after entering the maximum text length in editText in android?

New for Android In an application using editText its maximum text length is 2 Here is my question
After entering two characters in editText (ie) when editText reaches the maximum text length, shuold automatically hides the soft keyboard
Can anyone tell me how to do this, and is it possible?
I got some stack overflow answers like this

InputMethodManager inputManager = 
        (InputMethodManager) context.
            getSystemService(Context.INPUT_METHOD_SERVICE); 
inputManager.hideSoftInputFromWindow(
        this.getCurrentFocus().getWindowToken(),
        InputMethodManager.HIDE_NOT_ALWAYS); 

is that enough? or do I want to do some extra stuff in coding? Thanks

+3
source share
3 answers

use this in onTextChanged ()

   {
       InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
       imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);
}
+3
source
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(yourEditText.getWindowToken(), 0);
+2

, edittext. , . Textwatcher .

     // replace R.id.editText1 with your edittext id
    final EditText myEditText = (EditText) findViewById(R.id.editText1);
    final int maxTextLength = 2;//max length of your text

    InputFilter[] filterArray = new InputFilter[1];
    filterArray[0] = new InputFilter.LengthFilter(maxTextLength);
    myEditText.setFilters(filterArray);

    myEditText.addTextChangedListener(new TextWatcher(){


   @Override
   public void afterTextChanged(Editable arg0) {
    }

   @Override
   public void beforeTextChanged(CharSequence s, int start, int count, int after) {

   }

   @Override
   public void onTextChanged(CharSequence txtWatcherStr, int start, int before, int count){
       if(count==maxTextLength ){
           InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
           imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);
    }
 }
});
+1
source

All Articles