Skip to content
Advertisement

How to come out of EditText when clicked on empty space?

I made an app which gives a dialog when an EditText loses focus. However, the editText doesn’t lose focus even when the keyboard is closed. I want that the editText should lose focus when the keyboard is closed (using the back button) or when we click on empty space (empty space being LinearLayout.) How can I do that?

Advertisement

Answer

This method enables you to hide the cursor and hide the keyboard when Clicking anywhere on the layout and when clicking the back button :

  protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText.setFocusable(false);

            findViewById(R.id.layout).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

            editText.setInputType(InputType.TYPE_NULL);

            View view = this.getCurrentFocus();
                if (view != null) {

                InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                assert imm != null;
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);

                }
            }
        });
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement