【问题标题】:How to control input in EditText in Android? [duplicate]如何在 Android 中控制 EditText 中的输入? [复制]
【发布时间】:2026-02-05 02:35:01
【问题描述】:

这是一个两部分的问题:

1) 我目前正在使用

android:inputType="numberDecimal|numberSigned"

在我的应用中控制输入。

但是,我不断收到来自 NumberFormatExceptions 用户的崩溃报告。 其中之一是:

Caused by: java.lang.NumberFormatException: Invalid float: "2,7"

很明显,用户以某种方式规避了我控制输入的措施并使用“,”而不是“。”。我暂时用过

String.replace(",", ".")

试图修复它,但我仍然得到 NumberFormatExceptions 。

我该怎么办?

2) 如何强制软键盘应用仅显示数字键盘、“-”和“.”?

XML:

<EditText
        android:id="@+id/speed"
        android:layout_width="0px"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:inputType="number|numberDecimal" >

活动中:

public void onClickCalc(View view)
{
    switch(view.getId())
    {
              String sp = speed.getText().toString().replace(",", ".");
                if(functions.isNotValid(sp))
                {
                    Toast.makeText(this, "Invalid input.", Toast.LENGTH_LONG).show();
                    return;
                }

                float speed = Float.parseFloat(sp);

... logic here
}

在类函数中:

public static boolean isNotValid(String editable)
{
    try
    {
        float x = Float.parseFloat(editable);
    }
    catch(NumberFormatException nFE)
    {
        return true;
    }

    return false;
}

【问题讨论】:

标签: android input crash


【解决方案1】:

只需回答即可关闭此内容。 Kenton Prince 的回复很好。

【讨论】: