所以这是我到目前为止的代码:
Button calculate = (Button)findViewById(R.id.calculate);
calculate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText sun = (EditText)findViewById(R.id.sun1);
EditText mon = (EditText)findViewById(R.id.mon1);
EditText tue = (EditText)findViewById(R.id.tue1);
EditText wed = (EditText)findViewById(R.id.wed1);
EditText thu = (EditText)findViewById(R.id.thu1);
EditText fri = (EditText)findViewById(R.id.fri1);
EditText sat = (EditText)findViewById(R.id.sat1);
EditText wage = (EditText)findViewById(R.id.wage);
double sun1 = Double.parseDouble(sun.getText().toString());
double mon1 = Double.parseDouble(mon.getText().toString());
double tue1 = Double.parseDouble(tue.getText().toString());
double wed1 = Double.parseDouble(wed.getText().toString());
double thu1 = Double.parseDouble(thu.getText().toString());
double fri1 = Double.parseDouble(fri.getText().toString());
double sat1 = Double.parseDouble(sat.getText().toString());
double wage1 = Double.parseDouble(wage.getText().toString());
TextView hours = (TextView)findViewById(R.id.hours);
TextView income = (TextView)findViewById(R.id.Income);
if(wage.getText().length()==0){
Toast.makeText(getContext(), "Enter the wage", Toast.LENGTH_SHORT).show();
}
else{
Calculator calc = new Calculator(sun1,mon1,tue1,wed1,thu1,fri1,sat1,wage1);
hours.setText(calc.hours()+"");
income.setText(calc.calc()+"");
}
正如您所看到的,每当用户将任何字段留空时,我都希望显示一个Toast。在这种情况下,我只使用工资对象来显示我失败的地方。我也尝试过wage.getText()。toString()。equals("")仍然我的应用程序崩溃了。也许这是吐司课,我错了。在maketoast中使用(this)而不是getContext()也没有帮助。有什么建议?
答案 0 :(得分:1)
您收到了错误消息,因为findViewById(...)
并未绑定到正确的this
。它应该在onClick
监听器之外。
通常,我会做类似以下的事情:
public class MainActivity extends Activity {
private EditText sun;
private EditText mon;
private EditText tue;
private EditText wed;
private EditText thu;
private EditText fri;
private EditText sat;
private EditText wage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
instantiateViews();
}
private void instantiateViews() {
sun = (EditText) findViewById(R.id.sun1);
mon = (EditText) findViewById(R.id.mon1);
tue = (EditText) findViewById(R.id.tue1);
wed = (EditText) findViewById(R.id.wed1);
thu = (EditText) findViewById(R.id.thu1);
fri = (EditText) findViewById(R.id.fri1);
sat = (EditText) findViewById(R.id.sat1);
wage = (EditText) findViewById(R.id.wage);
}
//Write whatever other code you would here
}
此外,我建议您使用TextUtils.isEmpty
优先于当前方法检查wage
是否为空。