Android开发

Android 日期和时间的使用实例详解

本文主要是介绍Android 日期和时间的使用实例详解,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Android 日期和时间的使用

日期和时间的使用;

1:弹出框TimePickerDialog,DatePickerDialog

2:组件TimePicker,DatePicker

TimePickerDialog的使用:通过点击button显示图一,然后用户可以设置时间

DatePickerDialog的使用只需要将TimePickerDialog修改成DatePickerDialog, TimePickerDialog.OnTimeSetListener 分别修改成DatePickerDialog,OnDateSetListener既可

public static class TimePickerFragment extends DialogFragment
              implements TimePickerDialog.OnTimeSetListener {
    //用户创建弹出时间框的方法
  @Override
  public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Use the current time as the default values for the picker
    final Calendar c = Calendar.getInstance();
    int hour = c.get(Calendar.HOUR_OF_DAY);
    int minute = c.get(Calendar.MINUTE);

    // Create a new instance of TimePickerDialog and return it
    return new TimePickerDialog(getActivity(), this, hour, minute,
        DateFormat.is24HourFormat(getActivity()));
  }

  public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    // Do something with the time chosen by the user
  }
}
 
  
 android:layout_width="wrap_content" 
  android:layout_height="wrap_content"
  android:text="@string/pick_time" 
  android:onClick="showTimePickerDialog" />
public void showTimePickerDialog(View v) {
  DialogFragment newFragment = new TimePickerFragment();
  newFragment.show(getSupportFragmentManager(), "timePicker");
}


DatePickerDialog的代码:

public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {

  //用户创建日期对话框的时间方法
  @Override
  public Dialog onCreateDialog(Bundle savedInstanceState) {

    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(getActivity(), this, year, month, day);
    return dialog;
  }



  @Override
  public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {



  }

}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

这篇关于Android 日期和时间的使用实例详解的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!