Calendar String.valueOf()

时间:2015-04-20 18:13:24

标签: java android android-intent calendar

我目前正在尝试创建一个日历应用程序,但我的代码中有些错误,我不能用它。目前我已经制作了一个calendarView并设置了一个onSelectedDateChangeListner并且即时分配了年,月,日的字符串。我将这个值传递给另一个有意图的类,但即使你点击另一个日期,它仍然是这个日期(2015.04.20)。对不起我的英语,这不是我的母语。下面是相关代码:

MainActivity.java:

    mCalendarView.setOnDateChangeListener(new                   CalendarView.OnDateChangeListener() {
        @Override
        public void onSelectedDayChange(CalendarView view, int year, int   month, int dayOfMonth) {
            Calendar c = Calendar.getInstance();
            String calYear = String.valueOf(c.get(Calendar.YEAR));
            String calMonth = String.valueOf(c.get(Calendar.MONTH)+1);
            String calDay = String.valueOf(c.get(Calendar.DAY_OF_MONTH));

            Intent newEvent = new Intent(MainActivity.this, CalendarEvent.class);

            newEvent.putExtra("YEAR", calYear);
            newEvent.putExtra("MONTH", calMonth);
            newEvent.putExtra("DAY", calDay);

            startActivity(newEvent);
        }
    });

CalendarEvent.java

Bundle extras = getIntent().getExtras();
    if(extras != null){
        mYear = extras.getString("YEAR");
        mMonth = extras.getString("MONTH");
        mDay = extras.getString("DAY");
    }

    TextView hello = (TextView)findViewById(R.id.helloworld);
    hello.setText(mYear + "/" + mMonth + "/" + mDay);

1 个答案:

答案 0 :(得分:1)

您传递的是日历c的值,而不是更改日期的值。您可以通过调用" c.set()"

来设置您正在使用的日历实例
mCalendarView.setOnDateChangeListener(new                   CalendarView.OnDateChangeListener() {
    @Override
    public void onSelectedDayChange(CalendarView view, int year, int   month, int dayOfMonth) {
        Calendar c = Calendar.getInstance();
        c.set(year, month, dayOfMonth);
        String calYear = String.valueOf(c.get(Calendar.YEAR));
        String calMonth = String.valueOf(c.get(Calendar.MONTH)+1);
        String calDay = String.valueOf(c.get(Calendar.DAY_OF_MONTH));

        Intent newEvent = new Intent(MainActivity.this, CalendarEvent.class);

        newEvent.putExtra("YEAR", calYear);
        newEvent.putExtra("MONTH", calMonth);
        newEvent.putExtra("DAY", calDay);

        startActivity(newEvent);
    }
});
但是,我认为你要做的就是:

mCalendarView.setOnDateChangeListener(new                   CalendarView.OnDateChangeListener() {
    @Override
    public void onSelectedDayChange(CalendarView view, int year, int   month, int dayOfMonth) {
        Intent newEvent = new Intent(MainActivity.this, CalendarEvent.class);
        newEvent.putExtra("YEAR", String.valueOf(year));
        newEvent.putExtra("MONTH", String.valueOf(month));
        newEvent.putExtra("DAY", String.valueOf(dayOfMonth));
        startActivity(newEvent);
    }
});