我试图创建一个简单的计算器来计算矩形的平方,其中包含在EditText中保存的两边。按下按钮后,结果应显示在textView中。但是我无法将从EditText获得的值转换为Int
类型。这是我的代码:
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) {
}
});
}
有人对我有任何建议吗?
答案 0 :(得分:2)
编辑代码如下:
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;
}
});