Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 專案實戰(二十九):酒店預定的日期區間選擇

編輯:關於 Android 開發

先看需求效果圖:

   

需求拆解

1、同時顯示當月與下個月的日曆(可自行擴展到更多月份)。

2、第一次點擊選「開始日期」,再一次點擊選「結束日期」:

(1)若起訖同一天

(2)若結束日晚於開始日,且兩者不同

(3)若結束日早於開始日,則把當前點擊日重設為新的「開始日期」,並清空結束日。

3、選好的起訖日期要回顯在上方

難點

1、取得當月與下月的日曆資訊:一個月有幾天、每天的星期幾。

2、判斷每一天與「開始/結束日期」的關係,據此套用不同的背景色。

技術儲備

1、初談 RecyclerView(近乎完美替代 ListView、GridView)。
2、Android 專案實戰(十三):初談 EventBus。

-----------------------------------------------------------------------------------------------------------------------

實現思路

1、外層一個 RecyclerView 負責顯示日曆,每個 item 對應「一個月」,以下簡稱外部 RecyclerView。

2、外部 RecyclerView 的每個 item 內部再放一個 RecyclerView,用來鋪該月的每一天,以下簡稱內部 RecyclerView。

3、為內部 RecyclerView 的 item 掛上點擊監聽,依「開始/結束/中間」三種身分套用對應的背景。

程式碼實現

1、程式碼框架總覽

2、實體類

(1)月份類,外部 RecyclerView 的資料來源

/** 代表日曆上的每一個月份 */
public class MonthTimeEntity {
    private int year;  // 該月份屬於哪一年
    private int month; // 該月是哪一個月份

    public MonthTimeEntity(int year, int month) {
        this.year = year;
        this.month = month;
    }
    public int getYear() { return year; }
    public void setYear(int year) { this.year = year; }
    public int getMonth() { return month; }
    public void setMonth(int month) { this.month = month; }
}

(2)日期類,內部 RecyclerView 的資料來源

/** 日曆中每一個月中的每一個天數 */
public class DayTimeEntity {
    private int day;           // 日期,幾號
    private int month;         // 屬於的月份
    private int year;          // 屬於的年份
    private int monthPosition; // 屬於的月份在外層列表中的 position(注意不是月份數字)
    private int dayPosition;   // 屬於的日期在該月(內層列表)中的位置

    public DayTimeEntity(int day, int month, int year, int monthPosition) {
        this.day = day;
        this.month = month;
        this.year = year;
        this.monthPosition = monthPosition;
    }
    public int getDay() { return day; }
    public void setDay(int day) { this.day = day; }
    public int getMonth() { return month; }
    public void setMonth(int month) { this.month = month; }
    public int getYear() { return year; }
    public void setYear(int year) { this.year = year; }
    public int getMonthPosition() { return monthPosition; }
    public void setMonthPosition(int monthPosition) { this.monthPosition = monthPosition; }
    public int getDayPosition() { return dayPosition; }
    public void setDayPosition(int dayPosition) { this.dayPosition = dayPosition; }
}

(3)更新類,用於選擇起訖日期後通知刷新

/** 用於 EventBus 發送消息 */
public class UpdataCalendar { }

3、主要實現

(1)主介面佈局:日曆用一個 RecyclerView 顯示,每個 item 顯示一個月的所有天數。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" >
    <!--標題欄-->
    <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"
        android:padding="6dp" android:background="@color/white" >
        <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:text="預定日期" android:layout_centerInParent="true" android:textSize="20sp" />
    </RelativeLayout>
    <ImageView android:layout_width="match_parent" android:layout_height="1dp" android:background="#d9d9d9" />
    <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"
        android:background="#f2f4f7" android:paddingTop="20dp" >
        <TextView android:id="@+id/plan_time_txt_start" android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:text="開始\n時間"
            android:layout_alignParentLeft="true" android:layout_marginLeft="87dp"
            android:background="@mipmap/bg_white_circle" android:gravity="center" />
        <TextView android:id="@+id/plan_time_txt_stop" android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:text="結束\n時間"
            android:layout_alignParentRight="true" android:layout_marginRight="74dp"
            android:background="@mipmap/bg_white_circle" android:gravity="center" />
    </RelativeLayout>
    <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"
        android:orientation="horizontal" android:background="#f2f4f7"
        android:padding="20dp" >
        <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="S" android:gravity="center" />
        <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="M" android:gravity="center" />
        <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="T" android:gravity="center" />
        <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="W" android:gravity="center" />
        <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="T" android:gravity="center" />
        <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="F" android:gravity="center" />
        <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="S" android:gravity="center" />
    </LinearLayout>
    <android.support.v7.widget.RecyclerView android:id="@+id/plan_time_calender"
        android:layout_width="match_parent" android:layout_height="match_parent"
        android:background="@color/white" android:paddingLeft="20dp" android:paddingRight="20dp" >
    </android.support.v7.widget.RecyclerView>
</LinearLayout>

(2)外部 RecyclerView 的 ViewHolder:一個 TextView 顯示年月,一個 RecyclerView 鋪該月天數。

public class MonthTimeViewHolder extends RecyclerView.ViewHolder {
    public TextView plan_time_txt_month;        // 文本,例如 2018-1
    public RecyclerView plan_time_recycler_content; // 月份裡面詳細日期的列表
    public Context context;

    public MonthTimeViewHolder(View itemView, Context context) {
        super(itemView);
        this.context = context;
        plan_time_recycler_content = (RecyclerView) itemView.findViewById(R.id.plan_time_recycler_content);
        plan_time_txt_month = (TextView) itemView.findViewById(R.id.plan_time_txt_month);
        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(context,
                7,                     // 每行顯示 7 項
                GridLayoutManager.VERTICAL,
                false);
        plan_time_recycler_content.setLayoutManager(layoutManager);
    }
}

(3)外部 RecyclerView 的 item 佈局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content">
    <TextView android:id="@+id/plan_time_txt_month" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:textColor="@color/blue" android:textSize="16sp"
        android:text="Aug 2017" android:layout_marginTop="10dp" android:layout_marginLeft="20dp"
        android:layout_marginBottom="10dp" />
    <android.support.v7.widget.RecyclerView android:id="@+id/plan_time_recycler_content"
        android:layout_width="match_parent" android:layout_height="wrap_content" >
    </android.support.v7.widget.RecyclerView>
</LinearLayout>

(4)Activity

public class MonthTimeActivity extends Activity {
    private TextView startTime;  // 開始時間
    private TextView stopTime;   // 結束時間
    private RecyclerView reycycler;
    private MonthTimeAdapter adapter;
    private ArrayList<MonthTimeEntity> datas;

    public static DayTimeEntity startDay; // 開始日期
    public static DayTimeEntity stopDay;  // 結束日期

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initData();
        EventBus.getDefault().register(this);
    }

    private void initData() {
        startDay = new DayTimeEntity(0, 0, 0, 0);
        stopDay = new DayTimeEntity(-1, -1, -1, -1); // 這裡的 -1 不是隨便設的,後面會用到
        datas = new ArrayList<>();
        Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH) + 1;
        c.add(Calendar.MONTH, 1);
        int nextYear = c.get(Calendar.YEAR);
        int nextMonth = c.get(Calendar.MONTH) + 1;
        datas.add(new MonthTimeEntity(year, month));       // 當前月份
        datas.add(new MonthTimeEntity(nextYear, nextMonth)); // 下個月
        adapter = new MonthTimeAdapter(datas, MonthTimeActivity.this);
        reycycler.setAdapter(adapter);
    }

    private void initView() {
        startTime = (TextView) findViewById(R.id.plan_time_txt_start);
        stopTime = (TextView) findViewById(R.id.plan_time_txt_stop);
        reycycler = (RecyclerView) findViewById(R.id.plan_time_calender);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this,
                LinearLayout.VERTICAL, false);
        reycycler.setLayoutManager(layoutManager);
    }

    public void onEventMainThread(UpdataCalendar event) {
        adapter.notifyDataSetChanged();
        startTime.setText(startDay.getMonth() + "月" + startDay.getDay() + "日" + "\n");
        if (stopDay.getDay() == -1) {
            stopTime.setText("結束" + "\n" + "時間");
        } else {
            stopTime.setText(stopDay.getMonth() + "月" + stopDay.getDay() + "日" + "\n");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}

兩個關鍵點:一是用一對靜態變數標記起訖日期,方便和每個格子比對以決定背景色;二是資料初始化時,把 stopDay 的四個欄位都設為 -1,作為「尚未選擇結束日」的哨兵值。

(5)外部 RecyclerView 的 Adapter

public class MonthTimeAdapter extends RecyclerView.Adapter<MonthTimeViewHolder> {
    private ArrayList<MonthTimeEntity> datas;
    private Context context;

    public MonthTimeAdapter(ArrayList<MonthTimeEntity> datas, Context context) {
        this.datas = datas;
        this.context = context;
    }

    @Override
    public MonthTimeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // 進入此方法必然沒有可複用項,RecyclerView 以 Holder 檢查複用
        View v = LayoutInflater.from(context).inflate(R.layout.item_recycler_timeplan, parent, false);
        return new MonthTimeViewHolder(v, context);
    }

    @Override
    public void onBindViewHolder(MonthTimeViewHolder holder, int position) {
        MonthTimeEntity monthTimeEntity = datas.get(position);
        holder.plan_time_txt_month.setText(monthTimeEntity.getYear() + "--" + monthTimeEntity.getMonth());

        // 得到該月份的第一天
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, monthTimeEntity.getYear());   // 指定年份
        calendar.set(Calendar.MONTH, monthTimeEntity.getMonth() - 1); // Java 月份從 0 開始
        calendar.set(Calendar.DAY_OF_MONTH, 1);                   // 指定天數
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);       // 該月 1 號是星期幾

        ArrayList<DayTimeEntity> days = new ArrayList<DayTimeEntity>();
        for (int i = 0; i < dayOfWeek - 1; i++) {
            // 填充空白天數:若 1 號是星期三,週日~週二的位置留白
            // days.add(new DayTimeEntity(0, ...));
        }
        calendar.add(Calendar.MONTH, 1);  // 加一個月,變為下月 1 號
        calendar.add(Calendar.DATE, -1);  // 減一天,變為當月最後一天
        for (int i = 1; i <= calendar.get(Calendar.DAY_OF_MONTH); i++) {
            // 從 1 號到當月最後一天全部加入資料源
            days.add(new DayTimeEntity(i, monthTimeEntity.getMonth(),
                    monthTimeEntity.getYear(), position));
        }
        holder.plan_time_recycler_content.setAdapter(new DayTimeAdapter(days, context));
    }

    @Override
    public int getItemCount() {
        return datas != null ? datas.size() : 0;
    }
}

這裡最關鍵的兩段:先用 DAY_OF_WEEK 補出「空白格」,讓 1 號落在正確的星期欄位(getDay() == 0 即代表空格,不可點擊);再用「加一月、減一天」的技巧取得當月最後一天,把整月的日期灌進內部 RecyclerView。

以上是外層(每個 item 一個月)的程式碼。

-------------------------------------------------------------------------------------------------

(6)內部 RecyclerView 的 item 佈局:只有一個 TextView 顯示幾號。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content"
    android:layout_marginTop="2dp" android:layout_marginBottom="2dp"
    android:paddingTop="6dp" android:paddingBottom="6dp" android:id="@+id/select_ly_day" >
    <TextView android:id="@+id/select_txt_day" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="" android:layout_gravity="center"
        android:gravity="center" />
</LinearLayout>

(7)內部 RecyclerView 的 ViewHolder

public class DayTimeViewHolder extends RecyclerView.ViewHolder {
    public TextView select_txt_day;    // 日期文本
    public LinearLayout select_ly_day; // 父容器,用於點擊日期

    public DayTimeViewHolder(View itemView) {
        super(itemView);
        select_ly_day = (LinearLayout) itemView.findViewById(R.id.select_ly_day);
        select_txt_day = (TextView) itemView.findViewById(R.id.select_txt_day);
    }
}

(8)內部 RecyclerView 的 Adapter

public class DayTimeAdapter extends RecyclerView.Adapter<DayTimeViewHolder> {
    private ArrayList<DayTimeEntity> days;
    private Context context;

    public DayTimeAdapter(ArrayList<DayTimeEntity> days, Context context) {
        this.days = days;
        this.context = context;
    }

    @Override
    public DayTimeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(context).inflate(R.layout.item_recycler_selectday, parent, false);
        return new DayTimeViewHolder(v);
    }

    @Override
    public void onBindViewHolder(final DayTimeViewHolder holder, final int position) {
        final DayTimeEntity dayTimeEntity = days.get(position);

        // 空白格不可點擊(getDay() == 0)
        if (dayTimeEntity.getDay() != 0) {
            holder.select_txt_day.setText(dayTimeEntity.getDay() + "");
            holder.select_ly_day.setEnabled(true);
        } else {
            holder.select_ly_day.setEnabled(false);
        }

        holder.select_ly_day.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (MonthTimeActivity.startDay.getYear() == 0) {
                    // 第一次點擊:記為開始日期(預設 0,0,0,0)
                    assignStart(dayTimeEntity, position);
                } else if (MonthTimeActivity.startDay.getYear() > 0
                        && MonthTimeActivity.stopDay.getYear() == -1) {
                    // 第二次點擊:候選結束日期(預設 -1 表示尚未選)
                    if (isAfterOrEqual(dayTimeEntity)) {
                        assignStop(dayTimeEntity, position);
                    } else {
                        // 早於開始日 → 重設為新的開始日,結束日清空
                        assignStart(dayTimeEntity, position);
                        resetStop();
                    }
                } else {
                    // 第三次起:重新選開始
                    assignStart(dayTimeEntity, position);
                    resetStop();
                }
                // 發消息刷新,重算各日期背景色
                EventBus.getDefault().post(new UpdataCalendar());
            }
        });

        // 依「開始 / 結束 / 中間」套用背景
        if (same(MonthTimeActivity.startDay, dayTimeEntity)
                && same(MonthTimeActivity.stopDay, dayTimeEntity)) {
            holder.select_ly_day.setBackgroundResource(R.drawable.bg_time_startstop); // 起訖同一天
        } else if (same(MonthTimeActivity.startDay, dayTimeEntity)) {
            holder.select_ly_day.setBackgroundResource(R.drawable.bg_time_start);
        } else if (same(MonthTimeActivity.stopDay, dayTimeEntity)) {
            holder.select_ly_day.setBackgroundResource(R.drawable.bg_time_stop);
        } else if (dayTimeEntity.getMonthPosition() >= MonthTimeActivity.startDay.getMonthPosition()
                && dayTimeEntity.getMonthPosition() <= MonthTimeActivity.stopDay.getMonthPosition()) {
            // 落在起訖區間內
            if (dayTimeEntity.getMonthPosition() == MonthTimeActivity.startDay.getMonthPosition()
                    && dayTimeEntity.getMonthPosition() == MonthTimeActivity.stopDay.getMonthPosition()) {
                // 起訖同一個月
                if (dayTimeEntity.getDay() > MonthTimeActivity.startDay.getDay()
                        && dayTimeEntity.getDay() < MonthTimeActivity.stopDay.getDay()) {
                    holder.select_ly_day.setBackgroundResource(R.color.blue);
                } else {
                    holder.select_ly_day.setBackgroundResource(R.color.white);
                }
            } else if (MonthTimeActivity.startDay.getMonthPosition()
                    != MonthTimeActivity.stopDay.getMonthPosition()) {
                // 起訖跨月
                if (dayTimeEntity.getMonthPosition() == MonthTimeActivity.startDay.getMonthPosition()
                        && dayTimeEntity.getDay() > MonthTimeActivity.startDay.getDay()) {
                    holder.select_ly_day.setBackgroundResource(R.color.blue); // 起始月:之後的天數
                } else if (dayTimeEntity.getMonthPosition() == MonthTimeActivity.stopDay.getMonthPosition()
                        && dayTimeEntity.getDay() < MonthTimeActivity.stopDay.getDay()) {
                    holder.select_ly_day.setBackgroundResource(R.color.blue); // 結束月:之前的天數
                } else if (dayTimeEntity.getMonthPosition() != MonthTimeActivity.startDay.getMonthPosition()
                        && dayTimeEntity.getMonthPosition() != MonthTimeActivity.stopDay.getMonthPosition()) {
                    holder.select_ly_day.setBackgroundResource(R.color.blue); // 中間整月
                } else {
                    holder.select_ly_day.setBackgroundResource(R.color.white);
                }
            }
        } else {
            holder.select_ly_day.setBackgroundResource(R.color.white);
        }
    }

    @Override
    public int getItemCount() {
        return days != null ? days.size() : 0;
    }

    /** 年、月、日三者是否相同 */
    private boolean same(DayTimeEntity a, DayTimeEntity b) {
        return a.getYear() == b.getYear() && a.getMonth() == b.getMonth()
                && a.getDay() == b.getDay();
    }

    /** 候選日是否為開始日當天或之後 */
    private boolean isAfterOrEqual(DayTimeEntity d) {
        DayTimeEntity s = MonthTimeActivity.startDay;
        if (d.getYear() > s.getYear()) return true;
        if (d.getYear() < s.getYear()) return false;
        if (d.getMonth() > s.getMonth()) return true;
        if (d.getMonth() < s.getMonth()) return false;
        return d.getDay() >= s.getDay();
    }

    private void assignStart(DayTimeEntity d, int position) {
        DayTimeEntity s = MonthTimeActivity.startDay;
        s.setDay(d.getDay());
        s.setMonth(d.getMonth());
        s.setYear(d.getYear());
        s.setMonthPosition(d.getMonthPosition());
        s.setDayPosition(position);
    }

    private void assignStop(DayTimeEntity d, int position) {
        DayTimeEntity e = MonthTimeActivity.stopDay;
        e.setDay(d.getDay());
        e.setMonth(d.getMonth());
        e.setYear(d.getYear());
        e.setMonthPosition(d.getMonthPosition());
        e.setDayPosition(position);
    }

    private void resetStop() {
        DayTimeEntity e = MonthTimeActivity.stopDay;
        e.setDay(-1); e.setMonth(-1); e.setYear(-1);
        e.setMonthPosition(-1); e.setDayPosition(-1);
    }
}

原文這裡把「年份/月份/日期」的比較展開成十幾個 else-if,逻辑雖然直白,但冗長且容易看漏分支。上面把它收斂成 isAfterOrEqual、same、assignStart/assignStop/resetStop 幾個小方法,行為一致而可讀性高得多——這也是重構時最值得優先處理的一類重複程式碼。

三個核心點:

1、getDay() 為 0 的空格子直接 disable,點不動。

2、點擊時依「第一次/第二次/第三次」以及是否合法(不早於開始日)決定賦值或重置。

3、每次點擊後用 EventBus 發一個 UpdataCalendar,讓外層 Activity 刷新 adapter,重算所有格子的背景。

(9)資源檔

drawable:bg_time_start.xml(開始日,只有左側圓角)

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android">
    <!--開始日期的背景-->
    <corners android:bottomLeftRadius="20dp" android:topLeftRadius="20dp" ></corners>
    <solid android:color="#4ab7e8"></solid>
</shape>

bg_time_stop.xml(結束日,只有右側圓角)

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android">
    <!--結束日期的背景-->
    <corners android:bottomRightRadius="20dp" android:topRightRadius="20dp" ></corners>
    <solid android:color="#4ab7e8"></solid>
</shape>

bg_time_startstop.xml(起訖同一天,四個角都圓)

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android">
    <!--開始日期和結束日期同一天的背景-->
    <corners android:radius="20dp" ></corners>
    <solid android:color="#4ab7e8"></solid>
</shape>

colors.xml

<color name="white">#fff</color>
<color name="blue">#4ab7e8</color>

--------------------------------------------------------------------------------------------------------------------------

源碼下載

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved