所以我是Android开发的新手。我一直在研究称为Tombstone计算器的小型软件。用户假设输入三个信息。这两个信息将用于填写最后一个信息。给出出生日期或死亡日期,它将计算出他们的生活年月日。否则,如果提供了生日和寿命,它将计算死亡日期。我已经为这些用户输入设置了三个Calendar Object,但是我不确定如何使用这些对象来获得所需的结果。这是我现在得到的代码。同样由于某种原因,onClick方法不起作用。
public class MainActivity extends AppCompatActivity {
private EditText birthdayText;
private EditText deathText;
private EditText yearsLived;
private Button compute;
private TextView LivedYears;
/*
private Date bi;
private Date de;
private Date li;
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
compute = findViewById(R.id.compute);
birthdayText = findViewById(R.id.birthday);
deathText = findViewById(R.id.death);
yearsLived = findViewById(R.id.lived);
LivedYears = findViewById(R.id.LivedYears);
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd ");
final SimpleDateFormat livedFormat = new SimpleDateFormat("yy-MM-dd");
compute.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String birthday = birthdayText.getText().toString();
String death = deathText.getText().toString();
String lived = yearsLived.getText().toString();
try{
if(death.matches("")){
Calendar calBi = Calendar.getInstance();
Date bi = dateFormat.parse(birthday);
calBi.setTime(bi);
Calendar calLi = Calendar.getInstance();
Date li = livedFormat.parse(lived);
calLi.setTime(li);
}else if(birthday.matches("")){
Calendar calDe = Calendar.getInstance();
Date de = dateFormat.parse(death);
calDe.setTime(de);
Calendar calLi = Calendar.getInstance();
Date li = livedFormat.parse(lived);
calLi.setTime(li);
}else if (lived.matches("")){
Calendar calBi = Calendar.getInstance();
Date bi = dateFormat.parse(birthday);
calBi.setTime(bi);
Calendar calDe = Calendar.getInstance();
Date de = dateFormat.parse(death);
calDe.setTime(de);
long diff = calDe.getTimeInMillis() - calBi.getTimeInMillis();
LivedYears.setText(Long.toString(diff));
}
}catch (ParseException e){
e.printStackTrace();
}
}
});
}
}