当EditText为空时,Android动态计算崩溃
我正在开发一个磁盘空间计算器,我需要根据用户输入动态计算一些值。我的应用程序中有一个接收数字的 EditText 元素。我想调用我的函数calculate(),当用户在文本字段中输入值时,它将自动计算其他值。这是我的代码
//fps is my EditText element
this.fps.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
// TODO Auto-generated method stub
calculate();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
我的calculate()函数使用文本输入,将其转换为浮点数并计算其他值,例如带宽。它工作正常,但当我想删除 EditText 中的所有数字以添加另一个数字时,问题就出现了。当 editText 中没有任何内容时,它会给出异常。据我了解,这是因为没有什么可以转换为浮点数,因此解析异常等。 我尝试设置默认值
if(fps.getText().length==0)
fps.setText("1");
但它不起作用。我该如何解决这个问题?
I'm working on a disk space calculator and i need to dynamically calculate some values according to user input. I have an EditText element in my application that receives numbers. I want to call my function calculate() that will calculate other values automatically when user inputs a value in the text field. Here's my code for it
//fps is my EditText element
this.fps.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
// TODO Auto-generated method stub
calculate();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
My calculate() function uses the text input, converts it into float and calculates other values like bandwidth. It works fine but the problem comes when I want to delete all numbers in EditText to add another one. The moment there's nothing in the editText it gives an exception. Which I understand, it's because there's nothing to convert into float so parsing exception etc.
I tried putting a default value
if(fps.getText().length==0)
fps.setText("1");
But it doesn't work. How can I solve this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只需尝试用 try/catch 块包围您的
calculate()
并捕获抛出的异常。Just try to surround your
calculate()
with try/catch block and catch the exception thrown..试试这个:
Try this:
当您的编辑文本中至少有一个字符时,尝试在 onTextChanged() 中调用您的calculate(),如下所示。
Try to call your calculate() in onTextChanged() when at least single charcter is there in your edittext like this.
在
afterTextChanged
中进行操作Do your operation in
afterTextChanged