How to prevent focus on Activity start
本问题已经有最佳答案,请猛点这里访问。
我有一个只有一个
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | @Override protected void onResume() { super.onResume(); new Handler().postDelayed(new Runnable() { @Override public void run() { InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE); //Find the currently focused view, so we can grab the correct window token from it. //If no view currently has focus, create a new one, just so we can grab a window token from it imm.hideSoftInputFromWindow(etBarcode.getWindowToken(), 0); } }, 500); } |
它隐藏了它(很快就出现了)。
是否有
更新
1 2 | // Add following code in activity onCreate this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); |
问题非常复杂,因为它是关于获得焦点的视图,以及所有布局如何处理它,关于触摸模式是可聚焦的,以及最后但并非最不重要的软键盘处理方式。
但这对我有用:
在清单中:
1 | android:windowSoftInputMode="stateHidden|stateAlwaysHidden" |
在布局中:
1 2 | android:focusable="true" android:focusableInTouchMode="true" |
最后但并非最不重要的是,触摸侦听器设置为EditText以防止软键盘在触摸后显示:
1 2 3 4 5 6 7 8 9 10 | mMyText.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // forward the touch event to the view (for instance edit text will update the cursor to the touched position), then // prevent the soft keyboard from popping up and consume the event v.onTouchEvent(event); disableSoftKeyboard(MyActivity.this); return true; } }); |
而这种方法或多或少地做了你正在做的事情:
1 2 3 4 5 6 7 8 9 | public void disableSoftKeyboard(@NonNull Activity activity) { View view = activity.getCurrentFocus(); if (view != null) { InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } else { activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); } } |
希望它有所帮助,而且我没有忘记任何事情:)
您可以设置Layout的属性
1 2 | android:descendantFocusability="beforeDescendants" android:focusableInTouchMode="true" |
对于父布局