我必须使用 DatePickerDialog 在文本视图中获取选定的日期。当我单击文本视图时,应出现 DatePickerDialog。
我写了这个
private DatePickerDialog.OnDateSetListener dateOnDateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDay) {
datePick.setText(new StringBuilder().append(selectedDay).append("-").append(selectedMonth).append("-").append(selectedYear));
}
};
datePick = (TextView) findViewById(R.id.date_pick);
datePick.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Calendar calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
monthOfYear = calendar.get(Calendar.MONTH);
dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
new DatePickerDialog(getContext(), dateOnDateSetListener, year, monthOfYear, dayOfMonth);
}
});
但它不起作用。所以几乎没有谷歌搜索,我把它改成了这个并且它的工作,但我不明白为什么会这样?我在上面的代码中搞砸了什么吗
datePick = (TextView) findViewById(R.id.date_pick);
datePick.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Calendar calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
monthOfYear = calendar.get(Calendar.MONTH);
dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
showDialog(DATE_DIALOG_ID);
}
});
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
// set date picker as current date
return new DatePickerDialog(this, dateOnDateSetListener,
year, monthOfYear,dayOfMonth);
}
return null;
}
private DatePickerDialog.OnDateSetListener dateOnDateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDay) {
datePick.setText(new StringBuilder().append(selectedDay).append("-").append(selectedMonth).append("-").append(selectedYear));
}
};