【Android】设置让输入框只能输入数字

在 Android 里想让输入框只能输入数字,一般用 EditText 并设置 android:inputType 或者 digits 属性。几种方式如下:


方式一:XML中设置 inputType

xml 复制代码
<EditText
    android:id="@+id/et_number"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:hint="请输入数字" />

这样就会弹出数字键盘,并且只能输入数字。


方式二:XML中设置 digits

如果只想限制特定字符(比如只允许 0-9),可以用 digits:

xml 复制代码
<EditText
    android:id="@+id/et_number"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:digits="0123456789"
    android:hint="只能输入0-9的数字" />

方式三:代码里动态设置

java 复制代码
EditText etNumber = findViewById(R.id.et_number);
etNumber.setInputType(InputType.TYPE_CLASS_NUMBER);

或者指定 digits:

java 复制代码
etNumber.setKeyListener(DigitsKeyListener.getInstance("0123456789"));

补充说明

  • android:inputType="numberDecimal" → 可以输入小数。
  • android:inputType="numberSigned" → 可以输入正负号。
  • 如果既要数字又要小数,可以用 numberDecimal|numberSigned。

相关推荐
三少爷的鞋2 小时前
为什么成熟 Android 项目几乎看不到 IdleHandler?
android
kururunga3 小时前
Android知识点回顾之蓝牙协议
android·蓝牙·车载开发
StarsGreen4 小时前
aosp中的SELinux 策略配置和编译流程
android
方白羽8 小时前
Android 开发中常见的编译加速方案
android·app·gradle
StarsGreen10 小时前
Android VINTF 中 Device Manifest 与 Framework Manifest 详解
android
Name_NaN_None12 小时前
安卓手机远程控制电脑方法(Android/Windows) —— 「小白教程」
android·windows·智能手机·电脑·笔记本
恋猫de小郭12 小时前
Flutter Perfetto:Dart Heap Sampling 终于要接入 Android 原生内存分析了
android·前端·flutter
敢敢のwings1 天前
GR00T 2:当机器人学会先想象未来,再决定怎么动
android·机器人
传奇开心果编程1 天前
【Jetpack Compose娓娓道来】第55课:传感器与设备姿态——把物理世界的数据接进Compose
android·kotlin·移动开发·传感器·jetpack compose·ui框架·声明式ui
传奇开心果编程1 天前
【Jetpack Compose娓娓道来】第52课:蓝牙与位置权限——把“附近”和“在哪”安全地接进Compose
android·kotlin·移动开发·蓝牙·jetpack compose·声明式ui·位置权限