EditText聚焦时如何弹出带+ - * / ( ) =键的全数字软键盘
Android EditText 调出带运算符号软键盘实现方案
你需要的包含+ - * / ( )按键的计算器样式软键盘,有两种实现路径:
方案1:系统输入类型适配(实现简单,适配依赖输入法)
直接在XML布局中给EditText添加对应属性即可,大部分主流输入法会自动适配调出带对应符号的数值键盘:
<EditText android:id="@+id/calculate_input" android:layout_width="match_parent" android:layout_height="wrap_content" <!-- 配置输入类型为数值类,优先调出数字键盘 --> android:inputType="numberDecimal|numberSigned" <!-- 限制允许输入的字符,输入法会自动过滤无关按键 --> android:digits="0123456789.+-*/()" />
注意:不同厂商的系统输入法、第三方输入法对该属性的适配逻辑不同,无法100%保证所有设备都能显示你需要的全部运算符号。
方案2:自定义软键盘(完全可控,全设备一致)
如果需要保证所有设备都显示完全符合要求的键盘布局,直接自定义软键盘是最稳妥的方案,核心步骤如下:
- 在
res/xml目录下新建键盘布局文件calc_keyboard.xml,自定义你需要的按键布局、按键对应的字符编码:
<?xml version="1.0" encoding="utf-8"?> <Keyboard xmlns:android="http://schemas.android.com/apk/res/android" android:keyWidth="20%p" android:keyHeight="56dp" android:horizontalGap="1dp" android:verticalGap="1dp"> <!-- 第一行:1 2 3 + - --> <Row> <Key android:codes="49" android:keyLabel="1"/> <Key android:codes="50" android:keyLabel="2"/> <Key android:codes="51" android:keyLabel="3"/> <Key android:codes="43" android:keyLabel="+"/> <Key android:codes="45" android:keyLabel="-"/> </Row> <!-- 第二行:4 5 6 * / --> <Row> <Key android:codes="52" android:keyLabel="4"/> <Key android:codes="53" android:keyLabel="5"/> <Key android:codes="54" android:keyLabel="6"/> <Key android:codes="42" android:keyLabel="*"/> <Key android:codes="47" android:keyLabel="/"/> </Row> <!-- 第三行:7 8 9 ( ) --> <Row> <Key android:codes="55" android:keyLabel="7"/> <Key android:codes="56" android:keyLabel="8"/> <Key android:codes="57" android:keyLabel="9"/> <Key android:codes="40" android:keyLabel="("/> <Key android:codes="41" android:keyLabel=")"/> </Row> <!-- 第四行:0 . 删除 --> <Row> <Key android:codes="48" android:keyLabel="0" android:keyWidth="40%p"/> <Key android:codes="46" android:keyLabel="."/> <Key android:codes="-5" android:keyLabel="删除" android:keyWidth="40%p"/> </Row> </Keyboard>
- 在你的布局文件中添加
KeyboardView组件,默认设置为GONE隐藏状态 - 给EditText设置焦点监听:当EditText获得焦点时,隐藏系统默认软键盘,加载自定义的键盘布局并显示自定义KeyboardView;监听按键点击事件,将对应字符写入EditText即可。
内容的提问来源于stack exchange,提问作者Padmaja Seshadri
相关产品推荐
相关产品推荐

