0

我正在开发一个应用程序,它将在单个输入中执行多种方法。例如计算平方周长和面积,我只给出一个 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();
    }
}

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

4

1 回答 1

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您应该使用this或代替YourActivityName.thisContextgetApplicationContext()

我可能会提出另一个建议,因为您onClick()的 s 只调用一个方法,为了使其更简单,您可以使用这样的一个侦听器

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;
     }
}

您只需要记住添加implements OnClickListener到您的类定义中。这只是一个偏好,但值得一提。

于 2013-06-17T18:14:10.327 回答