I want to stop keyboard from popping up in my android app. I wish to add this code
public void hideSoftKeyboard() {
if (getCurrentFocus() != null) {
InputMethodManager inputMethodManager = (InputMethodManager)
getSystemService(INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
0);
}
}
but I am not sure where to insert in my MainActivity.java
file
public class MainActivity extends AppCompatActivity {
Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.MyButton);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent myIntent = new Intent(MainActivity.this,
Main2Activity.class);
startActivity(myIntent);
}
});
}
}
为了避免键盘弹出,将其添加到onCreate()
方法中:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
If you want to dismiss the keyboard when users open MainActivity
, you should use this code in onStart
method.
@Override
protected void onStart() {
super.onStart();
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
}
For some cases to prevent keyboard from popping up when the MainActivity
goes from background to foreground, then you should use your method in onStop
method.
@Override
protected void onStop() {
super.onStop();
hideSoftKeyboard();
}
If you don't want the keyboard to show when your activity gets focus then you can add attributes in the manifest:
<activity android:windowSoftInputMode="stateAlwaysHidden" . . . >
This manipulates how the main window of the activity interacts with the window containing the on-screen soft keyboard. The setting for this attribute affects the state of the soft keyboard — whether it is hidden or visible — when the activity becomes the focus of user attention. You can use one of the following attribute depending on your requirement :
If you want to do it programatically then you can use your method in onCreate
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.