从 EditText 获取数字
我想从 EditText
的 getText()
方法获取 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于实数(浮点型或双精度型),请使用
android:inputType="numberDecimal"
。详细了解输入类型。要获取该值,请使用以下内容:
For real numbers (float or double), use
android:inputType="numberDecimal"
. More about input types.To get the value, use something like:
当编辑文本中没有任何内容时,我遇到了同样的问题。先尝试检查一下。
如果编辑文本的值为 android:text = "" 或 "123rt" 或 "45*" 或 "asdh" 等。我遇到了同样的异常问题。
编辑
这是我的建议
,仅允许整数值,例如 20、30 等。不允许浮点值,例如 20.002、30.345 等。
用于
允许用户将浮点值添加到编辑文本中
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
only allows integer values e.g. 20, 30, etc. not float values e.g. 20.002, 30.345, etc.
Use
to allow float values into the edit text by user
您收到的数字格式异常是因为返回了空值(假设该值为空)。它不会从 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.