从 EditText 获取数字

发布于 2025-01-02 23:54:15 字数 648 浏览 3 评论 0原文

我想从 EditTextgetText() 方法获取 float

这就是我所做的:

  • 在layout.xml 中
<前><代码><编辑文本 android:id="@+id/et_Amount" 安卓:layout_width =“fill_parent” 安卓:layout_height =“wrap_content” android:inputType="数字" android:hint="您购买的燃料单位"> <请求焦点/>
  • 在我的活动中
public void setAmount() {
  EditText tx = (EditText) findViewById(R.id.et_Amount);
  浮动金额 = Float.valueOf(tx.getText().toString()); 
}

不幸的是抛出了 NumberFormatException 。有什么想法吗?

I want to get a float from an EditText's getText() method

This is what I did:

  • In layout.xml
<EditText
    android:id="@+id/et_Amount"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:inputType="number" 
    android:hint="Units of fuel you purchased">

    <requestFocus />
</EditText>
  • In my activity
public void setAmount() {
  EditText tx = (EditText) findViewById(R.id.et_Amount);
  float amount = Float.valueOf(tx.getText().toString()); 
}

Unfortunately a NumberFormatException is thrown . Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

初吻给了烟 2025-01-09 23:54:15

对于实数(浮点型或双精度型),请使用 android:inputType="numberDecimal"。详细了解输入类型

<EditText
       ...
       android:inputType="numberDecimal" />

要获取该值,请使用以下内容:

EditText amount_text = (EditText) rootView.findViewById(R.id.et_Amount);
double amount = Double.parseDouble(amount_text.getText().toString());

For real numbers (float or double), use android:inputType="numberDecimal". More about input types.

<EditText
       ...
       android:inputType="numberDecimal" />

To get the value, use something like:

EditText amount_text = (EditText) rootView.findViewById(R.id.et_Amount);
double amount = Double.parseDouble(amount_text.getText().toString());
|煩躁 2025-01-09 23:54:15

当编辑文本中没有任何内容时,我遇到了同样的问题。先尝试检查一下。

如果编辑文本的值为 android:text = "" 或 "123rt" 或 "45*" 或 "asdh" 等。我遇到了同样的异常问题。

编辑
这是我的建议

android:inputType="number"

,仅允许整数值,例如 20、30 等。不允许浮点值,例如 20.002、30.345 等。

用于

android:numeric="integer|decimal"

允许用户将浮点值添加到编辑文本中

I got the same problem when nothing is there in edit text. Try to check it first.

If edit text have values android:text = "" or "123rt" or "45*" or "asdh", etc. I faced same exception problem.

EDIT
This is my suggestion only

android:inputType="number"

only allows integer values e.g. 20, 30, etc. not float values e.g. 20.002, 30.345, etc.

Use

android:numeric="integer|decimal"

to allow float values into the edit text by user

撕心裂肺的伤痛 2025-01-09 23:54:15

您收到的数字格式异常是因为返回了空值(假设该值为空)。它不会从 null 中解析出 0。

The number format exception you are getting is because there is a null value being returned (assuming the value is blank). It doesn't parse a 0 from a null.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文