EditText和软键盘的暧昧

当进入有EditText的页面中,默认EditText会获取焦点,此时可能就会有需求提出,请在进入页面时,弹出软键盘。关于这个问题,实现方法有很多,简直就是条条大路通罗马。借本文梳理下EditText和软件盘的设置的知识点。

1、对于上述的需求曲线解决办法(糊弄测试人员)。在进入页面中不让EditText获取到焦点,只有在触摸输入框时获取到焦点后,才弹出软键盘。实现原理是让EditText的父布局获取到焦点。xml代码如下设置:

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:orientation="vertical">
        <EditText
            android:id="@+id/edt"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="please input " />
    </LinearLayout>

2、实现上述需求的最便捷的两种方法。在清单文件中进行如下设置

      <activity android:name=".MainActivity"
            android:windowSoftInputMode="adjustResize"
            >    </activity>

或者

      <activity android:name=".MainActivity"
           android:windowSoftInputMode="adjustPan|stateAlwaysVisible"
            >    </activity>

adjustresize 属性设置后软键盘会将整体的布局向上推,不会让其遮挡布局底部的控件,adjustpan属性则不会。

3、在代码中实现上述需求。

   getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);

new Handler(getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.showSoftInput(search_name, InputMethodManager.SHOW_FORCED);
            }
        }, 200);               

4、最后献上软键盘的隐藏和显示的两种方法,有助你在代码中灵活的设置来应对各种需求。

InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(
        Context.INPUT_METHOD_SERVICE);
inputMethodManager.showSoftInput(edt, InputMethodManager.SHOW_FORCED);//edt为EditText控件

InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edt.getWindowToken(), 0);//edt为EditText控件
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

凯哥666

谢谢老板鼓励

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

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

打赏作者

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

抵扣说明:

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

余额充值