5

这是我的第一篇文章,我正在尝试创建一个非常简单的任务应用程序,但是我遇到了(似乎是)onDateChanged 方法的问题。即使对话框正常弹出,它似乎也没有实现更改。日志中没有错误,我仔细检查了具有类似功能的各种解决方案,但我找不到相关的东西。(最小SDK 16,目标21)

提前非常感谢,如果这是显而易见的事情,我很抱歉。

 
public class DatePickerFragment extends DialogFragment {

    public static final String EXTRA_DATE = "thanoschatz.com.annastodolist.date";

    private Date mDate;

    public static DatePickerFragment newInstance(Date mDate) {
        Bundle args = new Bundle();
        args.putSerializable(EXTRA_DATE, mDate);

        DatePickerFragment fragment = new DatePickerFragment();
        fragment.setArguments(args);

        return fragment;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        mDate = (Date) getArguments().getSerializable(EXTRA_DATE);


        Calendar calendar = Calendar.getInstance();
        calendar.setTime(mDate);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        View v = getActivity().getLayoutInflater().inflate(R.layout.dialog_date, null);

        DatePicker datePicker = (DatePicker) v.findViewById(R.id.dialog_date_datepicker);
        datePicker.init(year, month, day, new DatePicker.OnDateChangedListener() {
            @Override
            public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

                mDate = new GregorianCalendar(year, monthOfYear, dayOfMonth).getTime();


                getArguments().putSerializable(EXTRA_DATE, mDate);
            }
        });

        return new AlertDialog.Builder(getActivity())
                .setView(v) //
                .setTitle(R.string.date_picker_title) //
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        sendResult(Activity.RESULT_OK);
                    }
                })
                .create();
    }

    private void sendResult(int resultCode) {
        if (getTargetFragment() == null) return;

        Intent intent = new Intent();
        intent.putExtra(EXTRA_DATE, mDate);

        getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, intent);
    }
}
 

public class ToDoFragment extends Fragment {
    public static final String EXTRA_TODO_ID = "thanoschatz.com.annastodolist.todo_id";
    private static final String DIALOG_DATE = "date";
    private static final int REQUEST_DATE = 0;

    private ToDo mToDo;
    private EditText mTitleField;
    private Button mDateButton;
    private CheckBox mDoneCheckBox;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        UUID toDoId = (UUID)getArguments().getSerializable(EXTRA_TODO_ID);
        mToDo= ToDoLab.get(getActivity()).getToDo(toDoId);
    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_todo, container, false);
        wireTitleField(view);
        wireDateButton(view);
        wireSolvedCheckBox(view);
        return  view;
    }




    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        if (requestCode == REQUEST_DATE) {
            Date mDate = (Date)intent.getSerializableExtra(DatePickerFragment.EXTRA_DATE);
            mToDo.setDate(mDate);
           
        }
    }

    public ToDoFragment(){

    }

    
    public static ToDoFragment newInstance(UUID mId) {
        Bundle args = new Bundle();
        args.putSerializable(EXTRA_TODO_ID, mId);

        ToDoFragment fragment = new ToDoFragment();
        fragment.setArguments(args);

        return fragment;
    }

  

    private void wireDateButton(View view) {
        SimpleDateFormat dateFormatter = getSimpleDateFormat();
        mDateButton = (Button)view.findViewById(R.id.toDo_date);
        updateDate(dateFormatter);

        mDateButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                FragmentManager fragmentManager = getFragmentManager();
                DatePickerFragment datePicker = DatePickerFragment.newInstance(mToDo.getDate());
                datePicker.setTargetFragment(ToDoFragment.this, REQUEST_DATE);
                datePicker.show(fragmentManager, DIALOG_DATE);
            }
        });
    }
}

4

4 回答 4

11

您在 Android 5.0 下运行您的应用程序,对吗?我发现在 5.0 下,DatePicker 在其默认的 CalendarView 模式下不会调用 OnDateChanged() 方法,但如果它是 Spinners 模式,它会这样做。如果 DatePicker 显示为微调器,您的代码应该可以工作。

我发现强制 5.0 DatePicker 进入 Spinners 模式的唯一方法是在定义 DatePicker 的 xml 代码中包含以下内容:

android:datePickerMode="spinner"

Lollipop 似乎忽略了任何 android:CalendarViewShown="false" 指令以及 Java 代码中的所有 DatePicker.setCalendarViewShown(false) 调用。datePickerMode xml 指令仅在 API 21 中受支持,但任何以较低 API 级别运行的设备都会忽略它,因此您的代码仍将在旧版本的 Android 上运行。但是,如果您希望 DatePicker 在 5.0 之前的设备上成为微调器,请在您的 xml 代码中保留 CalendarViewShown="false" 指令。

于 2014-12-10T15:14:50.910 回答
1

改用DatePickerDialog

return new DatePickerDialog(getActivity(), this, year, month, day);

您的类声明应如下所示:

public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {

您将需要实现OnDateSet方法:

@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
    mDate = new GregorianCalendar(year, monthOfYear, dayOfMonth).getTime();
    getArguments().putSerializable(EXTRA_DATE, mDate);

    sendResult(Activity.RESULT_OK);
}

或者,您可以将主题设置为 Holo.Light,这似乎支持 DatePicker OnDateChanged 事件。在您的清单文件中:

<application android:label="@string/app_name"
             android:icon="@drawable/ic_launcher"
             android:theme="@android:style/Theme.Holo.Light">

或者您可以降低最低 API 级别,这将默认设置 Holo 主题:

<uses-sdk android:minSdkVersion="15" />
于 2014-11-12T21:49:35.720 回答
1

还有另一种方法可以让它在 5.0 下工作并让你的 DatePicker 保持日历模式。您可以做的是设置收听对话框上的点击更改,并更新您的日期参考。如果您的关闭对话框处理程序有任何机会注意到单击的最后一个按钮是“取消”,那么只需忽略更改...

private String dateString; //last date saved.
    private String clickedDate; //last date clicked on DatePicker
    private DatePicker datePicker;

@Override
    protected void onDialogClosed(boolean shouldSave) {
        if (shouldSave && this.clickedDate != null) {
            updateDate(this.clickedDate);
            this.clickedDate = null;
        }
    }

@Override
    public void onDateChanged(DatePicker view, int year, int month, int day)       {
        Calendar selected = new GregorianCalendar(year, month, day);
        this.clickedDate = formatter().format(selected.getTime());
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
        super.onClick(dialog, which);
        datePicker.clearFocus();
        onDateChanged(datePicker, datePicker.getYear(), datePicker.getMonth(),
                datePicker.getDayOfMonth());
        onDialogClosed(which == DialogInterface.BUTTON_NEGATIVE);
    }

private void updateDate(String s) {
dateString = s;
}

这就是这个想法来自https://github.com/bostonandroid/DatePreference/blob/master/DatePreference/src/org/bostonandroid/datepreference/DatePreference.java

于 2015-06-20T22:01:16.023 回答
0

这是我的答案,可以简单地解决这个问题:

public class MyDatePickerDialog extends DatePickerDialog
{

    public MyDatePickerDialog(Context context, OnDateSetListener callBack, int year,
                              int monthOfYear, int dayOfMonth)
    {
        super(context, callBack, year, monthOfYear, dayOfMonth);
    }


    @TargetApi(11)
    @Override
    public void onClick(DialogInterface dialog, int which)
    {
        getDatePicker().clearFocus();
        super.onClick(dialog, which);
    }
}
于 2016-08-04T07:45:49.177 回答