在我的活动中,我需要2个日期选择器。不幸的是,我不知道如何编码。由于空间不足,我需要将它们显示为对话框。
这是我拥有的并适用于一个DatePicker:
public static class DatePickerFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(),
(DatePickerDialog.OnDateSetListener)
getActivity(), year, month, day);
}
}
public void datePicker(View view) {
DatePickerFragment fragment = new DatePickerFragment();
fragment.show(getSupportFragmentManager(), "date");
}
和相应的监听器:
private void setDate(final Calendar calendar) {
final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM);
date = calendar.getTime();
Button btn = (Button) findViewById(R.id.date_text);
dateString = dateFormat.format(calendar.getTime());
btn.setText(dateString);
}
现在我需要第二个片段的第二个监听器,但我不知道如何实现它。 (片段仅返回已设置侦听器的对话框)\
修改
我提出了想法,但按钮文本仅在第二次尝试后设置:
public void datePicker2 (View view){
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(this,listener,year,month,day);
dialog.show();
listener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
Calendar cal = new GregorianCalendar(i, i1, i2);
setDateTo(cal);
}
};
}
private void setDateTo(final Calendar calendar) {
final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM);
date = calendar.getTime();
Button btn = (Button) findViewById(R.id.date_to_text);
dateString = dateFormat.format(calendar.getTime());
btn.setText(dateString);
}
答案 0 :(得分:-1)
移动
Button btn = (Button) findViewById(R.id.date_to_text);
到onCreate