How to hide Android soft keyboard on EditText

前端 未结 16 1137
长发绾君心
长发绾君心 2020-11-27 14:38

I have an Activity with some EditText fields and some buttons as a convenience for what normally would be used to populate those fields. However when we the user touches on

16条回答
  •  没有蜡笔的小新
    2020-11-27 14:54

    Hello Use this code it is working 100% for me

    EditText ee=new EditText(this);
    ee.setShowSoftInputOnFocus(false);
    

    *But you want to just hide keyboard on edittext click given below code will work but keyboard icon and upward sign of back-button will create *Given code is like this

            EditText ee=new EditText(this);//create edittext
            final   View.OnTouchListener disable =new View.OnTouchListener() {
            public boolean onTouch (View v, MotionEvent event) {
            v.onTouchEvent(event);
            InputMethodManager img = 
            (InputMethodManager)v.getContext().getSystemService(INPUT_METHOD_SERVICE);
            if (img != null) {
            img.hideSoftInputFromWindow(v.getWindowToken(),0);
            }
            return true;
            }
            };
            //call touch listener
           ee.setOnTouchListener(disable);
    

    Use also it in case of text-changing listener

            EditText ee= new EditText(this);
            Text=new TextWatcher(){
    
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int 
            after) {
            InputMethodManager img = (InputMethodManager) 
            getSystemService(INPUT_METHOD_SERVICE);
            img.hideSoftInputFromWindow(ee.getWindowToken(), 0);
    
            }
    
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
    
            InputMethodManager img = (InputMethodManager) 
            getSystemService(INPUT_METHOD_SERVICE);
            img.hideSoftInputFromWindow(ee.getWindowToken(), 0);
    
            }
           @Override
            public void afterTextChanged(Editable s) {
            InputMethodManager img = (InputMethodManager) 
            getSystemService(INPUT_METHOD_SERVICE);
            img.hideSoftInputFromWindow(ee.getWindowToken(), 0);
    
            }
            };
           ee.addTextChangedListener(Text);
    

    Use it also in case of onclick listener

     EditText ee=new EditText(this);
     ee.setOnClickListener(new View.OnClickListener() {
     public void onClick(View v) {
    
     InputMethodManager img= (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
     img.hideSoftInputFromWindow(ee.getWindowToken(),0);
    
     }});
    

    All the code will work but for me first code is best

提交回复
热议问题