how to auto hide keyboard after entering a maximum length of text in editText in android?

StackOverflow https://stackoverflow.com/questions/21901386

  •  14-10-2022
  •  | 
  •  

문제

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

도움이 되었습니까?

해결책

use this one in onTextChanged()

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

다른 팁

    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);
    }
 }
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top