253

Possible Duplicate:
How do you close/hide the Android soft keyboard programmatically?

First thing first I already saw this thread. I tried the accepted methods given there, but nothing worked for me.

I have two screens in my app.

  • First one has 2 EditText - One for username and one for password
  • Second one have one ListView, and an EditText - to filter the listView

In my first screen, I want username EditText to have focus on startup and the Keyboard should be visible. This is my implementation (simplified by removing unnecessary/unrelated code).

#app_login.xml

<LinearLayout android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:paddingLeft="20dip"  
    android:paddingRight="20dip">

    <EditText android:id="@+id/username" 
        android:singleLine="true" 
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content" android:hint="Username"  
        android:imeOptions="actionDone" android:inputType="text"
        android:maxLines="1"/>

    <EditText android:id="@+id/password" 
        android:password="true" 
        android:singleLine="true"  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"    
        android:hint="Password" />
</LinearLayout>

#AppLogin.java

class AppLogin extends Activity{
    private EditText mUserNameEdit = null;
    private EditText mPasswordEdit = null;

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.app_login);
        
        mUserNameEdit  =    (EditText) findViewById(R.id.username);
        mPasswordEdit  =    (EditText) findViewById(R.id.password);

        /* code to show keyboard on startup.this code is not working.*/
        InputMethodManager imm =  (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(mUserNameEdit, InputMethodManager.SHOW_IMPLICIT);
    
    }//End of onCreate()
}

Well, the keyboard is not showing at startup. And my design badly requires a keyboard there.

Now on to second page. As I already mentioned, I have a listView and EditText there. I want my keyboard to be hidden on startup only to appear when the user touches the editText. Can you believe it? whatever I tried soft Keyboard is showing when I load the activity. I am not able to hide it.

#app_list_view.xml

<LinearLayout android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" >
    
   <EditText android:id="@+id/filter_edittext"       
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:hint="Search" android:inputType="text" 
        android:maxLines="1"/>
    <ListView android:id="@id/android:list" 
        android:layout_height="fill_parent"
        android:layout_weight="1.0" 
        android:layout_width="fill_parent" 
        android:focusable="true" 
        android:descendantFocusability="beforeDescendants"/>
</LinearLayout>     

#AppList.java

public class MyListActivity extends ListActivity{
   private EditText mfilterEditText;

    @Override
   public void onCreate(Bundle savedInstanceState) {        
      super.onCreate(savedInstanceState);
      setContentView(R.layout.app_list_view);

      mFilterEditText  =  (EditText) findViewById(R.id.filter_edittext);
      InputMethodManager imm = InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
      imm.hideSoftInputFromWindow(mFilterEditText.getWindowToken(), 0);
   }
}

To simplify

  1. On Login Page (first Page) I want my keyboard to be visible on startup.
  2. On SecondPage I want the keyboard to be hidden first, only to appear when the user touches editText

And my problem is I am getting the exact opposite on both occasions. Hope someone faced this issue before. BTW I am testing on the simulator and HTC Desire phone.

#FINAL OUTCOME

Well, I got it working, with the help of all my friends here.

1. To Show keyboard on startup

Two answers worked for me. One provided by @CapDroid, which is to use a handler and post it delayed..

mUserNameEdit.postDelayed(new Runnable() {
  @Override
  public void run() {
    // TODO Auto-generated method stub
    InputMethodManager keyboard = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    keyboard.showSoftInput(mUserNameEdit, 0);
  }
},50);

The second answer is provided by @Dyarish, In fact, he linked to another SOF thread, which I haven't seen before. But the funny thing is that this solution is given in the thread which I referenced at the start. And I haven't tried it out because it had zero votes in a thread where all other posts have plenty of votes. Height of foolishness.

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

For me, the second solution looked neat, so I decided to stick with it..But the first one certainly works. Also, @Dyarish's answer contains a clever hack of using a ScrollView below EditText to give EditText the focus. But I haven't tried it, but it should work. Not neat though.

2. To hide keyboard at activity start

Only one answer worked for me, which is provided by @Dyarish. And the solution is to use focusableInTouchMode settings in XML for the layout containing the EditTexts. This did the trick

<LinearLayout android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" 
    android:focusableInTouchMode="true">
    <EditText android:id="@+id/filter_edittext"       
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:hint="Search" android:inputType="text" 
        android:maxLines="1"/>
    <ListView android:id="@id/android:list" 
        android:layout_height="fill_parent"
        android:layout_weight="1.0" 
        android:layout_width="fill_parent" 
        android:focusable="true" 
        android:descendantFocusability="beforeDescendants"/>
</LinearLayout> 

Anyway, I end up using Dyarish's answer in both cases. So I am awarding the bounty to him. Thanks to all my other friends who tried to help me.

Yash Joshi
  • 382
  • 2
  • 18
Krishnabhadra
  • 33,632
  • 30
  • 110
  • 164
  • @user7777777777 I have edited my question...but not working...I tried with different flags instead of 0 too.. – Krishnabhadra Aug 26 '11 at 05:55
  • 1
    see my **new update** answer it is working myside... – Niranj Patel Aug 30 '11 at 05:29
  • The app_login.xml layout does not appear to be the full layout file. Please post the full layout. – Ronnie Aug 30 '11 at 06:14
  • 1
    **The app_login.xml layout does not appear to be the full layout file** Does that matter? – Krishnabhadra Aug 30 '11 at 06:20
  • 1
    Thanks! Glad it worked for you. =D – Dave Sep 02 '11 at 05:26
  • @krishnabhadra : it works! but I don't get the reason what does focusableintouchmode="true" imply? – Ashwin Jun 22 '12 at 14:53
  • possible your answer: http://stackoverflow.com/a/1109108/779408 – Bobs Jan 26 '13 at 06:06
  • postDelayed work perfect with me – Mohamd Ali Jan 06 '16 at 12:11
  • It can be easily show and hide with convenient methods but there is not an implemented way of catching when user choose to hide it. Due to this limitations I coded a simple snippet that I hope it will be useful. It is available [here](https://felhr85.net/2014/05/04/catch-soft-keyboard-showhidden-events-in-android/). It is pretty easy to use. – Iman Marashi Nov 27 '16 at 17:18
  • Need to play with InputMethodManager with the INPUT_METHOD_SERVICE to handle soft keyboard like https://readyandroid.wordpress.com/show-hide-android-soft-keyboard/ – Ready Android Aug 08 '18 at 07:26

4 Answers4

168

UPDATE 2

@Override
    protected void onResume() {
        super.onResume();
        mUserNameEdit.requestFocus();

        mUserNameEdit.postDelayed(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                InputMethodManager keyboard = (InputMethodManager)
                getSystemService(Context.INPUT_METHOD_SERVICE);
                keyboard.showSoftInput(mUserNameEdit, 0);
            }
        },200); //use 300 to make it run when coming back from lock screen
    }

I tried very hard and found out a solution ... whenever a new activity starts then keyboard cant open but we can use Runnable in onResume and it is working fine so please try this code and check...

UPDATE 1

add this line in your AppLogin.java

mUserNameEdit.requestFocus();

and this line in your AppList.java

listview.requestFocus()'

after this check your application if it is not working then add this line in your AndroidManifest.xml file

<activity android:name=".AppLogin" android:configChanges="keyboardHidden|orientation"></activity>
<activity android:name=".AppList" android:configChanges="keyboard|orientation"></activity>

ORIGINAL ANSWER

 InputMethodManager imm = (InputMethodManager)this.getSystemService(Service.INPUT_METHOD_SERVICE);

for hide keyboard

 imm.hideSoftInputFromWindow(ed.getWindowToken(), 0); 

for show keyboard

 imm.showSoftInput(ed, 0);

for focus on EditText

 ed.requestFocus();

where ed is EditText

Niranj Patel
  • 35,286
  • 11
  • 96
  • 128
136

Adding this to your code android:focusableInTouchMode="true" will make sure that your keypad doesn't appear on startup for your edittext box. You want to add this line to your linear layout that contains the EditTextBox. You should be able to play with this to solve both your problems. I have tested this. Simple solution.

ie: In your app_list_view.xml file

<LinearLayout 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" 
    android:focusableInTouchMode="true">
    <EditText 
        android:id="@+id/filter_edittext"       
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:hint="Search" 
        android:inputType="text" 
        android:maxLines="1"/>
    <ListView 
        android:id="@id/android:list" 
        android:layout_height="fill_parent"
        android:layout_weight="1.0" 
        android:layout_width="fill_parent" 
        android:focusable="true" 
        android:descendantFocusability="beforeDescendants"/>
</LinearLayout> 

------------------ EDIT: To Make keyboard appear on startup -----------------------

This is to make they Keyboard appear on the username edittextbox on startup. All I've done is added an empty Scrollview to the bottom of the .xml file, this puts the first edittext into focus and pops up the keyboard. I admit this is a hack, but I am assuming you just want this to work. I've tested it, and it works fine.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:paddingLeft="20dip"  
    android:paddingRight="20dip">
    <EditText 
        android:id="@+id/userName" 
        android:singleLine="true" 
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content" 
        android:hint="Username"  
        android:imeOptions="actionDone" 
        android:inputType="text"
        android:maxLines="1"
       />
    <EditText 
        android:id="@+id/password" 
        android:password="true" 
        android:singleLine="true"  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:hint="Password" />
    <ScrollView
        android:id="@+id/ScrollView01"  
        android:layout_height="fill_parent"   
        android:layout_width="fill_parent"> 
    </ScrollView>
</LinearLayout>

If you are looking for a more eloquent solution, I've found this question which might help you out, it is not as simple as the solution above but probably a better solution. I haven't tested it but it apparently works. I think it is similar to the solution you've tried which didn't work for you though.

Hope this is what you are looking for.

Cheers!

Community
  • 1
  • 1
Dave
  • 3,118
  • 4
  • 25
  • 44
  • Well Dyarish, Your solutions certainly hide the keyboard. Now let me play with this to show keyboard on startup – Krishnabhadra Sep 01 '11 at 03:28
  • Hey Krishnabhadra, I have two potential solutions that should work. The first is kind of a hack, but I've tested this with your code and it works. (I'll admit I don't know why, but it's likely due to properties of this view) I've edited my answer to reflect these solutions. Let me know if this works for you. Cheers. – Dave Sep 02 '11 at 00:42
  • Funnily enough, only the `ScrollView` solution worked, I tried the other "more eloquent" solutions and they did not. – EpicPandaForce Mar 19 '15 at 15:18
  • The Scroll View however makes the keyboard appear *only on first startup*, meaning that if you lock the screen then come back, then it will no longer be triggered. As such, I used the following http://stackoverflow.com/a/29229865/2413303 in order to programmatically call the keyboard (with delay, because otherwise it didn't work). – EpicPandaForce Mar 24 '15 at 10:29
56

Try this code.

For showing Softkeyboard:

InputMethodManager imm = (InputMethodManager)
                                 getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
        imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
    }

For Hiding SoftKeyboard -

InputMethodManager imm = (InputMethodManager)
                                  getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
        imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
    }
halfer
  • 18,701
  • 13
  • 79
  • 158
Lalit Poptani
  • 65,659
  • 21
  • 155
  • 238
  • 1
    Are you sure arguments to toggleSoftInput for showing keyboard is right? – Krishnabhadra Aug 26 '11 at 05:59
  • 1
    I asked because toggleSoftInput documentation tells first arguement is flag for showing and second argument is flag for hiding..You gave InputMethodManger.SHOW_IMPLICIT as the second argument..Thats why I asked? – Krishnabhadra Aug 26 '11 at 06:08
  • 1
    Anyway I tried both ways..nothing worked.. – Krishnabhadra Aug 26 '11 at 06:09
  • You can see the answer's that I gave regarding this in my profile it works in the same manner http://stackoverflow.com/questions/7187137/edittext-keyboard-is-dissappearing/7187321#7187321 – Lalit Poptani Aug 26 '11 at 06:13
  • Well I tried bothways..but nothing worked.. – Krishnabhadra Aug 26 '11 at 06:15
  • 2
    It has to be [imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);] to show so that [imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);] to work for hiding. – Aung Pyae Sep 05 '14 at 05:09
  • Thanks, works. As Aung Pyae said - make sure when you open keyboard to use toggleSoftInput so you can close it using the same method. If you open keyboard with showSoftInput then closing it with toggleSoftInput will not work. – Marko Niciforovic Sep 09 '14 at 09:21
  • This codes worked in every cases. Totally worked. Totally good. – Huy Tower Sep 09 '14 at 09:47
  • 1
    if you show the keyboard with your code, and then hide it by pressing back, your code won't work correctly anymore. – lenooh Jan 11 '18 at 12:38
9

Did you try InputMethodManager.SHOW_IMPLICIT in first window.

and for hiding in second window use InputMethodManager.HIDE_IMPLICIT_ONLY

EDIT :

If its still not working then probably you are putting it at the wrong place. Override onFinishInflate() and show/hide there.

@override
public void onFinishInflate() {
     /* code to show keyboard on startup */
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(mUserNameEdit, InputMethodManager.SHOW_IMPLICIT);
}
Ronnie
  • 23,807
  • 8
  • 52
  • 93