如何在 DialogFragment
上格式化 DatePicker
的月份?
我创建了扩展 DialogFragment
的此类:
自定义日期选择器
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);
}
}
在我的 Activity 中,我创建了一个函数,当我触摸图标或 TextView
时显示 DatePicker
:
public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerCustom();
newFragment.show(getFragmentManager(), "datePicker");
}
在显示中我看到这样的日期:22 - 7 - 2016 但我会有这样的格式:22 - 07 - 2016 所以如果月份 < of 10
我该怎么做?
最佳答案
您可以使用 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);
}
关于android - 设置格式月 DatePicker extends DialogFragment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38529165/