EditText问题:不适用于多种方法

时间:2013-06-17 18:09:38

标签: android android-edittext

我正在开发一个应用程序,它将在单个输入中执行多个方法。例如,计算方形周长和面积,我只给出一个EditText和两个按钮。但是当我运行应用程序时,如果我提供输入并单击区域按钮,则在单击圆周按钮之前不会进行计算。如果我改变输入也一样。这是代码:

     @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.square);
    etSide = (EditText) findViewById(R.id.etSquare);
    tvResult = (TextView) findViewById(R.id.tvSquare);
    Button btnCir = (Button) findViewById(R.id.btnSqrCir);
    btnCir.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            countCir();
        }
    });
    Button btnArea = (Button) findViewById(R.id.btnSqrArea);
    btnArea.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            countArea();
        }
    });
}

private void countArea() {
    try {
        side = etSide.getText().toString();
        s = parseInt(side);
        area = s * s;
        tvResult.setText("Area = " + cir);
    } catch (NumberFormatException ex){
        Toast.makeText(getApplicationContext(), "Oops, you seem haven't enter the side length", Toast.LENGTH_LONG).show();
    }
}

private void countCir() {
    try {
        side = etSide.getText().toString();
        s = parseInt(side);
        cir = 4 * s;
        tvResult.setText("Circumference = " + area);
    } catch (NumberFormatException ex){
        Toast.makeText(getApplicationContext(), "Oops, you seem haven't enter the side length", Toast.LENGTH_LONG).show();
    }
}

有什么好主意吗?真的需要帮助......

1 个答案:

答案 0 :(得分:1)

看起来你的变量倒退了。例如:

private void countArea() {
try {
    side = etSide.getText().toString();
    s = parseInt(side);
    area = s * s;
    tvResult.setText("Area = " + cir);  // <-- here cir doesn't have a value until you click the circumference button
} catch (NumberFormatException ex){
    Toast.makeText(getApplicationContext(), "Oops, you seem haven't enter the side length", Toast.LENGTH_LONG).show();
}
}

因此,您的TextView会显示“”Area =“”

在我看来,你想要

tvResult.setText("Area = " + cir);

tvResult.setText("Area = " + area);

如果我没有正确理解你,请告诉我

注意:

对于Toast,您应使用thisYourActivityName.this代替Context

我可能会提出另一个建议,因为你的getApplicationContext()只调用一个方法,为了简化你可以使用这样的一个监听器

onClick()

您只需要记住将public void onCreate(...) { ... btnCir.setOnClickListener(this); btnArea.setOnClickListener(this); ... } public void onClick(View v) { switch(v.getId()) // get the id of the Button clicked { case (R.id.btnSqrArea): // call appropriate method countArea(); break; case (R.id.btnSqrCir): countCir(); break; } } 添加到您的类定义中。这只是一个偏好,但值得一提。