Android的EditText如何禁止弹出输入法并且光标正常闪烁

日常开发中我们经常会有这种需求,就是希望不弹出安卓自带的输入法,那么搜索出来的结果经常是用InputType.TYPE_NULL这个方法,

如下代码:

    public void hideInput(EditText editText) {
        editText.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                editText.setInputType(InputType.TYPE_NULL);
                return false;
            }
        });
    }

这个代码它能不能用呢?它可以用,简单,粗暴。但是它会导致,光标没办法闪烁。因此我们需要对他它进行改造。

首先,给EditText 在XML进行声明,让他可以闪烁并且获取焦点,

代码如下:具体属性得作用我就不细说了,可以百度下 。直接贴代码就可以用。

        <EditText
            android:focusable="true"
            android:focusableInTouchMode="true"
            android:cursorVisible="true"
            android:textCursorDrawable="@null"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

然后就是实际关闭的代码了

    public void hideSoftInput(EditText editText) {
        if (android.os.Build.VERSION.SDK_INT <= 10) {
            editText.setInputType(InputType.TYPE_NULL);
        } else {
            Class<EditText> cls = EditText.class;
            Method method;
            try {
                getWindow().setSoftInputMode(
                        WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
                method = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
                method.setAccessible(true);
                method.invoke(editText, false);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

就这么简单,完了。


posted @ 2022-02-22 16:45  _Vincent  阅读(477)  评论(0编辑  收藏  举报