CalendarView getDate method returns current date, not selected date… What am I doing wrong?

混江龙づ霸主 提交于 2019-12-11 03:21:26

问题


My calendarView fails to return the selected date, instead returning some default that always points to today.

I am of course changing the date selected in my calendar, and it indeed displays as having changed. I tried inspecting the view in debug mode, but didn't find anything.

I am running this in a simulator, not on a real phone... Should I modify some settings? Am I missing something important? Because it really is confusing that I'm not getting the selected date, but the current one.

<CalendarView
                            android:id="@+id/view_calendar_create_event_date"
                            android:layout_width="wrap_content"
                            android:layout_height="0dp"
                            android:layout_weight="1" />

This is called from the event listener

protected void createEvent(View view){
        TextView eventNameView = (TextView) this.findViewById(R.id.createEventNameInput);
        String eventName = eventNameView.getEditableText().toString();

        CalendarView eventOccursOnView = (CalendarView) this.findViewById(R.id.view_calendar_create_event_date);
        long eventOccursOn = eventOccursOnView.getDate();
        Date temporary = new Date(eventOccursOn);

        Event newEvent = new Event(eventName, "", 0, 0, eventOccursOn);
        newEvent.save(view.getContext());
    }

and this is how I'm setting my event listener

saveButton.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                // Create the event
                EventDetailsActivity.this.createEvent(view);

                // Notify the user
                Snackbar.make(view, "Successfully created a new event!", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();

                // Return to the previous activity
                finish();
            }
        });

回答1:


You need to implement setOnDateChangeListener

long eventOccursOn;

eventOccursOnView.setOnDateChangeListener(new OnDateChangeListener() {
    //show the selected date as a toast
    @Override
    public void onSelectedDayChange(CalendarView view, int year, int month, int day) {
        Toast.makeText(getApplicationContext(), day + "/" + month + "/" + year, Toast.LENGTH_LONG).show();
        Calendar c = Calendar.getInstance();
        c.set(year, month, day);
        eventOccursOn = c.getTimeInMillis(); //this is what you want to use later
    }
 });


来源:https://stackoverflow.com/questions/46144150/calendarview-getdate-method-returns-current-date-not-selected-date-what-am-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!