从DatePickerDialog设置日期的好习惯?

时间:2019-07-09 05:52:01

标签: java android date

我当前正在开发一个应用程序,在这个应用程序中,您需要能够选择日期。我通过显示DatePickerDialog并将值应用于EditText解决了此问题。我的同事告诉我,我不应该在函数中创建新对象,而应该将其声明为变量。

final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);
int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH);

DatePickerDialog datePickerDialog = new DatePickerDialog(this,
    new DatePickerDialog.OnDateSetListener() {

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

                startDate.setText(year + "-" +(monthOfYear + 1) + "-" + dayOfMonth);
        }
    }, mYear, mMonth, mDay);

//datePickerDialog.onDateChanged();
datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis());
datePickerDialog.show();

这是一种好习惯还是有更好的方法来解决这个问题?

2 个答案:

答案 0 :(得分:0)

尝试此操作,我们可以为此方法创建自定义日期选择器:

public class TimePickerDialogCustom extends Dialog implements View.OnClickListener {

public Activity c;
public Dialog d;
public RelativeLayout close;
TextView time;
private Button ok;
private TimePicker timePicker;
int status;
AlexPoppinsLightTextView error_msg_txtView;


public TimePickerDialogCustom(FragmentActivity a, TextView time, int status) {
    super(a);
    this.c = a;
    this.time = time;
    this.status = status;

}


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.pick_time_layout);
    close = findViewById(R.id.closepopup);
    ok = findViewById(R.id.btn_ok_time);
    timePicker = findViewById(R.id.tp_for_activity);

    AppGlobalValidation.hideKeyboard(getContext());


    if (status == 1) {
        SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm");
        SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a");
        try {
            Date date = parseFormat.parse(time.getText().toString());
         String time = displayFormat.format(date);            //which is from server;
            String splitTime[] = time.split(":");
            int hours = Integer.parseInt(splitTime[0]);
            int minutes = Integer.parseInt(splitTime[1]);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                timePicker.setHour(hours);
                timePicker.setMinute(minutes);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    } else if (status == 2) {

        SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm");
        SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a");
        try {
            Date date = parseFormat.parse(time.getText().toString());
            String time = displayFormat.format(date);    //which is from server;
            String splitTime[] = time.split(":");
            int hours = Integer.parseInt(splitTime[0]);
            int minutes = Integer.parseInt(splitTime[1]);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                timePicker.setHour(hours);
                timePicker.setMinute(minutes);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    } 


    error_msg_txtView = findViewById(R.id.error_msg_txtView);
    close.setOnClickListener(this);


    ok.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (status == 1) {
                int hour = timePicker.getCurrentHour();
                int minute = timePicker.getCurrentMinute();

                if (hour >= 0 && hour < 12) {
                    error_msg_txtView.setVisibility(View.GONE);
    time.setText(AppGlobalValidation.convertTo12Hour("" + hour + ":" + "" + minute));
                    AppGlobalValidation.hideKeyboard(getContext());
                    dismiss();

                } else {
                    error_msg_txtView.setVisibility(View.VISIBLE);
                    error_msg_txtView.setText("Please Select Morning");

                }

            } else if (status == 2) {

                int hour = timePicker.getCurrentHour();
                int minute = timePicker.getCurrentMinute();

                if (hour >= 12 && hour < 18) {
                    error_msg_txtView.setVisibility(View.GONE);
    time.setText(AppGlobalValidation.convertTo12Hour("" + hour + ":" + "" + minute));
                    dismiss();
                    AppGlobalValidation.hideKeyboard(getContext());

                } else {
                    error_msg_txtView.setVisibility(View.VISIBLE);
                    error_msg_txtView.setText("Please Select Afternoon ");

                }

            } 
}

@Override
public void onClick(View view) {
    dismiss();
    AppGlobalValidation.hideKeyboard(getContext());
}
 }

创建此方法后,可在您的活动或片段中调用此方法:

在单击侦听器上调用此方法:

    TimePickerDialogCustom timePickerDialogCustom = new 
    TimePickerDialogCustom(getActivity(), morning_time_txtView, 1);
            timePickerDialogCustom.show();
            timePickerDialogCustom.setCancelable(false);
            timePickerDialogCustom.setCanceledOnTouchOutside(true);

答案 1 :(得分:0)

我建议

  1. 使用现代Java日期和时间API java.time中的LocalDate代替CalendarCalendar设计欠佳,已经过时。
  2. 使用格式化程序来格式化要显示的日期文本。专门使用内置的本地化格式在某些语言环境中取悦用户。

所以您的代码片段变成了这样的东西:

    LocalDate today = LocalDate.now(ZoneId.systemDefault());
    int mYear = today.getYear();
    Month mMonth = today.getMonth();
    int mDay = today.getDayOfMonth();

    DatePickerDialog datePickerDialog = new DatePickerDialog(this,
        new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year,
                    int monthOfYear, int dayOfMonth) {
                DateTimeFormatter dateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
                LocalDate date = LocalDate.of(mYear, monthOfYear + 1, dayOfMonth);
                startDate.setText(date.format(dateFormatter));
            }
        }, mYear, mMonth.getValue() - 1, mDay);

问题:我可以在Android上使用LocalDate和Month吗?

是的,java.time中的类在旧的和更新的Android设备上都能很好地工作。他们只需要至少 Java 6

  • 在Java 8和更高版本以及更新的Android设备(API级别26以上)中,内置了现代API。
  • 在Java 6和7中,获得了ThreeTen反向端口,这是现代类的反向端口(JSR 310的ThreeTen;请参见底部的链接)。
  • 在(较旧的)Android上,使用Android版本的ThreeTen Backport。叫做ThreeTenABP。并确保您使用子包从org.threeten.bp导入日期和时间类。

链接