13

I have an EditText that I am passing focus to programmatically. But when I do, I want the keyboard to show up as well (and then go down when that EditText lose focus). Right now, the user has to click on the EditText to get the keyboard to show up -- even thought the EditText already has focus.

Cote Mounyo
  • 13,817
  • 23
  • 66
  • 87

5 Answers5

23
<activity   android:name=".YourActivity"
            android:windowSoftInputMode="stateVisible" />

Add this to manifest file...

Looking Forward
  • 3,579
  • 8
  • 45
  • 65
20

This is how I show the ketyboard:

EditText yourEditText= (EditText) findViewById(R.id.yourEditText);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(yourEditText, InputMethodManager.SHOW_IMPLICIT);
Waza_Be
  • 39,407
  • 49
  • 186
  • 260
7

set this for your activity in your manifest to pop keyboard automatically when your screen comes containing EditText box

<activity android:windowSoftInputMode="stateAlwaysVisible" ... />

To hide keyboard on losing focus set a OnFocusChangeListener for the EditText .

In the onCreate()

EditText editText = (EditText) findViewById(R.id.textbox);
OnFocusChangeListener ofcListener = new MyFocusChangeListener();
editText.setOnFocusChangeListener(ofcListener);

Add this class

private class MyFocusChangeListener implements OnFocusChangeListener {

    public void onFocusChange(View v, boolean hasFocus){

        if(v.getId() == R.id.textbox && !hasFocus) {

            InputMethodManager imm =  (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

        }
    }
}
jad
  • 493
  • 3
  • 16
6

To show the keyboard, use the following code.

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT);

To hide the keyboard,, use the code below. et is the reference to the EditText

InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
Rohit
  • 261
  • 3
  • 9
0

In order to do it based on focus listener you should go for:

final InputMethodManager imm =(InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
editText.setOnFocusChangeListener(new OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if(hasFocus){
                imm.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT);
            }else{
                 imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
            }
            imm.toggleSoftInput(0, 0);
        }
    });

Hope this helps.

Regards!

Martin Cazares
  • 13,637
  • 10
  • 47
  • 54