Android 禁止 EditText 弹出软件盘

Android About 1,859 words

禁止弹出

21版本后有方法mEditText.setShowSoftInputOnFocus(false); 可以设置不显示

21版本之前采用反射的方式获取方法名,然后调用

public void hideSoftInputMethod(Activity a, EditText editText) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        mDigitsLayout.mEditText.setShowSoftInputOnFocus(false);
        return;
    }

    a.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    int currentVersion = Build.VERSION.SDK_INT;
    String methodName = null;
    if (currentVersion >= Build.VERSION_CODES.JELLY_BEAN) {// 4.2
        methodName = "setShowSoftInputOnFocus";
    } else if (currentVersion >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {// 4.0
        methodName = "setSoftInputShownOnFocus";
    }
    if (methodName == null) {
        editText.setInputType(InputType.TYPE_NULL);
    } else {
        Class<EditText> cls = EditText.class;
        Method setShowSoftInputOnFocus;
        try {
            setShowSoftInputOnFocus = cls.getMethod(methodName, boolean.class);
            setShowSoftInputOnFocus.setAccessible(true);
            setShowSoftInputOnFocus.invoke(editText, false);
        } catch (NoSuchMethodException e) {
            editText.setInputType(InputType.TYPE_NULL);
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

不自动弹出

使EditText进入界面默认不跳出软键盘(不获得焦点)

EditText的父控件设置属性:

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

点击其他区域收回软键盘

点击EditText区域外让EditText失去焦点

给父布局设置触摸监听,设置focusabletrue,设置focusable的触摸模式为true,最后请求焦点

mLinearLayout.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        mLinearLayout.setFocusable(true);
        mLinearLayout.setFocusableInTouchMode(true);
        mLinearLayout.requestFocus();
        return false;
    }
});
Views: 5,887 · Posted: 2019-04-09

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh