点击textview获取焦点的同时不弹出软键盘

项目中需要实现点击TextView获取焦点但不弹出软键盘的需求:


要做两件工作:

1,进入Activity是TextView自动获取焦点时不弹出软键盘。这个需求比较简单,只要在AndroidManifest.xml配置文件注册Activity时如下红色配置:

<activity android:name=".Activity.MainActivity" android:windowSoftInputMode="stateHidden|stateAlwaysHidden"/>

如上配置之后,切换到某个activity时并不会弹出软键盘。但这样做还不够,这种情况下点击EditText不仅能获取焦点,还会弹出软件盘,如何才能即获取焦点又不弹出软键盘?

2,即获取焦点又不弹出软键盘。
   可以在监听TextView的各种事件的回调函数中添加如下代码:


((Activity)getContext()).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
try {
    Class cls = EditText.class;
    Method setSoftInputShownOnFocus;
    setSoftInputShownOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
    setSoftInputShownOnFocus.setAccessible(true);
    setSoftInputShownOnFocus.invoke(editText, false);
} catch (Exception e) {
    e.printStackTrace();
}

但是项目中有很多这样的EditText,每个都这么处理会出现大量的代码冗余。可以自定义继承自TextView的自定义View.如下面的
NoInputMethodPopEditText。

注意:一定要重写其构造方法。



public class NoInputMethodPopEditText extends EditText {
    public NoInputMethodPopEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        hideSoftKeyboard();
    }
    public NoInputMethodPopEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        hideSoftKeyboard();
    }
    public NoInputMethodPopEditText(Context context) {
        super(context);
        hideSoftKeyboard();
    }

    /**
     * 隐藏软键盘
     *
     */
    private  void hideSoftKeyboard(){
        ((Activity)getContext()).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        try {
            Class cls = EditText.class;
            Method setSoftInputShownOnFocus;
            setSoftInputShownOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
            setSoftInputShownOnFocus.setAccessible(true);
            setSoftInputShownOnFocus.invoke(this, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}



你可能感兴趣的:(java)