在Android中从Editable转换为int

she*_*rif 14 android

我想将类型Editable从android EditText转换为类型整数,以对用户输入数字进行数学运算

我尝试了以下方法:

int x=(int)R2.getText().toString();
Run Code Online (Sandbox Code Playgroud)

但它给了我一个错误,无法将字符串转换为int.

she*_*rif 27

好的,我得到了答案:

int x = Integer.parseInt(R2.getText().toString());
Run Code Online (Sandbox Code Playgroud)


Pau*_*ulP 9

使用parseInt(),就像这样 -

intX = Integer.parseInt(myEditWidget.getText().toString());
Run Code Online (Sandbox Code Playgroud)

getText()方法(由类中的EditText小部件继承View())返回一个类型的对象,Editable在parseInt()可以处理它之前必须将其转换为String类型.

请注意,即使您的EditText小部件已定义,android:inputType="number"您也希望捕获NumberFormatExceptionparseInt抛出的异常()以确保该值适合int!


iar*_*n01 5

尝试 Integer.ParseInteger(R2.getText())