如何防止专注于 Activity 启动

How to prevent focus on Activity start

我有一个 Activity,只有一个 EdtiText。当 Activity 启动时,EditText 获得焦点并显示软键盘。这似乎发生在 onResume 之后,因为当我以编程方式在 onResume 中隐藏键盘时它不起作用。当我这样做时:

@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);
}

它隐藏它(在弹出后不久)。

EditText 上是否有我可以用来防止键盘弹出的事件?或者其他一些防止它显示的方法?

Update focusableInTouchMode 没有做我想要的,因为当设置为 true 时键盘弹出,当设置为 false它根本无法聚焦。

父布局android:focusableInTouchMode="true"

// Add following code in activity onCreate
        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

您可以像

一样设置 属性 布局
android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true"

问题非常复杂,因为它是关于视图获得焦点的,以及它是如何被所有布局处理的,关于触摸模式是可聚焦的,最后但并非最不重要的是关于软键盘如何处理它。 但这对我有用:

清单中:

android:windowSoftInputMode="stateHidden|stateAlwaysHidden"

布局中:

android:focusable="true"
android:focusableInTouchMode="true"

最后但同样重要的是,将触摸侦听器设置为 EditText 以防止软键盘在触摸后显示:

        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;
        }
    });

而该方法或多或少做了您已经在做的事情:

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);
    }
}

希望对您有所帮助,而且我没有忘记任何事情:)