2016-07-22 87 views
2

如何在DialogFragment上格式化月份DatePicker? 我创建这个类,它扩展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); 

    } 
} 

在我的活动我已经创建了一个展示DatePicker当我触摸的图标或TextView功能:

public void showDatePickerDialog(View v) { 
    DialogFragment newFragment = new DatePickerCustom(); 
    newFragment.show(getFragmentManager(), "datePicker"); 

} 

在显示屏中,我看到的日期如下:22 - 7 - 2016,但是我将使用以下格式:22 - 7 - 2016 so with 0 before month如果它是< of 10

我该怎么做?

回答

1

您可以使用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); 
} 
+0

谢谢!完善! – LorenzoBerti