Android 设置格式月份日期选择器扩展DialogFragment
如何在Android 设置格式月份日期选择器扩展DialogFragment,android,android-datepicker,Android,Android Datepicker,如何在DialogFragment上格式化DatePicker的月份? 我创建了这个类,它扩展了DialogFragment: DatePickerCustom public class DatePickerCustom extends DialogFragment implements DatePickerDialog.OnDateSetListener { @Override public Dialog onCreateDialog(Bundle savedIns
DialogFragment
上格式化DatePicker
的月份?
我创建了这个类,它扩展了DialogFragment
:
DatePickerCustom
public class DatePickerCustom extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
@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);
month = month+1;
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
TextView datePickerText = (TextView)getActivity().findViewById(R.id.date_picker_text);
datePickerText.setText(day+" - "+month+" - "+year);
}
}
在我的活动中,我创建了一个函数,当我触摸图标或TextView
时,它会显示DatePicker
:
public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerCustom();
newFragment.show(getFragmentManager(), "datePicker");
}
在显示中,我看到的日期是:22-7-2016,但我会使用这种格式:22-07-2016,所以如果小于10,则在月份之前使用0
如何执行此操作?您可以使用
Calendar
从您的值创建一个Date
对象,并使用适当的SimpleDateFormat
实例对其进行格式化
大概是这样的:
public void onDateSet(DatePicker view, int year, int month, int day) {
TextView datePickerText = (TextView) getActivity().findViewById(R.id.date_picker_text);
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, day);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
String dateString = dateFormat.format(calendar.getTime());
datePickerText.setText(dateString);
}