Android - How to take an EditText (numbers) then convert it to an integer to use it for math?

大城市里の小女人 提交于 2019-12-05 05:51:26

First, get an instance of the EditText:

EditText myEdit = (EditText) findViewById(R.id.edittext1);

Then get the string that is currently being displayed:

String myEditValue = myEdit.getText().toString();

Then parse it for an integer:

int myEditNum = Integer.parseInt(myEditValue);

You have to change, in the property of your EditText, the Input type. For numbers, you have three choice: number, numberSigned or numberDecimal. It depends on what you want.

Then if you want to convert your string on your EditText to an integer, you can do:

int value = new Integer(myEditText.getText().toString()).intValue;
EditText myEdit = (EditText) findViewById(R.id.edittext1);

String myEditValue = myEdit.getText().toString();

int myEditNum = Integer.parseInt(myEditValue);

myEditNum.setText(textOut1);

I am using the above to get user input as a number format. However when I try to display the int myEditNum in a TextView(textOut1) using the setText() method I get an error for the setText method (saying: ''Cannot invoke setText(TextView) on the primitive type int'').

I also tried (below) to convert int myEditNum to a String and then display it to a TextView but still doesn't work as I get the folloing error for the setText method: ''The method setText(TextView) is undefined for the type String''. EditText myEdit = (EditText) findViewById(R.id.edittext1);

String myEditValue = myEdit.getText().toString();

int myEditNum = Integer.parseInt(myEditValue);


String texting = Integer.toString(myEditNum);

texting.setText(textOut1);

Why does this happen and how do I solve it?

Eryl Talbot

You should use:

myEdit.setText(myEditValue);

myEditValue is the String version of myEditNum.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!