You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android:限制EditText仅输入数字与句点,如何调出对应键盘?

实现EditText仅允许输入数字和句点(适配IP地址输入)

下面提供两种实用方案,既可以让键盘仅显示数字和句点,又能严格限制IP地址的格式:

方案1:系统键盘+输入过滤器(推荐)

通过指定EditText的输入类型和允许字符,再配合输入过滤器限制IP格式,是最省心的实现方式。

布局配置

在XML布局中给EditText设置输入类型和允许的字符:

<EditText
    android:id="@+id/et_ip"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="numberDecimal"
    android:digits="0123456789." />
  • android:inputType="numberDecimal":调出带小数点的数字键盘
  • android:digits="0123456789.":强制EditText仅接受数字和句点输入

代码添加格式校验

为了符合IP地址的规范(最多3个句点、每段数字0-255),添加输入过滤器:

Java代码

EditText etIp = findViewById(R.id.et_ip);
etIp.setFilters(new InputFilter[]{new InputFilter() {
    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        // 统计已输入的句点数量,最多允许3个
        int dotCount = 0;
        for (int i = 0; i < dest.length(); i++) {
            if (dest.charAt(i) == '.') dotCount++;
        }
        if (source.equals(".") && dotCount >= 3) {
            return ""; // 超过3个句点,拦截输入
        }

        // 校验每段数字不超过255
        if (dstart > 0) {
            int prevDotIndex = dest.toString().lastIndexOf('.', dstart - 1);
            String currentSegment = dest.toString().substring(prevDotIndex + 1, dstart) + source;
            if (!currentSegment.isEmpty()) {
                try {
                    int num = Integer.parseInt(currentSegment);
                    if (num > 255) return ""; // 超过255则拦截
                } catch (NumberFormatException e) {
                    return "";
                }
            }
        }
        return null; // 允许输入
    }
}});

Kotlin代码

val etIp = findViewById<EditText>(R.id.et_ip)
etIp.filters = arrayOf(InputFilter { source, _, _, dest, dstart, _ ->
    val dotCount = dest.count { it == '.' }
    if (source == "." && dotCount >= 3) {
        return@InputFilter ""
    }

    if (dstart > 0) {
        val prevDotIndex = dest.toString().lastIndexOf('.', dstart - 1)
        val currentSegment = dest.toString().substring(prevDotIndex + 1, dstart) + source
        currentSegment.toIntOrNull()?.takeIf { it > 255 }?.let {
            return@InputFilter ""
        }
    }
    null
})

方案2:自定义IP键盘(按需使用)

如果需要完全控制键盘的样式和按键,可以自定义仅包含数字和句点的键盘:

1. 创建键盘布局文件

在res/layout/下新建custom_ip_keyboard.xml:

<?xml version="1.0" encoding="utf-8"?>
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
    android:keyWidth="33%p"
    android:keyHeight="60dp"
    android:horizontalGap="1dp"
    android:verticalGap="1dp">

    <Row>
        <Key android:codes="49" android:keyLabel="1" />
        <Key android:codes="50" android:keyLabel="2" />
        <Key android:codes="51" android:keyLabel="3" />
    </Row>
    <Row>
        <Key android:codes="52" android:keyLabel="4" />
        <Key android:codes="53" android:keyLabel="5" />
        <Key android:codes="54" android:keyLabel="6" />
    </Row>
    <Row>
        <Key android:codes="55" android:keyLabel="7" />
        <Key android:codes="56" android:keyLabel="8" />
        <Key android:codes="57" android:keyLabel="9" />
    </Row>
    <Row>
        <Key android:codes="46" android:keyLabel="." />
        <Key android:codes="48" android:keyLabel="0" />
        <Key android:codes="-5" android:keyLabel="删除" />
    </Row>
</Keyboard>

2. 绑定键盘到EditText

Java代码

EditText etIp = findViewById(R.id.et_ip);
Keyboard customKeyboard = new Keyboard(this, R.layout.custom_ip_keyboard);

// 隐藏系统键盘
etIp.setInputType(InputType.TYPE_NULL);
// 点击EditText时显示自定义键盘
etIp.setOnTouchListener((v, event) -> {
    if (!customKeyboard.isShown()) {
        customKeyboard.show();
    }
    return true;
});

// 处理键盘按键事件
customKeyboard.setOnKeyboardActionListener(new Keyboard.OnKeyboardActionListener() {
    @Override
    public void onKey(int primaryCode, int[] keyCodes) {
        Editable editable = etIp.getText();
        int cursorPos = etIp.getSelectionStart();
        if (primaryCode == -5) { // 处理删除键
            if (editable != null && cursorPos > 0) {
                editable.delete(cursorPos - 1, cursorPos);
            }
        } else { // 插入数字或句点
            editable.insert(cursorPos, Character.toString((char) primaryCode));
        }
    }

    // 实现其他空方法
    @Override public void onPress(int primaryCode) {}
    @Override public void onRelease(int primaryCode) {}
    @Override public void onText(CharSequence text) {}
    @Override public void swipeLeft() {}
    @Override public void swipeRight() {}
    @Override public void swipeDown() {}
    @Override public void swipeUp() {}
});

内容的提问来源于stack exchange,提问作者Thisal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 13:38:22