import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Set;

public class CalendarAdapter extends BaseAdapter {
    private Context context;
    private List<Date> dates;
    private Calendar currentDate;
    private SimpleDateFormat dateFormat = new SimpleDateFormat('dd', Locale.getDefault());
    private Set<Date> markedDates;

    public CalendarAdapter(Context context, List<Date> dates, Calendar currentDate, Set<Date> markedDates) {
        this.context = context;
        this.dates = dates;
        this.currentDate = currentDate;
        this.markedDates = markedDates;
    }

    @Override
    public int getCount() {
        return dates.size();
    }

    @Override
    public Object getItem(int position) {
        return dates.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;

        if (view == null) {
            LayoutInflater inflater = LayoutInflater.from(context);
            view = inflater.inflate(R.layout.calendar_item, parent, false);
        }

        TextView tvDate = view.findViewById(R.id.tv_date);
        Date date = dates.get(position);
        tvDate.setText(dateFormat.format(date));

        if (date.getMonth() != currentDate.getTime().getMonth()) {
            tvDate.setTextColor(Color.GRAY);
        } else {
            tvDate.setTextColor(Color.BLACK);
        }

        if (markedDates.contains(date)) {
            tvDate.setBackgroundResource(R.drawable.circle_background); // 设置已打卡日期的背景样式
        } else {
            tvDate.setBackground(null); // 清除未打卡日期的背景样式
        }

        return view;
    }
}

This CalendarAdapter class extends the BaseAdapter to display a list of dates in a calendar view. Key features include:

  • Date Display: It displays the day of the month (dd) using SimpleDateFormat.
  • Current Date: It allows setting the current date for visual distinction.
  • Marked Dates: It supports marking specific dates (e.g., for events) and provides a customizable background resource for marked dates.
  • Customizable Appearance: You can customize the appearance of dates (e.g., text color) based on their month or marked status.

This adapter is a reusable component for creating calendar views in Android applications. You can integrate it with a ListView or GridView to display the calendar data.

Android Calendar Adapter: Displaying Dates and Marking Events

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

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