Search code examples
androidandroid-softkeyboardonfocussoft-keyboardonclicklistener

Issue with OnFocus and having softkeyboard hidden


I have been looking online for some time now to make sure there was not already one of these on here, but for some reason I cannot seem to find the exact way to make this work, and after 4 hours of trying I figured I would ask the experts.

I have my class right now that is suppose to have a onFocusChangeListener when the window is loaded that is suppose to trigger when I click my background causing the softkeyboard to be hidden.

So the short of the long is: how can I fix my class to listen for when I click my background and make my keyboard hidden.

Here is my code so far: (keep in mind I have made my layout both focusable and clickable)

package com.example.haymaker;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

public class addAppointment extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.appointment);
    final EditText appointmentName = (EditText) findViewById(R.id.editText1);

    appointmentName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
                InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(appointmentName.getWindowToken(), 0);

            }
        }
    });


    }

}

Thanks for your assistance


Solution

  • This is a little unusual, the android pattern is generally to let users close the keyboard using the back button.

    If you really want to close it when they touch outside of the edit text, you can add an onTouch listener(s) to your primary view and hide the keyboard:

    findViewById(R.id.you_main_view).setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent e){
            if (e.getAction() == MotionEvent.ACTION_UP) hideSoftKeyboard();
            return false;
        }
    }
    

    This is a little tricky because your containing view may not get to handle touches to subviews (like list views for example) that handle touches themselves. You may have to add a couple of similar touch listeners to different views to get the entire screen to register a hit. Make sure your touch listeners return false, or otherwise they will swallow clicks you expect to be handled elsewhere.