我正在尝试从按钮创建一个弹出日期选择器(弹出它的按钮也显示日期)。但是弹出窗口没有显示出来。按下按钮时没有任何反应。
DatePicker需要从xml中提取,因为我希望它显示为旋转器而不是日历(并且我在API 21之后读取的唯一方法是在xml中)
以下是按钮的onClickLlistner的代码:
final Button startDate = (Button)findViewById(R.id.startDate);
Calendar currentDate = Calendar.getInstance();
mYear = currentDate.get(Calendar.YEAR);
mMonth = currentDate.get(Calendar.MONTH);
int mDay = currentDate.get(Calendar.DAY_OF_MONTH);
startDate.setText(mMonth + "/" + mDay + "/" + mYear);
startDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//get date from button text
Calendar dateInButton = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
try {
dateInButton.setTime(sdf.parse(startDate.getText().toString()));
} catch (ParseException e) {
e.printStackTrace();
}
int pYear = dateInButton.get(Calendar.YEAR);
int pMonth = dateInButton.get(Calendar.MONTH);
int pDay = dateInButton.get(Calendar.DAY_OF_MONTH);
//display popup datepicker
final View dialogView = View.inflate(MyActivity.this, R.layout.date_picker, null);
DatePicker datePicker = (DatePicker) dialogView.findViewById(R.id.date_picker);
datePicker.updateDate(pYear, pMonth, pDay);
datePicker.init(pYear, pMonth, pDay, new DatePicker.OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker view, int year, int month, int day) {
month++;
startDate.setText(month + "/" + day + "/" + year);
}
});
}
});