Tap outside edittext to lose focus

后端 未结 9 1691
萌比男神i
萌比男神i 2020-12-24 02:02

I just want when click outside the \"edittext\" to automatically lose focus and hide keyboard. At the moment, if I click on the \"edittext\" it focuses but i need to hit the

9条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-24 02:47

    I had the same requirement as I had to hide the keyboard once I touch anywhere outside my EditText box. The setOnFocusChangeListener does not do the job as even if you touch outside the edit text box is still selected.

    For this I used the solution edc598 here.

    • I first got the MainLayout containing the whole view and add touch listener to it.
    • When onTouch event was triggered I check if the EditText box has focus.
    • If the EditText box has focus then I check the event's X-Y co-ordinates.
    • Based on the placement of my EditText box I hide the key board if touched anywhere outside the box

    Code sample modified from here:

    LinearLayout MainLayout = (LinearLayout) findViewById(R.id.MainLayout);
    EditText textBox        = (EditText) findViewById(R.id.textBox);   
    int X_TOP_LEFT      = 157;
    int Y_TOP_LEFT      = 388;
    int X_BOTTOM_RIGHT  = 473;
    int Y_BOTTOM_RIGHT  = 570;   
    MainLayout.setOnTouchListener(new View.OnTouchListener() {
    
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
            if(textBox.isFocused()){
    
                Log.i("Focussed", "--" + event.getX() + " : " + event.getY() + "--");
    
                if(event.getX() <= 157 || event.getY() <= 388 || event.getX() >= 473 || event.getY() >= 569){
                    //Will only enter this if the EditText already has focus
                    //And if a touch event happens outside of the EditText
                    textBox.clearFocus();
                    InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                    //Do something else
                }
            }
            Log.i("X-Y coordinate", "--" + event.getX() + " : " + event.getY() + "--");
        //Toast.makeText(getBaseContext(), "Clicked", Toast.LENGTH_SHORT).show();
            return false;
        }
    });
    

提交回复
热议问题