【发布时间】:2016-01-21 03:50:21
【问题描述】:
我有一个 DatePickerFragment,它可以让用户从日历中选择一个日期。然后将捕获的日期设置在 EditText 行上。 onDateSet 中的以下代码在以前版本的操作系统上运行良好,现在它给出了以下错误并且日期未按预期显示:mm/dd/yyyy。该错误在“txtDate.setText...”行上突出显示。我在这里做错了什么?
public Dialog onCreateDialog(@NonNull Bundle savedInstanceState) {
super.onCreateDialog(savedInstanceState);
// If the argsbundle from the Activity has data (because the user previously selected a date) then
// set that date in the DatePicker.
if (getArguments() != null) {
c = Calendar.getInstance();
year = getArguments().getInt("year");
month = getArguments().getInt("month");
day = getArguments().getInt("day");
c.set(year, month, day);
} else { // If the DueDate EditText line is empty (no previously selected date by the user then
// set today's date into the DatePicker.
// Calendar class obtains the current date on the device and has fields for
// each of the parts of the date: day, month and year.
c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
}
DatePickerDialog picker = new DatePickerDialog(getActivity(),
this, year, month, day);
// Set monthly calendar rather than default spinner.
picker.getDatePicker().setCalendarViewShown(true);
// Turn off date selector spinner.
picker.getDatePicker().setSpinnersShown(false);
picker.setTitle("Select a Due Date");
return picker;
}
部分 DatePickerFragment.java 文件:
...
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
// Set the selected date into the FEditText line.
EditText txtDate = (EditText) getActivity().getWindow().getDecorView().getRootView().findViewById(R.id.FEditText);
// Format the selected date.
txtDate.setText((monthOfYear + 1) + "/" + dayOfMonth + "/" + year + " ");
// Display the date. "Month" uses a zero-based index from 0 to 11, so need to add 1 to show properly.
txtDate.setSelection(txtDate.getText().length());
}
【问题讨论】:
-
这是一个警告,很清楚它在说什么。 1)字符串与数字的连接可能不会产生预期的结果,并且 2)您应该通过 res/strings.xml 使用字符串资源
-
我是编程和 Android 新手……我不清楚,这就是我问这个问题的原因。
标签: android android-edittext android-datepicker