开发者

Converting from Editable to int in android

I want to convert the type Editable from an android EditText to the type integer to do maths operations on a user input number

I tried the following:

int x=(int)R2.getText().to开发者_高级运维String();

but it gives me an error of cannot convert a string to int.


Fine, I got the answer:

int x = Integer.parseInt(R2.getText().toString());


Use parseInt(), like this -

intX = Integer.parseInt(myEditWidget.getText().toString());

The getText() method (which is inherited by your EditText widget from the View() class) returns an object of type Editable which must be converted to a String type before parseInt() can handle it.

Note that even if your EditText widget is defined with the android:inputType="number" you will want to catch the exception (NumberFormatException) that parseInt throws to make sure the value fits in an int!


Try Integer.ParseInteger(R2.getText())


I used

int x = Integer.getInteger(R2.getText().toString()); 

parseInteger wouldn't work for me.


My program works this way:

int age = 0;

final EditText txt_age = (EditText) findViewById (R.id.editTextAge);


String str_age = txt_age.getText().toString();

age = Integer.valueOf(str_age);


In Koltin you can just add toString().toInt(). For example,

var someInt = some_edit_text.toString().toInt()


In Kotlin: Here we get a text from the edt that is an edit text.

val edt = findViewById<EditText>(R.id.editText)
val id = edt.text

To convert id to int:

id.toString().toInt()

Done!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜