简体   繁体   中英

How can i get value from EditText and convert it to int type

I've tried to create a simple calculator to calculate the square of the rectangle with 2 sides of it held in EditText. After I press the button, the result should be displayed in the textView. But I couldn't convert the value that I get from the EditText to an Int type. Here is my code:

protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button button = (Button)findViewById(R.id.btn);


    final TextView textView = (TextView) findViewById(R.id.txt1);

    final EditText editText1 = (EditText)findViewById(R.id.edittxt1);

    final EditText editText2 = (EditText)findViewById(R.id.edittxt2);

    int num1=0,num2=0;
    final int num3=0;
    String a = editText1.getText().toString();
    String b = editText2.getText().toString();
    num1=Integer.parseInt(a);
    num2=Integer.parseInt(b);


    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


        }
    });
}

Does anyone have any suggestions for me?

Edit your code follow:

    final TextView textView = (TextView) findViewById(R.id.txt1);

    final EditText editText1 = (EditText)findViewById(R.id.edittxt1);

    final EditText editText2 = (EditText)findViewById(R.id.edittxt2);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

          String a = editText1.getText().toString();
          String b = editText2.getText().toString();
          int num1=Integer.parseInt(a);
          int num2=Integer.parseInt(b);
          int num3 = num1 + num2;
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM