我正在编写一个年龄计算器功能,用户输入年龄(出生年份)和月份(月出生)的年龄值,并根据输入的值计算年龄。
有两个edittext
一个(年龄)和其他(年龄),但我无法获得这些值来计算用户的出生日期。
所以,这就是要清楚我想要的enter image description here 因此,当用户输入年龄6和月3时,它应显示2011-9-01
注意:我在这里使用textwatcher
。
以下是年龄与年龄的代码相同的逻辑以月为单位。
mAgeInYears.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (!s.toString().trim().isEmpty()) {
if (getCurrentFocus().getId() == mAge.getId() || mDOB.getText().toString().trim().isEmpty()) {
Calendar calendar = Calendar.getInstance();
int curYear = calendar.get(Calendar.YEAR);
int curMonth = calendar.get(Calendar.MONTH);
int birthYear = curYear - Integer.valueOf(s.toString().trim());
String calcDOB = String.valueOf(birthYear) + "-" + (String.valueOf(curMonth))+ "-01";
mDOB.setText(calcDOB);
}
}
答案 0 :(得分:0)
您可以尝试这种方式,下面是解决问题的代码段。
<强> MainActivity.java 强>
public class MainActivity extends AppCompatActivity {
private EditText edtYear;
private EditText edtMonth;
private EditText edtDob;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtYear = (EditText) findViewById(R.id.edtYear);
edtMonth = (EditText) findViewById(R.id.edtMonth);
edtDob = (EditText) findViewById(R.id.edtDob);
edtYear.addTextChangedListener(textWatcher);
edtMonth.addTextChangedListener(textWatcher);
}
private TextWatcher textWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
setDobFromYearAndMonth();
}
};
private void setDobFromYearAndMonth() {
int year = 0;
int month = 0;
if (!TextUtils.isEmpty(edtYear.getText())) {
year = Integer.parseInt(edtYear.getText().toString());
}
if (!TextUtils.isEmpty(edtMonth.getText())) {
month = Integer.parseInt(edtMonth.getText().toString());
}
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, -year);
calendar.add(Calendar.MONTH, -month);
calendar.set(Calendar.DAY_OF_MONTH, 1);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
edtDob.setText(sdf.format(calendar.getTimeInMillis()));
}
}
<强>输出:强>
我希望它会对你有所帮助。