Android 日历视图标记打卡日期实现方法

在 Android 应用中,如果需要在日历视图中标记用户打卡的日期,可以使用 setMarkedDates() 方法。以下是如何实现的:

  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();

        // 将成功打卡的日期保存到列表中
        markedDates.add(currentDate);
        calendarView.setMarkedDates(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();

    // 初始化成功打卡的日期列表
    List<CheckIn> checkIns = appDatabase.checkInDao().getAllCheckIns();
    for (CheckIn checkIn : checkIns) {
        markedDates.add(checkIn.getDate());
    }
    calendarView.setMarkedDates(markedDates);

    // 其他代码...
}

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

Android 日历视图标记打卡日期实现方法

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

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