Question

Am new to android
In a app am using editText its maximun text length is 2
Here my question
After entering two characters in editText (i.e) when editText reaching the maximum text length it shuold automatically hide the soft keyboard
Can any one say how to do that and is it possible?
I got some answers in stack overflow like this

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

IS it enough ? or i want to do any extra things in coding ? Thanks

Was it helpful?

Solution

use this one in onTextChanged()

   {
       InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
       imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);
}

OTHER TIPS

    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(yourEditText.getWindowToken(), 0);

You actually need to listen when the text of edittext being changed. Then you may hide the keyboard when text reached to a specific length.You may use Textwatcher like this.

     // 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);
    }
 }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top