一步一步構(gòu)建自己的簡單日歷控件 MySimpleCalendar(篇一)

日歷控件大家應(yīng)該不陌生,github 上面一搜一大堆,但是我們拿到 github 上面的一個(gè)日歷控件,想動手改改功能改改需求,有時(shí)可能會覺得無從下手,(當(dāng)然了,老司機(jī)就忽略我說的 —?!┠敲?,如果想知道一個(gè)日歷控件是如何從無到有構(gòu)建起來的,不妨各位看官快速瀏覽一下我的這篇文章。
文章主要是帶大家一步一步熟悉構(gòu)建的流程,并沒有什么特別酷炫狂拽的效果。

先上一個(gè)效果圖鎮(zhèn)鎮(zhèn)樓。


MySimpleCalendar 控件

一、數(shù)據(jù)準(zhǔn)備

1、實(shí)體類 MyCalendarBean

/**
 * Created by deeson.woo
 */
public class MyCalendarBean {

    private int year;
    private int month;//1-12
    private int day;//1-31

    public MyCalendarBean(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
    }

    public int getYear() {
        return year;
    }

    public int getMonth() {
        return month;
    }

    public int getDay() {
        return day;
    }
}

2、構(gòu)建日期實(shí)體

    /**
     * 構(gòu)建具體一天的對象
     * @param year
     * @param month
     * @param day
     * @return
     */
    public MyCalendarBean generateCalendarBean(int year, int month, int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, day);
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH) + 1;
        day = calendar.get(Calendar.DATE);

        return new MyCalendarBean(year, month, day);
    }

3、打印當(dāng)前月份的所有日期

    /**
     * 獲取當(dāng)前月份的日期列表
     * @param year
     * @param month
     * @return
     */
    public List<MyCalendarBean> getDaysListOfMonth(int year, int month) {

        List<MyCalendarBean> list = new ArrayList<>();

        int daysOfMonth = getDaysOfCertainMonth(year, month);

        for (int i = 0; i < daysOfMonth; i++) {
            MyCalendarBean bean = generateCalendarBean(year, month, i + 1);
            list.add(bean);
        }
        return list;
    }

    /**
     * 獲取具體月份的最大天數(shù)
     *
     * @param year
     * @param month
     * @return
     */
    public static int getDaysOfCertainMonth(int year, int month) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, 1);
        return calendar.getActualMaximum(Calendar.DATE);
    }
//測試打印2018年2月份
printDaysList(getDaysListOfMonth(2018, 2));

2018年2月 = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28 }

二、展示日期

1、將月份的所有日期按照7列展示

自定義ViewGroup(MonthCalendarView)

/**
 * Created by deeson.woo
 * 月份視圖
 */

public class MonthCalendarView extends ViewGroup {

    private int column = 7;

    public MonthCalendarView(Context context) {
        super(context);
    }

    public MonthCalendarView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

}
(1)onMeasure()方法
  • 拿到控件的寬度,分成七份,賦給 item 的寬度和高度
  • 同時(shí)計(jì)算控件所需的高度
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        
        int parentWidth = MeasureSpec.getSize(MeasureSpec.makeMeasureSpec(widthMeasureSpec, MeasureSpec.EXACTLY));

        //將寬度平均分成七份,每個(gè)item的寬高都等于它
        int itemWidth = parentWidth / column;
        int itemHeight = itemWidth;

        int parentHeight = 0;

        for (int i = 0; i < getChildCount(); i++) {
            View childView = getChildAt(i);
            childView.measure(MeasureSpec.makeMeasureSpec(itemWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(itemHeight, MeasureSpec.EXACTLY));
            
            //計(jì)算控件所需的高度
            if (i % column == 0) {
                parentHeight += childView.getMeasuredHeight();
            }
        }

        setMeasuredDimension(parentWidth, parentHeight);
    }
(2)onLayout()方法
  • 按照七列布局的設(shè)計(jì),計(jì)算出每個(gè) item 的 left, top, right, bottom,精確地添加到控件里
    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        for (int i = 0; i < getChildCount(); i++) {
            View itemView = getChildAt(i);
            int columnCount = i % column;
            int rowCount = i / column;

            int itemWidth = itemView.getMeasuredWidth();
            int itemHeight = itemView.getMeasuredHeight();

            left = columnCount * itemWidth;
            top = rowCount * itemHeight;
            right = left + itemWidth;
            bottom = top + itemHeight;
            itemView.layout(left, top, right, bottom);
        }
    }
(3)填充月份日期數(shù)據(jù)
  • 暴露一個(gè)公共方法用于填充數(shù)據(jù)
  • 根據(jù)傳進(jìn)來的年、月,構(gòu)建日期列表
  • 逐一構(gòu)建 itemView,填充到控件里
  • 調(diào)用requestLayout()方法,重新繪制
    public void setMonth(int year, int month) {
        mList = calendarUtils.getDaysListOfMonth(year, month);
        addAllItem();
        requestLayout();
    }

    private void addAllItem() {
        for (int i = 0; i < mList.size(); i++) {
            MyCalendarBean bean = mList.get(i);

            View itemView = generateDateView(bean);
            addViewInLayout(itemView, i, itemView.getLayoutParams(), true);
        }
    }

    private View generateDateView(MyCalendarBean bean) {
        View itemView = LayoutInflater.from(getContext()).inflate(R.layout.item_date_view, null);
        if (bean.isCurrentMonth()) {
            TextView date = itemView.findViewById(R.id.date);
            date.setText(String.valueOf(bean.getDay()));
        }
        return itemView;
    }

把 item_date_view.xml 布局也放出來

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:textSize="14sp"
        android:textColor="@color/text_black"
        />

</RelativeLayout>

2、在布局中使用

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@color/background_white"
    >

    <com.example.deesonwoo.mysimplecalendar.calendar.MonthCalendarView
        android:id="@+id/month_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent">

    </com.example.deesonwoo.mysimplecalendar.calendar.MonthCalendarView>

</LinearLayout>

3、在 MainActivity 中的使用

package com.example.deesonwoo.mysimplecalendar;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.example.deesonwoo.mysimplecalendar.calendar.MonthCalendarView;
import com.example.deesonwoo.mysimplecalendar.calendar.MyCalendarBean;
import com.example.deesonwoo.mysimplecalendar.calendar.MyCalendarUtils;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    MonthCalendarView monthView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        monthView = findViewById(R.id.month_view);
        initCalendar();
    }

    private void initCalendar() {
        //測試顯示2018年3月
        monthView.setMonth(2018, 3);
    }
}

效果展示如下:

2018年3月

4、添加頂部周布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@color/background_white"
    >


    <LinearLayout
        android:id="@+id/week_layout"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:orientation="horizontal"
        android:background="@color/white"
        >

        <TextView
            android:id="@+id/week_00"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="周日"
            android:textColor="@color/text_black"
            android:textSize="12sp" />

        <TextView
            android:id="@+id/week_01"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="周一"
            android:textColor="@color/text_black"
            android:textSize="12sp" />

        <TextView
            android:id="@+id/week_02"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="周二"
            android:textColor="@color/text_black"
            android:textSize="12sp" />

        <TextView
            android:id="@+id/week_03"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="周三"
            android:textColor="@color/text_black"
            android:textSize="12sp" />

        <TextView
            android:id="@+id/week_04"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="周四"
            android:textColor="@color/text_black"
            android:textSize="12sp" />

        <TextView
            android:id="@+id/week_05"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="周五"
            android:textColor="@color/text_black"
            android:textSize="12sp" />

        <TextView
            android:id="@+id/week_06"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="周六"
            android:textColor="@color/text_black"
            android:textSize="12sp" />
    </LinearLayout>

    <com.example.deesonwoo.mysimplecalendar.calendar.MonthCalendarView
        android:id="@+id/month_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent">

    </com.example.deesonwoo.mysimplecalendar.calendar.MonthCalendarView>

</LinearLayout>

效果如下:


2018年3月

5、優(yōu)化日期與星期的對應(yīng)關(guān)系

相信你們已經(jīng)發(fā)現(xiàn),上面展示的效果中,日期與星期并沒有進(jìn)行一一對應(yīng)的排布。接下來,一起我們優(yōu)化一下。

  • 找到當(dāng)前月份第一天對應(yīng)的星期
  • 修改工具類方法 getDaysListOfMonth(), 將前面空缺的上一個(gè)月的日期填充到月份列表中
  • 將上個(gè)月的日期隱藏
(1)在 MyCalendarUtils 工具類中添加下面“獲取具體一天對應(yīng)的星期”的方法
    /**
     * 獲取具體一天對應(yīng)的星期
     *
     * @param year
     * @param month
     * @param day
     * @return 1-7(周日-周六)
     */
    private int getWeekDayOnCertainDate(int year, int month, int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, day);
        return calendar.get(Calendar.DAY_OF_WEEK);
    }
(2)修改 getDaysListOfMonth()方法,將前面空缺的上一個(gè)月的日期填充到月份列表中
    /**
     * 獲取當(dāng)前月份的日期列表
     *
     * @param year
     * @param month
     * @return
     */
    public List<MyCalendarBean> getDaysListOfMonth(int year, int month) {

        List<MyCalendarBean> list = new ArrayList<>();

        int daysOfMonth = getDaysOfCertainMonth(year, month);

        //找到當(dāng)前月第一天的星期,計(jì)算出前面空缺的上個(gè)月的日期個(gè)數(shù),填充到當(dāng)月日期列表中
        int weekDayOfFirstDay = getWeekDayOnCertainDate(year, month, 1);
        int preMonthDays = weekDayOfFirstDay - 1;

        for (int i = preMonthDays; i > 0; i--) {
            MyCalendarBean preMonthBean = generateCalendarBean(year, month, 1 - i);
            list.add(preMonthBean);
        }

        for (int i = 0; i < daysOfMonth; i++) {
            MyCalendarBean monthBean = generateCalendarBean(year, month, i + 1);
            list.add(monthBean);
        }
        return list;
    }

展示效果如下:

2018年3月

顯然,上一個(gè)月的日期在這里是需要區(qū)別展示或者需要隱藏的,不然會給用戶造成視覺上的困擾,這里,我直接做隱藏操作。

(3)給日期實(shí)體類增加當(dāng)前月標(biāo)識,isCurrentMonth,并在構(gòu)建數(shù)據(jù)的時(shí)候給標(biāo)識賦值。

實(shí)體類如下:

/**
 * Created by deeson.woo
 */
public class MyCalendarBean {

    private int year;
    private int month;//1-12
    private int day;//1-31
    private boolean isCurrentMonth = true;//是否為當(dāng)前月份的日期

    public MyCalendarBean(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
    }

    public int getYear() {
        return year;
    }

    public int getMonth() {
        return month;
    }

    public int getDay() {
        return day;
    }

    public boolean isCurrentMonth() {
        return isCurrentMonth;
    }

    public void setCurrentMonth(boolean currentMonth) {
        isCurrentMonth = currentMonth;
    }
}

給標(biāo)識賦值,在 getDaysListOfMonth()中賦值:

    /**
     * 獲取當(dāng)前月份的日期列表
     *
     * @param year
     * @param month
     * @return
     */
    public List<MyCalendarBean> getDaysListOfMonth(int year, int month) {

        List<MyCalendarBean> list = new ArrayList<>();

        int daysOfMonth = getDaysOfCertainMonth(year, month);

        //找到當(dāng)前月第一天的星期,計(jì)算出前面空缺的上個(gè)月的日期個(gè)數(shù),填充到當(dāng)月日期列表中
        int weekDayOfFirstDay = getWeekDayOnCertainDate(year, month, 1);
        int preMonthDays = weekDayOfFirstDay - 1;

        for (int i = preMonthDays; i > 0; i--) {
            MyCalendarBean preMonthBean = generateCalendarBean(year, month, 1 - i);
            preMonthBean.setCurrentMonth(false);
            list.add(preMonthBean);
        }

        for (int i = 0; i < daysOfMonth; i++) {
            MyCalendarBean monthBean = generateCalendarBean(year, month, i + 1);
            monthBean.setCurrentMonth(true);
            list.add(monthBean);
        }
        return list;
    }

最后修改我們自定義月歷類中 generateDateView()方法,不顯示上個(gè)月的日期:

    private View generateDateView(MyCalendarBean bean) {
        View itemView = LayoutInflater.from(getContext()).inflate(R.layout.item_date_view, null);
        if(bean.isCurrentMonth()){
            TextView date = itemView.findViewById(R.id.date);
            date.setText(String.valueOf(bean.getDay()));
        }
        return itemView;
    }

效果如下:


2018年3月

三、持續(xù)優(yōu)化改進(jìn)

1、將靜態(tài)日歷改成動態(tài)可切換顯示

(1)添加頭部布局,用于顯示當(dāng)前月份以及翻頁
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/background_blue"
        >
        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:textSize="20sp"
            android:textColor="@color/white"
            />

        <ImageView
            android:id="@+id/pre_month"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_centerVertical="true"
            android:layout_alignParentLeft="true"
            android:src="@mipmap/btn_preview"
            />
        <ImageView
            android:id="@+id/next_month"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_centerVertical="true"
            android:layout_alignParentRight="true"
            android:src="@mipmap/btn_next"
            />

    </RelativeLayout>
(2)修改自定義月歷類
  • 增加當(dāng)前顯示的年月成員變量

private int mYear, mMonth;

  • 修改構(gòu)造方法和填充數(shù)據(jù)的方法
    public MonthCalendarView(Context context) {
        super(context);
        calendarUtils = new MyCalendarUtils(context);
    }

    public MonthCalendarView(Context context, AttributeSet attrs) {
        super(context, attrs);
        calendarUtils = new MyCalendarUtils(context);
    }

    public void setMonth(int year, int month) {
        this.mYear = year;
        this.mMonth = month;
        invalidateMonth();
    }

    private void invalidateMonth() {
        mList = calendarUtils.getDaysListOfMonth(mYear, mMonth);
        removeAllViews();
        addAllItem();
        requestLayout();
    }
  • 增加前翻頁、后翻頁方法
    /**
     * 展示上一個(gè)月
     */
    public void moveToPreMonth() {
        mMonth -= 1;
        invalidateMonth();
    }

    /**
     * 展示下一個(gè)月
     */
    public void moveToNextMonth() {
        mMonth += 1;
        invalidateMonth();
    }
  • 增加獲取當(dāng)前顯示年月的方法
    public String getCurrentYearAndMonth() {
        return MyCalendarUtils.formatYearAndMonth(mYear, mMonth);
    }
(3)增加工具類方法
    /**
     * 格式化標(biāo)題展示
     * @param year
     * @param month
     * @return
     */
    public static String formatYearAndMonth(int year, int month) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, 1);
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH) + 1;
        return year + "年" + month + "月";
    }

    /**
     * 獲取系統(tǒng)當(dāng)前年月日
     *
     * @return
     */
    public static int[] getNowDayFromSystem() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        return new int[]{cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.DATE)};
    }
(4)修改 MainActivity 類
  • 修改主題樣式
  • 增加頭部布局相關(guān)
  • 默認(rèn)顯示系統(tǒng)當(dāng)前年月
package com.example.deesonwoo.mysimplecalendar;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.deesonwoo.mysimplecalendar.calendar.MonthCalendarView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    MonthCalendarView monthView;
    ImageView btnPreMonth, btnNextMonth;
    TextView title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);
        monthView = findViewById(R.id.month_view);
        initCalendar();
        initTitleView();
        updateTitle();
    }

    private void initCalendar() {
        int[] nowDay = MyCalendarUtils.getNowDayFromSystem();
        monthView.setMonth(nowDay[0], nowDay[1]);
    }

    private void initTitleView() {
        title = findViewById(R.id.title);
        btnPreMonth = findViewById(R.id.pre_month);
        btnNextMonth = findViewById(R.id.next_month);
        btnPreMonth.setOnClickListener(this);
        btnNextMonth.setOnClickListener(this);
    }

    /**
     * 刷新標(biāo)題顯示年月
     */
    private void updateTitle() {
        String yearAndMonth = monthView.getCurrentYearAndMonth();
        title.setText(yearAndMonth);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.pre_month:
                monthView.moveToPreMonth();
                updateTitle();
                break;
            case R.id.next_month:
                monthView.moveToNextMonth();
                updateTitle();
                break;
        }
    }
}

最后顯示的效果如下動圖:


MyCalendar

2、增加高亮顯示系統(tǒng)當(dāng)天日期

  • 增加工具類方法
    /**
     * 判斷是否為系統(tǒng)當(dāng)天
     * @param bean
     * @return
     */
    public static boolean isToday(MyCalendarBean bean) {
        int[] nowDay = getNowDayFromSystem();
        return bean.getYear() == nowDay[0] && bean.getMonth() == nowDay[1] && bean.getDay() == nowDay[2];
    }
  • 修改自定義月歷類構(gòu)建日期的方法
    private View generateDateView(MyCalendarBean bean) {
        View itemView = LayoutInflater.from(getContext()).inflate(R.layout.item_date_view, null);
        if (bean.isCurrentMonth()) {
            TextView date = itemView.findViewById(R.id.date);
            if (MyCalendarUtils.isToday(bean)) {
                date.setBackgroundResource(R.drawable.item_today_bg);
            }
            date.setText(String.valueOf(bean.getDay()));
        }
        return itemView;
    }
  • 系統(tǒng)當(dāng)天高亮顯示的背景 item_today_bg.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid
        android:color="@color/theme_color" />

</shape>

效果如下:


MyCalendar

3、增加點(diǎn)擊日期效果

(1)修改自定義月歷類
  • 修改構(gòu)建日期方法
    private View generateDateView(MyCalendarBean bean) {
        View itemView = LayoutInflater.from(getContext()).inflate(R.layout.item_date_view, null);
        if (bean.isCurrentMonth()) {
            TextView date = itemView.findViewById(R.id.date);
            if (MyCalendarUtils.isToday(bean)) {
                date.setBackgroundResource(R.drawable.item_today_bg);
            } else {
                date.setBackgroundResource(R.drawable.item_pick_up);
            }
            date.setText(String.valueOf(bean.getDay()));
        }
        return itemView;
    }
  • item_pick_up.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_selected="true">
        <shape android:shape="oval">
            <stroke android:color="@color/theme_color" android:width="1dp"/>
        </shape>
    </item>

    <item android:drawable="@android:color/transparent" />
</selector>
  • 增加在主界面點(diǎn)擊的回調(diào)接口方法
    private OnDatePickUpListener onDatePickUpListener;

    public void setOnDatePickUpListener(OnDatePickUpListener onDatePickUpListener) {
        this.onDatePickUpListener = onDatePickUpListener;
    }

    public interface OnDatePickUpListener {
        void onDatePickUp(MyCalendarBean bean);
    }
  • 修改添加日期的方法,增加點(diǎn)擊監(jiān)聽
    private void addAllItem() {
        for (int i = 0; i < mList.size(); i++) {
            final MyCalendarBean bean = mList.get(i);

            final View itemView = generateDateView(bean);
            addViewInLayout(itemView, i, itemView.getLayoutParams(), true);
            final int position = i;
            itemView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (pickUpPosition == position) {
                        return;
                    }

                    if (pickUpPosition != -1) {
                        getChildAt(pickUpPosition).setSelected(false);
                    }
                    itemView.setSelected(true);

                    if (null != onDatePickUpListener) {
                        onDatePickUpListener.onOnDatePickUp(bean);
                    }

                    pickUpPosition = position;
                }
            });
        }
    }
(2)在MainActivity中調(diào)用
    private void initCalendar() {
        int[] nowDay = MyCalendarUtils.getNowDayFromSystem();
        monthView.setMonth(nowDay[0], nowDay[1]);
        monthView.setOnDatePickUpListener(new MonthCalendarView.OnDatePickUpListener() {
            @Override
            public void onDatePickUp(MyCalendarBean bean) {
                Toast.makeText(MainActivity.this, bean.toString(), Toast.LENGTH_SHORT).show();
            }
        });
    }

效果如下動圖:


MyCalendar

四、整合自定義控件

大家可能覺得我們的自定義控件到這里就完結(jié)了,但是young、simple、naive......(瞎bb)
秉著高內(nèi)聚低耦合的原則(再次瞎bb),我將剛剛出現(xiàn)的操作全部整合到一個(gè)控件SimpleCalendarView 中。
直接上代碼吧,也沒幾行,就不做什么解釋了。

1、SimpleCalendarView 類

  • 無非就是將標(biāo)題視圖、星期視圖、月歷視圖逐一添加到自定義SimpleCalendarView 類中,再將相關(guān)接口補(bǔ)上,請看下面代碼
package com.example.deesonwoo.mysimplecalendar.calendar;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.deesonwoo.mysimplecalendar.R;


public class SimpleCalendarView extends LinearLayout implements View.OnClickListener, MonthCalendarView.OnDatePickUpListener {

    private MonthCalendarView monthCalendarView;// 月歷
    private OnDatePickListener onDatePickListener;

    private TextView title;

    public SimpleCalendarView(Context context) {
        this(context, null);
    }

    public SimpleCalendarView(Context context, AttributeSet attrs) {
        super(context, attrs);

        setOrientation(VERTICAL);
        setBackgroundColor(context.getResources().getColor(R.color.white));

        // 年月標(biāo)題、翻頁按鈕
        LayoutParams titleParams = new LayoutParams(LayoutParams.MATCH_PARENT, MyCalendarUtils.dp2px(context, 50));
        RelativeLayout titleLayout = (RelativeLayout) LayoutInflater.from(context).inflate(R.layout.title_layout, null);
        title = titleLayout.findViewById(R.id.title);
        ImageView preMonth = titleLayout.findViewById(R.id.pre_month);
        ImageView nextMonth = titleLayout.findViewById(R.id.next_month);
        preMonth.setOnClickListener(this);
        nextMonth.setOnClickListener(this);
        addView(titleLayout, titleParams);

        //星期布局
        LayoutParams weekParams = new LayoutParams(LayoutParams.MATCH_PARENT, MyCalendarUtils.dp2px(context, 40));
        LinearLayout weekLayout = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.week_layout, null);
        addView(weekLayout, weekParams);

        //月歷視圖
        LayoutParams monthParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        monthCalendarView = new MonthCalendarView(context);
        initCalendarDate();
        monthCalendarView.setOnDatePickUpListener(this);
        addView(monthCalendarView, monthParams);
    }

    private void initCalendarDate() {
        int[] nowDay = MyCalendarUtils.getNowDayFromSystem();
        monthCalendarView.setMonth(nowDay[0], nowDay[1]);
        updateTitle();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.pre_month:
                if (null != monthCalendarView) {
                    monthCalendarView.moveToPreMonth();
                }
                updateTitle();
                break;
            case R.id.next_month:
                if (null != monthCalendarView) {
                    monthCalendarView.moveToNextMonth();
                }
                updateTitle();
                break;
        }
    }

    private void updateTitle() {
        if (null != title && null != monthCalendarView) {
            title.setText(monthCalendarView.getCurrentYearAndMonth());
        }
    }

    @Override
    public void onDatePickUp(MyCalendarBean bean) {
        if (null != onDatePickListener) {
            onDatePickListener.onDatePick(bean);
        }
    }

    public void setOnDatePickListener(OnDatePickListener onDatePickListener) {
        this.onDatePickListener = onDatePickListener;
    }

    public interface OnDatePickListener {
        void onDatePick(MyCalendarBean bean);
    }
}

2、在布局中使用,非常簡單

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/background_white"
    android:orientation="vertical">

    <com.example.deesonwoo.mysimplecalendar.calendar.SimpleCalendarView
        android:id="@+id/calendarView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </com.example.deesonwoo.mysimplecalendar.calendar.SimpleCalendarView>

</LinearLayout>

3、在MainActivity 中調(diào)用

package com.example.deesonwoo.mysimplecalendar;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.example.deesonwoo.mysimplecalendar.calendar.MyCalendarBean;
import com.example.deesonwoo.mysimplecalendar.calendar.SimpleCalendarView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);

        SimpleCalendarView calendarView = findViewById(R.id.calendarView);
        calendarView.setOnDatePickListener(new SimpleCalendarView.OnDatePickListener() {
            @Override
            public void onDatePick(MyCalendarBean bean) {
                Toast.makeText(MainActivity.this, bean.toString(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}

最后的效果就是文章開頭的動態(tài)圖。

五、后續(xù)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容