編輯:關於 Android 程式設計
月歷很常見,但有些場景(例如按周查看數據、日程安排)用「周歷」更合適:一屏展示七天,左右滑動切換上一周/下一周。本文記錄一個可滑動的周歷實現,核心由四個文件組成。
main.xml:顶部星期標題欄 + 中間的 ViewFlipper(承載 GridView)+ 底部日期顯示;item_calendar.xml:格子裡的日期 TextView;SpecialCalendar.java:日期工具類,負責閏年、天數、星期幾的計算;DateAdapter.java:把「某一週的七天」渲染成七個格子。
<RelativeLayout 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" >
<!-- 星期標題欄 -->
<LinearLayout
android:id="@+id/ll_week"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="周日" />
<!-- 周一至周六同理,各佔一份 weight -->
</LinearLayout>
<!-- 承載每一週的容器,用於實現切換動畫 -->
<ViewFlipper
android:id="@+id/flipper1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/ll_week" />
<TextView
android:id="@+id/tv_date"
android:layout_below="@id/flipper1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="2014年5月6日"
android:gravity="center" />
</RelativeLayout>
這裡有個值得注意的細節:七個 TextView 都用 layout_width="match_parent" 搭配 layout_weight="1",效果是等分屏幕。若寫成 wrap_content,各標題寬度會因文字而異,對不齊。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="@+id/tv_calendar"
android:layout_width="30dp"
android:layout_height="30dp"
android:gravity="center" />
</LinearLayout>
</LinearLayout>
這個類不依賴任何 Android API,純邏輯計算,也便於單獨測試:
public class SpecialCalendar {
private int daysOfMonth = 0; // 某月的天數
private int dayOfWeek = 0; // 某一天是星期幾
/** 判斷是否為閏年 */
public boolean isLeapYear(int year) {
if (year % 100 == 0 && year % 400 == 0) {
return true;
} else if (year % 100 != 0 && year % 4 == 0) {
return true;
}
return false;
}
/** 得到某月有多少天 */
public int getDaysOfMonth(boolean isLeapyear, int month) {
switch (month) {
case 1: case 3: case 5: case 7:
case 8: case 10: case 12:
daysOfMonth = 31;
break;
case 4: case 6: case 9: case 11:
daysOfMonth = 30;
break;
case 2:
daysOfMonth = isLeapyear ? 29 : 28;
break;
}
return daysOfMonth;
}
/** 指定某年某月的第一天是星期幾(注意減 1 的原因) */
public int getWeekdayOfMonth(int year, int month) {
Calendar cal = Calendar.getInstance();
cal.set(year, month - 1, 1);
// Calendar.DAY_OF_WEEK 中週日是 1,這裡減 1 變成「週日 = 0」的約定
dayOfWeek = cal.get(Calendar.DAY_OF_WEEK) - 1;
return dayOfWeek;
}
/** 指定某年某月某日是星期幾 */
public int getWeekDayOfLastMonth(int year, int month, int day) {
Calendar cal = Calendar.getInstance();
cal.set(year, month - 1, day);
return cal.get(Calendar.DAY_OF_WEEK) - 1;
}
}
這裡有兩個坑要記住:Calendar 的 month 從 0 開始,所以傳入時要 month - 1;DAY_OF_WEEK 返回 1~7(週日為 1),而我們的標題欄是「週日排第一」,所以統一減 1,讓 0 代表週日。
「某月有幾週」不能用固定公式,因為它取決於該月 1 號是星期幾:
public int getWeeksOfMonth() {
int preMonthRelax = 0;
if (dayOfWeek != 7) { // 若 1 號正好是週日,前面不需要補位
preMonthRelax = dayOfWeek;
}
if ((daysOfMonth + preMonthRelax) % 7 == 0) {
weeksOfMonth = (daysOfMonth + preMonthRelax) / 7;
} else {
weeksOfMonth = (daysOfMonth + preMonthRelax) / 7 + 1;
}
return weeksOfMonth;
}
而「某一天屬於本月第幾週」,則需要按 similar 邏輯推導:
if (dayOfWeek == 7) {
week_c = day_c / 7 + 1;
} else {
if (day_c <= (7 - dayOfWeek)) {
week_c = 1; // 還在第一週
} else {
if ((day_c - (7 - dayOfWeek)) % 7 == 0) {
week_c = (day_c - (7 - dayOfWeek)) / 7 + 1;
} else {
week_c = (day_c - (7 - dayOfWeek)) / 7 + 2;
}
}
}
這段邏輯建議畫一張月歷草稿紙驗證幾個邊界:1 號是週日的月份、2 月、以及 31 天的月份。
DateAdapter 的核心是 getWeek()——根據「年、月、第幾週」算出七天的日期數字,其中第一週的空白位置要填上月的最後幾天:
public void getWeek(int year, int month, int week) {
for (int i = 0; i < dayNumber.length; i++) {
if (dayOfWeek == 7) {
// 1 號恰好是週日,整齊排列
dayNumber[i] = String.valueOf((i + 1) + 7 * (week - 1));
} else {
if (week == 1) {
if (i < dayOfWeek) {
// 用上月最後幾天補位
dayNumber[i] = String.valueOf(lastDaysOfMonth - (dayOfWeek - (i + 1)));
} else {
dayNumber[i] = String.valueOf(i - dayOfWeek + 1);
}
} else {
dayNumber[i] = String.valueOf((7 - dayOfWeek + 1 + i) + 7 * (week - 2));
}
}
}
}
選中態通過 clickTemp 記錄,在 getView 中切換背景:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.item_calendar, null);
}
TextView tvCalendar = (TextView) convertView.findViewById(R.id.tv_calendar);
tvCalendar.setText(dayNumber[position]);
if (clickTemp == position) {
tvCalendar.setSelected(true);
tvCalendar.setTextColor(Color.WHITE);
tvCalendar.setBackgroundResource(R.drawable.circle_message);
} else {
tvCalendar.setSelected(false);
tvCalendar.setTextColor(Color.BLACK);
tvCalendar.setBackgroundColor(Color.TRANSPARENT);
}
return convertView;
}
MainActivity 實現 OnGestureListener,在 onFling 中判斷水平位移方向,配合 ViewFlipper 播放左右推入動畫:
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
int gvFlag = 0;
if (e1.getX() - e2.getX() > 80) { // 向左滑 → 下一週
addGridView();
currentWeek++;
getCurrent();
dateAdapter = new DateAdapter(this, getResources(), currentYear, currentMonth,
currentWeek, currentNum, selectPostion, currentWeek == 1);
dayNumbers = dateAdapter.getDayNumbers();
gridView.setAdapter(dateAdapter);
tvDate.setText(dateAdapter.getCurrentYear(selectPostion) + "年"
+ dateAdapter.getCurrentMonth(selectPostion) + "月"
+ dayNumbers[selectPostion] + "日");
gvFlag++;
flipper1.addView(gridView, gvFlag);
dateAdapter.setSeclection(selectPostion);
flipper1.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.push_left_in));
flipper1.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.push_left_out));
flipper1.showNext();
flipper1.removeViewAt(0); // 移除舊視圖,防止 ViewFlipper 無限膨脹
return true;
} else if (e1.getX() - e2.getX() < -80) { // 向右滑 → 上一週
// 邏輯對稱,動畫換成 push_right_in / push_right_out,並調用 showPrevious()
return true;
}
return false;
}
跨月、跨年的處理集中在 getCurrent() 中:週序超出當月總週數就進到下一月,小於 1 就退回上一月,並同步更新 currentNum。
這裡必須強調一個容易忘的收尾:每執行一次 flipper1.addView() 都要跟著 removeViewAt(0)。ViewFlipper 不會自動淘汰舊子視圖,只加不刪會導致內存持續上漲,滑個幾十次就明顯卡頓。
這個實現思路清晰、易於理解,但也有幾處值得在正式項目中調整:
Calendar.WEEK_OF_MONTH 或 java.time(API 26+)的 WeekFields。總體來說,周歷的技術含量集中在「日期數學」與「手勢 + 容器動畫」兩塊,把這兩處邏輯抽乾淨,UI 層替換成本很低。
Android 使用 Socket 進行網路通信的完整示範
用戶端通常只要呼叫 Socket 的建構子並指定位址與埠號,就能建立與伺服器的連線。以下示範一個 Android 端連上伺服器並接收伺服器推送訊息的完整流程。 一、伺服器
Android MVP 入門實作:把邏輯從 Activity 裡拆出來
先看專案結構: 可以歸納出一個規律:每個功能模組都由四個部分組成: XXActivity:負責畫面與使用者互動(View 層) XXView(Interface):
DrySister 圖片應用實作:加入 SQLite 離線快取
為什麼需要資料快取 在 DrySister 的第一版中,我們已經加入非同步圖片載入與記憶體、磁碟快取。不過,若只在有網路時取得圖片資訊,一旦離線後重新進入 App,雖然圖
Android SQLite 資料庫完整實戰:增刪改查、分頁、事務與 ListView 展示
剛接觸 Android 開發時,資料持久化往往是第一道門檻。本文以一個聯絡人小專案為例,完整示範如何使用系統內建的 SQLite,並把資料以 ListView 呈現,同時