具有负数的EditText和TextWatcher

时间:2012-09-12 05:37:48

标签: java android textwatcher

我在向EditText输入负int时出现问题,当我这样做时出现错误09-12 06:26:42.025: E/AndroidRuntime(18247): java.lang.NumberFormatException: Invalid int: "-" xml文件:

<EditText
        android:id="@+id/downAndDistanceStarting"
        android:layout_width="180dp"
        android:layout_height="match_parent"
        android:ems="10"
        android:inputType="numberSigned"
        android:selectAllOnFocus="true"
        android:textSize="@dimen/enterText" >

java代码:

end = (EditText) findViewById(R.id.downAndDistanceEnding);
public void afterTextChanged(Editable s) {
int w = Integer.parseInt(end.getText().toString());
}

我假设我的textWatcher出现了问题,并且在每次键盘“按下”后“发送”我的输入,所以当我尝试输入-12时,它会发送“ - ”进行“解析”之前我设法完成,这就是我的应用程序崩溃的原因,我是对的吗?任何人都知道如何解决它?

2 个答案:

答案 0 :(得分:0)

是的,你是对的。将代码包装在try / catch块中,然后,当收到 - 时,它将抛出NumberFormatException,它将被捕获。

try
{
int w = Integer.parseInt(end.getText().toString());
}catch(NumberFormatException e)
{

}

答案 1 :(得分:0)

我遇到了同样的问题。我在解析之前放了一个if条件。像这样,所以直到你输入第二个数字,它才会解析。

end = (EditText) findViewById(R.id.downAndDistanceEnding);
public void afterTextChanged(Editable s) {
  if(!end.getText().toString().equals("-"));
  {
    int w = Integer.parseInt(end.getText().toString());
  } else { //do something  }
}