我正在尝试从http://developer.android.com/guide/topics/ui/controls/pickers.html实施日期选择器,以便在特定日期创建日历活动。我从这个stackoverflow线程中抓取了一些代码:How to add calendar events in Android?将所选日期作为事件传递出去,从而启动日历应用程序。
然而,每次我这样做时,都会传出两个相同的事件,我无法弄清楚原因。
以下是我的主要课程的代码:
package com.example.calendartest;
import java.util.Calendar;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.content.Intent;
public class CalendarTest extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar_test);
}
public void testCalendar(View v) {
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime", cal.getTimeInMillis());
intent.putExtra("allDay", true);
intent.putExtra("rrule", "FREQ=YEARLY");
intent.putExtra("endTime", cal.getTimeInMillis()+60*60*1000);
intent.putExtra("title", "A Test Event from android app");
startActivity(intent);
}
public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
}
创建日期选择器的类:
package com.example.calendartest;
import java.util.Calendar;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.DatePicker;
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener
{
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
Calendar cal = Calendar.getInstance();
cal.set(year, month, day);
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime", cal.getTimeInMillis());
intent.putExtra("allDay", false);
intent.putExtra("endTime", cal.getTimeInMillis()+60*60*1000);
intent.putExtra("title", "A Test Event from android app");
startActivity(intent);
}
}
你会注意到我有一些相同的代码,我一直用它来测试。有两种方法,testCalendar()和showDatePickerDialog()都包含创建事件的代码。在testCalendar()中,使用当前日期和时间创建事件。在showDatePickerDialog()中,使用日期选择器决定的日期和时间创建事件。
我设置了一个调用testCalendar()的按钮和一个调用showDatePickerDialog()的按钮。 testCalendar()按钮正确创建单个事件。 showDatePickerDialog()创建两个。为什么呢?