简体   繁体   English

我如何从EditText获取值并将其转换为int类型

[英]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. 我试图创建一个简单的计算器来计算包含在EditText中的矩形的两个边的平方。 After I press the button, the result should be displayed in the textView. 按按钮后,结果应显示在textView中。 But I couldn't convert the value that I get from the EditText to an Int type. 但是我无法将从EditText获得的值转换为Int类型。 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;
        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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