Android Float.parseFloat由于小数点而导致致命错误



我使用以下代码解析字符串中的浮点值:

 EditText CurrPLC = (EditText) findViewById(R.id.CurrPLC);
 String s5 = CurrPLC.getText().toString();
 float F5 = Float.parseFloat(s5);

在我尝试将负值写入EditText之前,这种方法非常有效。因为"负数"符号和小数点在同一个按钮上,所以我先写了一个小数,然后应用程序崩溃,因为字符串"."无法解析为浮点值。该代码在EditText 中的任何文本更改时执行

这是布局文件中的EditText代码:

 <EditText
            android:id="@+id/CurrPLC"
            android:layout_width="100dp"
            android:layout_height="30dp"
            android:padding="2dp"
            android:hint="eg. 3277"
            android:gravity="center_horizontal"
            android:layout_gravity="right"
            android:textSize="13sp"
            android:digits="-0123456789."
            android:inputType="numberSigned|numberDecimal"
            android:maxLength="10"
            android:background="@drawable/plc_edit_text_holo_light"
            android:layout_marginRight="19dp"
            android:layout_marginEnd="19dp"
            android:layout_alignBaseline="@+id/CurrPLCLabel"
            android:layout_alignBottom="@+id/CurrPLCLabel"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />
        />

是我做错了什么,还是这只是因为在错误发生之前处理好了?

感谢

根据您的评论,使用TextWatcher会尝试在每次按键时解析浮点值,问题不在于负数。

parseFloat()可以很好地处理负数。问题出在空字符串或--..上。

因此,你不应该在每次按键时进行解析,而应该只在需要的地方进行解析(我不确定你的完整用例,所以我不能评论解析浮点的适当时间和地点(。否则,您需要在当前解析浮点的任何位置为java.lang.NumberFormatException添加一个try/catch

相关内容

最新更新