我是一个刚入门的 android 程序员,我正在尝试制作一个小费计算器。这是我到目前为止写的代码。我对此有两个问题。首先是,为什么我的计算按钮不起作用?第二个是,如果这段代码写得很干净?还是我走错了路?
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Fooi extends Activity implements OnClickListener {
EditText etBill, etPers, etPerc;
TextView tvTotal, tvTip, tvPerson;
Button bCalc, bReset;
double billamount = 0;
double percentage = 0;
double persons = 0;
double tipamount = 0;
double totaltopay = 0;
double perperson = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.fooi);
Controls();
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bCalculate:
if (billamount == 0 | percentage == 0 | persons == 0) {
// toast text
} else {
Calculate();
}
break;
case R.id.bReset:
etBill.setText("");
etPerc.setText("");
etPers.setText("");
break;
}
}
private void Calculate() {
billamount = Double.parseDouble(etBill.getText().toString());
percentage = Double.parseDouble(etPerc.getText().toString());
persons = Double.parseDouble(etPers.getText().toString());
tipamount = (billamount * percentage) / 100;
totaltopay = billamount + tipamount;
perperson = totaltopay / persons;
tvTip.setText(Double.toString(tipamount));
tvTotal.setText(Double.toString(totaltopay));
tvPerson.setText(Double.toString(perperson));
}
private void Controls() {
bCalc = (Button) findViewById(R.id.bCalculate);
bReset = (Button) findViewById(R.id.bReset);
bCalc.setOnClickListener(this);
bReset.setOnClickListener(this);
tvTotal = (TextView) findViewById(R.id.tvTotal);
tvTip = (TextView) findViewById(R.id.tvBill);
tvPerson = (TextView) findViewById(R.id.tvPerPerson);
etBill = (EditText) findViewById(R.id.etBill);
etPerc = (EditText) findViewById(R.id.etPercentage);
etPers = (EditText) findViewById(R.id.etPerson);
}
}
关于这行代码我也不确定。 if (billamount == 0 | percentage == 0 | persons == 0) {
// toast text
我希望它仅在填充三个 EditText 时才计算。如果我错了,有人可以告诉我吗?
提前致谢!!