如何在EditText上删除Android Studio中的连接错误?

时间:2015-10-22 00:10:13

标签: android android-edittext android-datepicker

我有一个DatePickerFragment,允许用户从日历中选择日期。然后在EditText行上设置捕获的日期。 onDateSet中的下面代码在操作系统的早期版本中运行良好,现在它给出了以下错误,并且日期没有按预期显示:mm / dd / yyyy。错误在" txtDate.setText ..."上突出显示。线。我在这里做错了什么?

enter image description here

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 个答案:

答案 0 :(得分:2)

你可以这样做:

 String date = String.format("%d/%d/%d ",monthOfYear + 1, dayOfMonth, year);
 txtDate.setText(date);

或者:

int day = view.getDayOfMonth();
int month = view.getMonth();
int year =  view.getYear();
Calendar calendar = Calendar.getInstance();
calendar.set(year, monthOfYear, day);

Date asDate = calendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy", Locale.US);
txtDate.setText(sdf.format(asDate));