点击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<EditText> 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<EditText> cls = EditText.class;
            Method setSoftInputShownOnFocus;
            setSoftInputShownOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
            setSoftInputShownOnFocus.setAccessible(true);
            setSoftInputShownOnFocus.invoke(this, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小手追梦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值