以下是正确的实现方式:

  1. onCreate()方法中,找到以下代码:
checkInButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        String currentDate = getCurrentDate();
        String currentTime = getCurrentTime();
        CheckIn checkIn = new CheckIn(currentDate, currentTime);
        appDatabase.checkInDao().insert(checkIn);
        Toast.makeText(com.example.pg_helper.ClockActivity.this, '打卡成功:' + currentDate + ' ' + currentTime, Toast.LENGTH_SHORT).show();

        int checkInCount = appDatabase.checkInDao().getCheckInCount();
        //   Toast.makeText(com.example.pg_helper.ClockActivity.this, '已打卡次数:' + checkInCount, Toast.LENGTH_SHORT).show();

    }
});
  1. onClick()方法中,获取当前日期,并将成功打卡的日期保存到一个列表中。修改后的代码如下:
checkInButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        String currentDate = getCurrentDate();
        String currentTime = getCurrentTime();
        CheckIn checkIn = new CheckIn(currentDate, currentTime);
        appDatabase.checkInDao().insert(checkIn);
        Toast.makeText(com.example.pg_helper.ClockActivity.this, '打卡成功:' + currentDate + ' ' + currentTime, Toast.LENGTH_SHORT).show();

        int checkInCount = appDatabase.checkInDao().getCheckInCount();
        //   Toast.makeText(com.example.pg_helper.ClockActivity.this, '已打卡次数:' + checkInCount, Toast.LENGTH_SHORT).show();

        // 将成功打卡的日期保存到列表中
        List<String> checkInDates = appDatabase.checkInDao().getCheckInDates();
        calendarView.setMarkedDates(checkInDates);
    }
});
  1. CalendarView的布局文件中,添加一个自定义属性markedDates,用于标记成功打卡的日期。修改后的布局文件如下:
<CalendarView
    android:id="@+id/calendarView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:markedDates="@{viewModel.markedDates}" />
  1. ClockActivity类中,添加一个markedDates属性,并在onCreate()方法中初始化该属性:
private List<String> markedDates = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.oclock);
    InitviewS();
    countdownTextView = findViewById(R.id.countdownTextView);
    calendarView = findViewById(R.id.calendarView);
    checkInButton = findViewById(R.id.checkInButton);
    appDatabase = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "check-in-db")
            .allowMainThreadQueries()
            .build();

    // 初始化成功打卡的日期列表
    markedDates = appDatabase.checkInDao().getCheckInDates();
    calendarView.setMarkedDates(markedDates);

    // 其他代码...
}

通过以上修改,成功打卡的日期将会在日历视图中加上星号。

Android 日历视图标记成功打卡日期

原文地址: https://www.cveoy.top/t/topic/bPDN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录