Hiding keyboard after calling new Activity that shows a ProgressDialog

Venator85 picture Venator85 · May 3, 2012 · Viewed 14k times · Source

I'm having trouble with the on screen keyboard. I have an activity with an EditText which shows the keyboard, and a button to go to a second activity. The second activity shows a ProgressDialog on its onCreate(), does stuff, and dismisses the ProgressDialog. The problem is that while the ProgressDialog is displayed, so is the keyboard.

I would like the keyboard to disappear before creating the ProgressDialog. I searched thorougly both StackOverflow and other sites, but nothing seems to work with this particular scenario.

I'm attaching two pics for your reference:

This is the code of the first activity:

public class FirstActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
                startActivity(intent);
            }
        });
    }
}

and this is the code of the second activity:

public class SecondActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second);

        // TODO: hide keyboard here

        final ProgressDialog dialog = ProgressDialog.show(this, "", "Please wait...", true, false, null);

        // in real code, here there is an AsyncTask doing stuff...
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                dialog.dismiss();
            }
        }, 5000);
    }
}

Thanks

Answer

Venator85 picture Venator85 · May 3, 2012

Solved using a variation of the technique posted by phalt:

InputMethodManager im = (InputMethodManager) this.getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

This code works correctly during onCreate/onStart/onResume, since doesn't rely on a focused view to get the window token from.