Converting EditText to int? (Android)

2019-01-17 22:31发布

I am wondering how to convert an edittext input to an int, I have the user input a number, it than divides it by 8.

MainActivity.java

@SuppressWarnings("unused")
public void calcSpeed(View view)
{       
    setContentView(R.layout.activity_speed);     

    final TextView mTextView = (TextView) findViewById(R.id.textView3);
    mTextView.setText("You should be getting: " +netSpedCalcd);
}

activity_main.xml

    <EditText
    android:id="@+id/editText1" 
    android:inputType="number"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="62dp"
    android:ems="10" >

9条回答
我只想做你的唯一
2楼-- · 2019-01-17 23:03

you have to used.

String value= et.getText().toString();
int finalValue=Integer.parseInt(value);

if you have only allow enter number then set EditText property.

android:inputType="number"

if this is helpful then accept otherwise put your comment.

查看更多
Explosion°爆炸
3楼-- · 2019-01-17 23:03

I'm very sleepy and tired right now but wouldn't this work?:

EditText et = (EditText)findViewById(R.id.editText1);
String sTextFromET = et.getText().toString();
int nIntFromET = new Integer(sTextFromET).intValue();

OR

try
{
    int nIntFromET = Integer.parseInt(sTextFromET);
}
catch (NumberFormatException e)
{
    // handle the exception
}
查看更多
看我几分像从前
4楼-- · 2019-01-17 23:12

Use Integer.parseInt, and make sure you catch the NumberFormatException that it throws if the input is not an integer.

查看更多
登录 后发表回答