How to hide Android soft keyboard on EditText

I have an Activity with some EditText fields and some buttons as a convenience for what normally would be used to populate those fields. However when we the user touches one of the EditText fields the Android soft keyboard automatically appears. I want it to remain hidden by default, unless the user long presses the menu button. I have search for a solution to this and found several answers, but so far I can't get them to work.

I have tried the following:

1 - In the onCreate method,

this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

2 - Also in the onCreate method,

InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);

3 - and fIn the Manifest file,

<activity android:name=".activityName" android:windowSoftInputMode="stateAlwaysHidden"/>

None of these methods work. Whenever the user clicks on the EditText field, the soft keyboard appears. I only want the soft keyboard to appear if the user explicitly shows it by long pressing the menu key.

Why isn't this working?


This will help you

editText.setInputType(InputType.TYPE_NULL);

Edit:

To show soft keyboard, you have to write following code in long key press event of menu button

editText.setInputType(InputType.TYPE_CLASS_TEXT);
            editText.requestFocus();
            InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            mgr.showSoftInput(editText, InputMethodManager.SHOW_FORCED);

you need to add in manifest. Your manifest file would look like:

<activity
...
android:windowSoftInputMode="stateHidden|adjustResize"
...
>

I sometimes use a bit of a trick to do just that. I put an invisible focus holder somewhere on the top of the layout. It would be eg like this

 <EditText android:id="@id/editInvisibleFocusHolder"
          style="@style/InvisibleFocusHolder"/>

with this style

<style name="InvisibleFocusHolder">
    <item name="android:layout_width">0dp</item>
    <item name="android:layout_height">0dp</item>
    <item name="android:focusable">true</item>
    <item name="android:focusableInTouchMode">true</item>
    <item name="android:inputType">none</item>
</style>

and then in onResume I would call

    editInvisibleFocusHolder.setInputType(InputType.TYPE_NULL);
    editInvisibleFocusHolder.requestFocus();

That works nicely for me from 1.6 up to 4.x

链接地址: http://www.djcxy.com/p/16680.html

上一篇: 出现软键盘时如何调整布局

下一篇: 如何在EditText上隐藏Android软键盘