You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android开发中CalendarView与Button无法共享selectedDate变量该如何解决?

错误根因

报错的核心原因是变量作用域限制:你定义的selectedDate是OnDateChangeListener的onSelectedDayChange回调方法内的局部变量,仅能在该回调方法内部访问,外部的按钮点击监听器无法跨作用域读取这个变量。

解决方案

最常用的方案是将selectedDate提升为当前Activity的成员变量,修改后代码如下:

// 首先在Activity类的 onCreate 方法外部定义成员变量
private String selectedDate;

protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.calendar_layout);
    mCalendarView = (CalendarView) findViewById(R.id.calendarView);
    btnConfirmCal = (Button) findViewById(R.id.confirmCalendar);
    et_assignName = (EditText) findViewById(R.id.assignName);
    et_assignDesc = (EditText) findViewById(R.id.assignDesc);

    // 可选:初始化时默认赋值为当前日期,避免用户未选日期直接点确认出现空值
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    selectedDate = sdf.format(new Date(mCalendarView.getDate()));

    mCalendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
        @Override
        public void onSelectedDayChange(@NonNull CalendarView calendarView, int year, int month, int dayOfMonth) {
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
            // 直接给成员变量赋值,不要加String类型声明,否则会变成同名局部变量覆盖成员变量
            selectedDate = sdf.format(new Date(mCalendarView.getDate()));
        }
    });
    btnConfirmCal.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                ScheduleList scheduleList = new ScheduleList(et_assignName.getText().toString(),
                        et_assignDesc.getText().toString(), selectedDate);
                Toast.makeText(CalendarActivity.this, scheduleList.toString(), Toast.LENGTH_SHORT).show();
            }
            catch (Exception e) {
                Toast.makeText(CalendarActivity.this, "Error creating schedule", Toast.LENGTH_SHORT).show();
            }
        }
    });
}

注意:不要在onSelectedDayChange里再次写String selectedDate = xxx,否则会重新声明一个同名局部变量,不会给外层的成员变量赋值,问题依然存在。

内容的提问来源于stack exchange,提问作者Irfan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 20:15:04