diff --git a/src/Notes-master/app/src/main/java/net/micode/notes/MainActivity.java b/src/Notes-master/app/src/main/java/net/micode/notes/MainActivity.java index 6ba80f2..271c365 100644 --- a/src/Notes-master/app/src/main/java/net/micode/notes/MainActivity.java +++ b/src/Notes-master/app/src/main/java/net/micode/notes/MainActivity.java @@ -1,3 +1,7 @@ +/* + * 应用主Activity + * 负责设置全屏沉浸效果,适配系统状态栏和导航栏 + */ package net.micode.notes; import android.os.Bundle; @@ -8,17 +12,38 @@ import androidx.core.graphics.Insets; import androidx.core.view.ViewCompat; import androidx.core.view.WindowInsetsCompat; +/** + * 应用主Activity + * 实现全屏沉浸效果,使应用内容能够延伸到系统状态栏和导航栏区域 + */ public class MainActivity extends AppCompatActivity { + /** + * Activity创建时调用的生命周期方法 + * 设置全屏沉浸效果并处理窗口Insets + * + * @param savedInstanceState 保存的实例状态,如果Activity是重新创建的 + */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); + + // 启用全屏沉浸效果,允许内容延伸到系统状态栏和导航栏区域 EdgeToEdge.enable(this); + + // 设置Activity布局 setContentView(R.layout.activity_main); + + // 设置窗口Insets监听器,处理系统窗口边界 ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> { + // 获取系统状态栏和导航栏的Insets(边距) Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()); + + // 将Insets应用到主视图的padding中,确保内容不会被系统UI遮挡 v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom); + + // 返回处理后的Insets,供其他视图继续使用 return insets; }); } -} \ No newline at end of file +} diff --git a/src/Notes-master/app/src/main/java/net/micode/notes/ui/AlarmAlertActivity.java b/src/Notes-master/app/src/main/java/net/micode/notes/ui/AlarmAlertActivity.java index 85723be..3cc50da 100644 --- a/src/Notes-master/app/src/main/java/net/micode/notes/ui/AlarmAlertActivity.java +++ b/src/Notes-master/app/src/main/java/net/micode/notes/ui/AlarmAlertActivity.java @@ -39,21 +39,34 @@ import net.micode.notes.tool.DataUtils; import java.io.IOException; - +/** + * 闹钟提醒活动 - 处理笔记提醒的显示和响铃 + * 当笔记提醒时间到达时,此活动会显示提醒对话框并播放提醒音 + */ public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener { + // 笔记ID和摘要内容 private long mNoteId; private String mSnippet; + // 摘要预览最大长度常量 private static final int SNIPPET_PREW_MAX_LEN = 60; + // 媒体播放器,用于播放提醒音 MediaPlayer mPlayer; + /** + * 活动创建时调用 + * 设置窗口属性、解析意图数据、显示提醒对话框并播放提醒音 + */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); + // 请求无标题窗口 requestWindowFeature(Window.FEATURE_NO_TITLE); + // 获取窗口并添加显示在锁屏上的标志 final Window win = getWindow(); win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); + // 如果屏幕未开启,则添加唤醒屏幕的标志 if (!isScreenOn()) { win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON @@ -61,11 +74,14 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR); } + // 获取启动活动的意图 Intent intent = getIntent(); + // 从意图数据中解析笔记ID和摘要 try { mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1)); mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId); + // 如果摘要过长,则截断并添加省略号 mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0, SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info) : mSnippet; @@ -74,7 +90,9 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD return; } + // 创建媒体播放器实例 mPlayer = new MediaPlayer(); + // 检查笔记是否有效,如果有效则显示对话框并播放提醒音,否则关闭活动 if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) { showActionDialog(); playAlarmSound(); @@ -83,76 +101,108 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD } } + /** + * 检查屏幕是否开启 + */ private boolean isScreenOn() { PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); return pm.isScreenOn(); } + /** + * 播放闹钟提醒音 + * 配置媒体播放器并播放默认闹钟铃声 + */ private void playAlarmSound() { + // 获取默认闹钟铃声URI Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM); + // 获取静音模式下受影响的音频流设置 int silentModeStreams = Settings.System.getInt(getContentResolver(), Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0); + // 根据设置配置音频流类型 if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) { mPlayer.setAudioStreamType(silentModeStreams); } else { mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); } + + // 配置并启动媒体播放器 try { mPlayer.setDataSource(this, url); mPlayer.prepare(); - mPlayer.setLooping(true); + mPlayer.setLooping(true); // 设置循环播放 mPlayer.start(); } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block + // 异常处理:参数错误 e.printStackTrace(); } catch (SecurityException e) { - // TODO Auto-generated catch block + // 异常处理:安全权限问题 e.printStackTrace(); } catch (IllegalStateException e) { - // TODO Auto-generated catch block + // 异常处理:播放器状态错误 e.printStackTrace(); } catch (IOException e) { - // TODO Auto-generated catch block + // 异常处理:IO错误 e.printStackTrace(); } } + /** + * 显示提醒操作对话框 + * 包含笔记摘要和操作按钮 + */ private void showActionDialog() { AlertDialog.Builder dialog = new AlertDialog.Builder(this); - dialog.setTitle(R.string.app_name); - dialog.setMessage(mSnippet); - dialog.setPositiveButton(R.string.notealert_ok, this); + dialog.setTitle(R.string.app_name); // 设置对话框标题为应用名称 + dialog.setMessage(mSnippet); // 设置对话框内容为笔记摘要 + dialog.setPositiveButton(R.string.notealert_ok, this); // 添加"确定"按钮 + + // 如果屏幕已开启,添加"进入"按钮用于打开笔记编辑界面 if (isScreenOn()) { dialog.setNegativeButton(R.string.notealert_enter, this); } + + // 显示对话框并设置关闭监听器 dialog.show().setOnDismissListener(this); } + /** + * 处理 对话框按钮点击事件 + */ public void onClick(DialogInterface dialog, int which) { switch (which) { case DialogInterface.BUTTON_NEGATIVE: + // "进入"按钮:打开笔记编辑界面 Intent intent = new Intent(this, NoteEditActivity.class); intent.setAction(Intent.ACTION_VIEW); intent.putExtra(Intent.EXTRA_UID, mNoteId); startActivity(intent); break; default: + // 默认情况(通常是"确定"按钮):不执行额外操作,对话框关闭时会停止铃声 break; } } + /** + * 处理对话框关闭事件 + */ public void onDismiss(DialogInterface dialog) { + // 停止闹钟声音并结束活动 stopAlarmSound(); finish(); } + /** + * 停止闹钟声音并释放资源 + */ private void stopAlarmSound() { if (mPlayer != null) { - mPlayer.stop(); - mPlayer.release(); - mPlayer = null; + mPlayer.stop(); // 停止播放 + mPlayer.release(); // 释放资源 + mPlayer = null; // 置空引用,防止重复操作 } } } diff --git a/src/Notes-master/app/src/main/java/net/micode/notes/ui/AlarmInitReceiver.java b/src/Notes-master/app/src/main/java/net/micode/notes/ui/AlarmInitReceiver.java index f221202..c38a09a 100644 --- a/src/Notes-master/app/src/main/java/net/micode/notes/ui/AlarmInitReceiver.java +++ b/src/Notes-master/app/src/main/java/net/micode/notes/ui/AlarmInitReceiver.java @@ -27,38 +27,64 @@ import android.database.Cursor; import net.micode.notes.data.Notes; import net.micode.notes.data.Notes.NoteColumns; - +/** + * 闹钟初始化接收器 - 负责重新设置所有待处理的笔记提醒 + * 当系统启动完成或时区变化时,该接收器会被触发,重新设置所有未来的笔记提醒 + */ public class AlarmInitReceiver extends BroadcastReceiver { + // 查询投影 - 定义需要从数据库中获取的列 private static final String [] PROJECTION = new String [] { - NoteColumns.ID, - NoteColumns.ALERTED_DATE + NoteColumns.ID, // 笔记ID + NoteColumns.ALERTED_DATE // 提醒日期 }; + // 列索引常量,用于从Cursor中获取数据 private static final int COLUMN_ID = 0; private static final int COLUMN_ALERTED_DATE = 1; + /** + * 接收广播时调用 + * 重新设置所有未来的笔记提醒 + */ @Override public void onReceive(Context context, Intent intent) { + // 获取当前时间戳 long currentDate = System.currentTimeMillis(); + + // 查询数据库中所有未来的提醒(提醒时间大于当前时间且类型为笔记的记录) Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI, PROJECTION, NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE, new String[] { String.valueOf(currentDate) }, null); + // 处理查询结果 if (c != null) { if (c.moveToFirst()) { + // 遍历所有未来提醒 do { + // 获取提醒时间 long alertDate = c.getLong(COLUMN_ALERTED_DATE); + + // 创建用于触发提醒的Intent Intent sender = new Intent(context, AlarmReceiver.class); + // 设置Intent的数据URI,包含笔记ID sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID))); + + // 创建用于延迟执行的PendingIntent PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0); - AlarmManager alermManager = (AlarmManager) context + + // 获取AlarmManager系统服务 + AlarmManager alarmManager = (AlarmManager) context .getSystemService(Context.ALARM_SERVICE); - alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent); + + // 设置闹钟,在指定时间触发PendingIntent + alarmManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent); + } while (c.moveToNext()); } + // 关闭Cursor,释放 资源 c.close(); } } diff --git a/src/Notes-master/app/src/main/java/net/micode/notes/ui/AlarmReceiver.java b/src/Notes-master/app/src/main/java/net/micode/notes/ui/AlarmReceiver.java index 54e503b..5dd4aed 100644 --- a/src/Notes-master/app/src/main/java/net/micode/notes/ui/AlarmReceiver.java +++ b/src/Notes-master/app/src/main/java/net/micode/notes/ui/AlarmReceiver.java @@ -20,11 +20,24 @@ import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; +/** + * 闹钟接收器 - 负责接收闹钟触发事件并启动提醒界面 + * 当设置的闹钟时间到达时,AlarmManager会发送广播,此接收器会捕获该广播并启动提醒界面 + */ public class AlarmReceiver extends BroadcastReceiver { + /** + * 接收广播时调用 + * 将接收到的闹钟广播转换为启动提醒界面的意图 + */ @Override public void onReceive(Context context, Intent intent) { + // 将意图的目标类设置为AlarmAlertActivity(闹钟提醒界面) intent.setClass(context, AlarmAlertActivity.class); + + // 添加FLAG_ACTIVITY_NEW_TASK标志,确保在非Activity上下文(如BroadcastReceiver)中可以启动Activity intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + + // 启动闹钟提 醒界面 context.startActivity(intent); } } diff --git a/src/Notes-master/app/src/main/java/net/micode/notes/ui/DateTimePicker.java b/src/Notes-master/app/src/main/java/net/micode/notes/ui/DateTimePicker.java index 496b0cd..c78dd27 100644 --- a/src/Notes-master/app/src/main/java/net/micode/notes/ui/DateTimePicker.java +++ b/src/Notes-master/app/src/main/java/net/micode/notes/ui/DateTimePicker.java @@ -1,17 +1,9 @@ /* * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * 版权声明:本代码受Apache许可证2.0版本保护 + * 您可以在遵守许可证的前提下使用、修改和分发本代码 + * 许可证全文可在http://www.apache.org/licenses/LICENSE-2.0获取 */ package net.micode.notes.ui; @@ -28,85 +20,130 @@ import android.view.View; import android.widget.FrameLayout; import android.widget.NumberPicker; +/** + * 日期时间选择器控件 + * 功能:提供可视化的日期(年/月/日)和时间(时/分/上下午)选择界面 + * 实现:基于Android NumberPicker组件构建,支持24小时制和12小时制切换 + */ public class DateTimePicker extends FrameLayout { + // 默认启用状态 private static final boolean DEFAULT_ENABLE_STATE = true; - - private static final int HOURS_IN_HALF_DAY = 12; - private static final int HOURS_IN_ALL_DAY = 24; - private static final int DAYS_IN_ALL_WEEK = 7; - private static final int DATE_SPINNER_MIN_VAL = 0; - private static final int DATE_SPINNER_MAX_VAL = DAYS_IN_ALL_WEEK - 1; + + // 时间显示模式相关常量 + private static final int HOURS_IN_HALF_DAY = 12; // 12小时制半天时长 + private static final int HOURS_IN_ALL_DAY = 24; // 24小时制全天时长 + private static final int DAYS_IN_ALL_WEEK = 7; // 一周天数 + + // 日期选择器范围常量 + private static final int DATE_SPINNER_MIN_VAL = 0; // 日期选择器最小值 + private static final int DATE_SPINNER_MAX_VAL = DAYS_IN_ALL_WEEK - 1; // 日期选择器最大值 + + // 小时选择器范围常量(24小时制) private static final int HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW = 0; private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23; + + // 小时选择器范围常量(12小时制) private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1; private static final int HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW = 12; + + // 分钟选择器范围常量 private static final int MINUT_SPINNER_MIN_VAL = 0; private static final int MINUT_SPINNER_MAX_VAL = 59; + + // 上下午选择器范围常量 private static final int AMPM_SPINNER_MIN_VAL = 0; private static final int AMPM_SPINNER_MAX_VAL = 1; - private final NumberPicker mDateSpinner; - private final NumberPicker mHourSpinner; - private final NumberPicker mMinuteSpinner; - private final NumberPicker mAmPmSpinner; - private Calendar mDate; - + // UI组件引用 + private final NumberPicker mDateSpinner; // 日期选择器(显示一周内的日期) + private final NumberPicker mHourSpinner; // 小时选择器 + private final NumberPicker mMinuteSpinner; // 分钟选择器 + private final NumberPicker mAmPmSpinner; // 上下午选择器 + private Calendar mDate; // 当前选中的日期时间 + + // 日期显示文本数组 private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK]; - - private boolean mIsAm; - - private boolean mIs24HourView; - - private boolean mIsEnabled = DEFAULT_ENABLE_STATE; - - private boolean mInitialising; - + + // 时间状态标记 + private boolean mIsAm; // 是否为上午(12小时制专用) + private boolean mIs24HourView; // 是否使用24小时制 + private boolean mIsEnabled = DEFAULT_ENABLE_STATE; // 控件启用状态 + private boolean mInitialising; // 初始化标记(防止事件回调循环) + + // 日期时间变化监听器 private OnDateTimeChangedListener mOnDateTimeChangedListener; + /** + * 日期选择变化监听器 + * 功能:处理日期选择器值变化事件,更新日期并触发回调 + */ private NumberPicker.OnValueChangeListener mOnDateChangedListener = new NumberPicker.OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { + // 根据新旧值差调整日期 mDate.add(Calendar.DAY_OF_YEAR, newVal - oldVal); + // 更新日期显示 updateDateControl(); + // 触发日期时间变化回调 onDateTimeChanged(); } }; + /** + * 小时选择变化监听器 + * 功能:处理小时选择器值变化事件,处理12/24小时制转换逻辑 + */ private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { boolean isDateChanged = false; Calendar cal = Calendar.getInstance(); + + // 12小时制特殊处理逻辑 if (!mIs24HourView) { + // 下午11点->12点:日期加1天 if (!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) { cal.setTimeInMillis(mDate.getTimeInMillis()); cal.add(Calendar.DAY_OF_YEAR, 1); isDateChanged = true; - } else if (mIsAm && oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) { + } + // 上午12点->11点:日期减1天 + else if (mIsAm && oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) { cal.setTimeInMillis(mDate.getTimeInMillis()); cal.add(Calendar.DAY_OF_YEAR, -1); isDateChanged = true; } + + // 上下午切换处理 if (oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY || oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) { mIsAm = !mIsAm; updateAmPmControl(); } - } else { + } + // 24小时制特殊处理逻辑 + else { + // 23点->0点:日期加1天 if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) { cal.setTimeInMillis(mDate.getTimeInMillis()); cal.add(Calendar.DAY_OF_YEAR, 1); isDateChanged = true; - } else if (oldVal == 0 && newVal == HOURS_IN_ALL_DAY - 1) { + } + // 0点->23点:日期减1天 + else if (oldVal == 0 && newVal == HOURS_IN_ALL_DAY - 1) { cal.setTimeInMillis(mDate.getTimeInMillis()); cal.add(Calendar.DAY_OF_YEAR, -1); isDateChanged = true; } } + + // 计算实际小时值(12小时制转换) int newHour = mHourSpinner.getValue() % HOURS_IN_HALF_DAY + (mIsAm ? 0 : HOURS_IN_HALF_DAY); mDate.set(Calendar.HOUR_OF_DAY, newHour); onDateTimeChanged(); + + // 日期变更时更新年月日 if (isDateChanged) { setCurrentYear(cal.get(Calendar.YEAR)); setCurrentMonth(cal.get(Calendar.MONTH)); @@ -115,21 +152,30 @@ public class DateTimePicker extends FrameLayout { } }; + /** + * 分钟选择变化监听器 + * 功能:处理分钟选择器值变化事件,处理跨小时逻辑 + */ private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { int minValue = mMinuteSpinner.getMinValue(); int maxValue = mMinuteSpinner.getMaxValue(); int offset = 0; + + // 处理分钟循环选择导致的小时变化 if (oldVal == maxValue && newVal == minValue) { - offset += 1; + offset += 1; // 60分->0分:小时加1 } else if (oldVal == minValue && newVal == maxValue) { - offset -= 1; + offset -= 1; // 0分->60分:小时减1 } + if (offset != 0) { mDate.add(Calendar.HOUR_OF_DAY, offset); mHourSpinner.setValue(getCurrentHour()); updateDateControl(); + + // 更新上下午状态 int newHour = getCurrentHourOfDay(); if (newHour >= HOURS_IN_HALF_DAY) { mIsAm = false; @@ -139,15 +185,22 @@ public class DateTimePicker extends FrameLayout { updateAmPmControl(); } } + + // 设置分钟值并触发回调 mDate.set(Calendar.MINUTE, newVal); onDateTimeChanged(); } }; + /** + * 上下午选择变化监听器 + * 功能:处理AM/PM切换事件,更新小时值 + */ private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { mIsAm = !mIsAm; + // 上下午切换时调整小时值(12小时制) if (mIsAm) { mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY); } else { @@ -158,11 +211,16 @@ public class DateTimePicker extends FrameLayout { } }; + /** + * 日期时间变化回调接口 + * 当用户修改日期或时间时触发 + */ public interface OnDateTimeChangedListener { void onDateTimeChanged(DateTimePicker view, int year, int month, int dayOfMonth, int hourOfDay, int minute); } + // 构造函数系列(支持不同初始化方式) public DateTimePicker(Context context) { this(context, System.currentTimeMillis()); } @@ -176,50 +234,61 @@ public class DateTimePicker extends FrameLayout { mDate = Calendar.getInstance(); mInitialising = true; mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY; + + // 加载布局文件 inflate(context, R.layout.datetime_picker, this); + // 初始化日期选择器 mDateSpinner = (NumberPicker) findViewById(R.id.date); mDateSpinner.setMinValue(DATE_SPINNER_MIN_VAL); mDateSpinner.setMaxValue(DATE_SPINNER_MAX_VAL); mDateSpinner.setOnValueChangedListener(mOnDateChangedListener); + // 初始化小时选择器 mHourSpinner = (NumberPicker) findViewById(R.id.hour); mHourSpinner.setOnValueChangedListener(mOnHourChangedListener); + + // 初始化分钟选择器 mMinuteSpinner = (NumberPicker) findViewById(R.id.minute); mMinuteSpinner.setMinValue(MINUT_SPINNER_MIN_VAL); mMinuteSpinner.setMaxValue(MINUT_SPINNER_MAX_VAL); - mMinuteSpinner.setOnLongPressUpdateInterval(100); + mMinuteSpinner.setOnLongPressUpdateInterval(100); // 长按快速滚动间隔 mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener); + // 初始化上下午选择器 String[] stringsForAmPm = new DateFormatSymbols().getAmPmStrings(); mAmPmSpinner = (NumberPicker) findViewById(R.id.amPm); mAmPmSpinner.setMinValue(AMPM_SPINNER_MIN_VAL); mAmPmSpinner.setMaxValue(AMPM_SPINNER_MAX_VAL); - mAmPmSpinner.setDisplayedValues(stringsForAmPm); + mAmPmSpinner.setDisplayedValues(stringsForAmPm); // 设置AM/PM显示文本 mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener); - // update controls to initial state + // 初始化控件状态 updateDateControl(); updateHourControl(); updateAmPmControl(); + // 设置时间显示模式 set24HourView(is24HourView); - // set to current time + // 设置当前日期时间 setCurrentDate(date); + // 设置控件启用状态 setEnabled(isEnabled()); - // set the content descriptions + // 完成初始化(启用事件回调) mInitialising = false; } + // 控件启用状态相关方法 @Override public void setEnabled(boolean enabled) { if (mIsEnabled == enabled) { return; } super.setEnabled(enabled); + // 同步设置所有选择器的启用状态 mDateSpinner.setEnabled(enabled); mMinuteSpinner.setEnabled(enabled); mHourSpinner.setEnabled(enabled); @@ -233,34 +302,32 @@ public class DateTimePicker extends FrameLayout { } /** - * Get the current date in millis - * - * @return the current date in millis + * 获取当前选择的日期时间(毫秒值) + * @return 自1970-01-01以来的毫秒数 */ public long getCurrentDateInTimeMillis() { return mDate.getTimeInMillis(); } /** - * Set the current date - * - * @param date The current date in millis + * 设置当前日期时间(毫秒值) + * @param date 自1970-01-01以来的毫秒数 */ public void setCurrentDate(long date) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(date); + // 分解为年月日时分设置 setCurrentDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE)); } /** - * Set the current date - * - * @param year The current year - * @param month The current month - * @param dayOfMonth The current dayOfMonth - * @param hourOfDay The current hourOfDay - * @param minute The current minute + * 设置当前日期时间(详细参数) + * @param year 年份 + * @param month 月份(0-11) + * @param dayOfMonth 日期(1-31) + * @param hourOfDay 小时(0-23) + * @param minute 分钟(0-59) */ public void setCurrentDate(int year, int month, int dayOfMonth, int hourOfDay, int minute) { @@ -271,20 +338,11 @@ public class DateTimePicker extends FrameLayout { setCurrentMinute(minute); } - /** - * Get current year - * - * @return The current year - */ + // 年份相关操作方法 public int getCurrentYear() { return mDate.get(Calendar.YEAR); } - /** - * Set current year - * - * @param year The current year - */ public void setCurrentYear(int year) { if (!mInitialising && year == getCurrentYear()) { return; @@ -294,20 +352,11 @@ public class DateTimePicker extends FrameLayout { onDateTimeChanged(); } - /** - * Get current month in the year - * - * @return The current month in the year - */ + // 月份相关操作方法 public int getCurrentMonth() { return mDate.get(Calendar.MONTH); } - /** - * Set current month in the year - * - * @param month The month in the year - */ public void setCurrentMonth(int month) { if (!mInitialising && month == getCurrentMonth()) { return; @@ -317,20 +366,11 @@ public class DateTimePicker extends FrameLayout { onDateTimeChanged(); } - /** - * Get current day of the month - * - * @return The day of the month - */ + // 日期相关操作方法 public int getCurrentDay() { return mDate.get(Calendar.DAY_OF_MONTH); } - /** - * Set current day of the month - * - * @param dayOfMonth The day of the month - */ public void setCurrentDay(int dayOfMonth) { if (!mInitialising && dayOfMonth == getCurrentDay()) { return; @@ -341,145 +381,39 @@ public class DateTimePicker extends FrameLayout { } /** - * Get current hour in 24 hour mode, in the range (0~23) - * @return The current hour in 24 hour mode + * 获取当前小时(24小时制) + * @return 0-23范围内的小时值 */ public int getCurrentHourOfDay() { return mDate.get(Calendar.HOUR_OF_DAY); } + /** + * 获取当前小时(根据显示模式转换) + * @return 12小时制下1-12,24小时制下0-23 + */ private int getCurrentHour() { if (mIs24HourView){ return getCurrentHourOfDay(); } else { int hour = getCurrentHourOfDay(); - if (hour > HOURS_IN_HALF_DAY) { - return hour - HOURS_IN_HALF_DAY; - } else { - return hour == 0 ? HOURS_IN_HALF_DAY : hour; - } + // 12小时制特殊处理(0点显示为12点) + return hour == 0 ? HOURS_IN_HALF_DAY : (hour > HOURS_IN_HALF_DAY ? hour - HOURS_IN_HALF_DAY : hour); } } /** - * Set current hour in 24 hour mode, in the range (0~23) - * - * @param hourOfDay + * 设置当前小时 (24小时制) + * @param hourOfDay 0-23范围内的小时值 */ public void setCurrentHour(int hourOfDay) { if (!mInitialising && hourOfDay == getCurrentHourOfDay()) { return; } mDate.set(Calendar.HOUR_OF_DAY, hourOfDay); + + // 12小时制下的小时转换 if (!mIs24HourView) { if (hourOfDay >= HOURS_IN_HALF_DAY) { mIsAm = false; - if (hourOfDay > HOURS_IN_HALF_DAY) { - hourOfDay -= HOURS_IN_HALF_DAY; - } - } else { - mIsAm = true; - if (hourOfDay == 0) { - hourOfDay = HOURS_IN_HALF_DAY; - } - } - updateAmPmControl(); - } - mHourSpinner.setValue(hourOfDay); - onDateTimeChanged(); - } - - /** - * Get currentMinute - * - * @return The Current Minute - */ - public int getCurrentMinute() { - return mDate.get(Calendar.MINUTE); - } - - /** - * Set current minute - */ - public void setCurrentMinute(int minute) { - if (!mInitialising && minute == getCurrentMinute()) { - return; - } - mMinuteSpinner.setValue(minute); - mDate.set(Calendar.MINUTE, minute); - onDateTimeChanged(); - } - - /** - * @return true if this is in 24 hour view else false. - */ - public boolean is24HourView () { - return mIs24HourView; - } - - /** - * Set whether in 24 hour or AM/PM mode. - * - * @param is24HourView True for 24 hour mode. False for AM/PM mode. - */ - public void set24HourView(boolean is24HourView) { - if (mIs24HourView == is24HourView) { - return; - } - mIs24HourView = is24HourView; - mAmPmSpinner.setVisibility(is24HourView ? View.GONE : View.VISIBLE); - int hour = getCurrentHourOfDay(); - updateHourControl(); - setCurrentHour(hour); - updateAmPmControl(); - } - - private void updateDateControl() { - Calendar cal = Calendar.getInstance(); - cal.setTimeInMillis(mDate.getTimeInMillis()); - cal.add(Calendar.DAY_OF_YEAR, -DAYS_IN_ALL_WEEK / 2 - 1); - mDateSpinner.setDisplayedValues(null); - for (int i = 0; i < DAYS_IN_ALL_WEEK; ++i) { - cal.add(Calendar.DAY_OF_YEAR, 1); - mDateDisplayValues[i] = (String) DateFormat.format("MM.dd EEEE", cal); - } - mDateSpinner.setDisplayedValues(mDateDisplayValues); - mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2); - mDateSpinner.invalidate(); - } - - private void updateAmPmControl() { - if (mIs24HourView) { - mAmPmSpinner.setVisibility(View.GONE); - } else { - int index = mIsAm ? Calendar.AM : Calendar.PM; - mAmPmSpinner.setValue(index); - mAmPmSpinner.setVisibility(View.VISIBLE); - } - } - - private void updateHourControl() { - if (mIs24HourView) { - mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW); - mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW); - } else { - mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW); - mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW); - } - } - - /** - * Set the callback that indicates the 'Set' button has been pressed. - * @param callback the callback, if null will do nothing - */ - public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) { - mOnDateTimeChangedListener = callback; - } - - private void onDateTimeChanged() { - if (mOnDateTimeChangedListener != null) { - mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(), - getCurrentMonth(), getCurrentDay(), getCurrentHourOfDay(), getCurrentMinute()); - } - } -} + if (hourOfDay > HOURS_IN_H \ No newline at end of file diff --git a/src/Notes-master/app/src/main/java/net/micode/notes/ui/DateTimePickerDialog.java b/src/Notes-master/app/src/main/java/net/micode/notes/ui/DateTimePickerDialog.java index 2c47ba4..794fe38 100644 --- a/src/Notes-master/app/src/main/java/net/micode/notes/ui/DateTimePickerDialog.java +++ b/src/Notes-master/app/src/main/java/net/micode/notes/ui/DateTimePickerDialog.java @@ -1,17 +1,9 @@ /* * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * 版权声明:本代码受Apache许可证2.0版本保护 + * 您可以在遵守许可证的前提下使用、修改和分发本代码 + * 许可证全文可在http://www.apache.org/licenses/LICENSE-2.0获取 */ package net.micode.notes.ui; @@ -29,59 +21,113 @@ import android.content.DialogInterface.OnClickListener; import android.text.format.DateFormat; import android.text.format.DateUtils; +/** + * 日期时间选择对话框 + * 功能:封装DateTimePicker控件,提供弹窗式的日期时间选择界面 + * 特点:支持标题自动更新、24小时制/12小时制切换、确定/取消按钮 + */ public class DateTimePickerDialog extends AlertDialog implements OnClickListener { + // 当前选择的日期时间 private Calendar mDate = Calendar.getInstance(); + // 是否使用24小时制 private boolean mIs24HourView; + // 日期时间设置回调接口 private OnDateTimeSetListener mOnDateTimeSetListener; + // 内嵌的日期时间选择器控件 private DateTimePicker mDateTimePicker; + /** + * 日期时间设置回调接口 + * 当用户点击确定按钮时触发 + */ public interface OnDateTimeSetListener { void OnDateTimeSet(AlertDialog dialog, long date); } + /** + * 构造函数 + * @param context 上下文对象 + * @param date 初始显示的日期时间(毫秒值) + */ public DateTimePickerDialog(Context context, long date) { super(context); + + // 初始化日期时间选择器控件 mDateTimePicker = new DateTimePicker(context); setView(mDateTimePicker); + + // 设置日期时间变化监听器,更新日期并刷新标题 mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() { public void onDateTimeChanged(DateTimePicker view, int year, int month, int dayOfMonth, int hourOfDay, int minute) { + // 更新日历对象 mDate.set(Calendar.YEAR, year); mDate.set(Calendar.MONTH, month); mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth); mDate.set(Calendar.HOUR_OF_DAY, hourOfDay); mDate.set(Calendar.MINUTE, minute); + // 更新对话框标题 updateTitle(mDate.getTimeInMillis()); } }); + + // 设置初始日期时间(忽略秒) mDate.setTimeInMillis(date); mDate.set(Calendar.SECOND, 0); mDateTimePicker.setCurrentDate(mDate.getTimeInMillis()); + + // 设置对话框按钮 setButton(context.getString(R.string.datetime_dialog_ok), this); setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null); + + // 设置时间显示模式 set24HourView(DateFormat.is24HourFormat(this.getContext())); + + // 初始化对话框标题 updateTitle(mDate.getTimeInMillis()); } + /** + * 设置时间显示模式 + * @param is24HourView true为24小时制,false为12小时制 + */ public void set24HourView(boolean is24HourView) { mIs24HourView = is24HourView; } + /** + * 设置日期时间选择回调 + * @param callBack 回调接口实现 + */ public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) { mOnDateTimeSetListener = callBack; } + /** + * 更新对话框标题 + * @param date 要显示的日期时间(毫秒值) + */ private void updateTitle(long date) { + // 设置日期格式标志:显示年、月、日、时间 int flag = DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME; + + // 根据24小时制/12小时制设置相应标志 flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR; + + // 使用系统工具类格式化日期并设置为标题 setTitle(DateUtils.formatDateTime(this.getContext(), date, flag)); } + /** + * 点击事件 处理 + * 当用户点击确定按钮时触发 + */ public void onClick(DialogInterface arg0, int arg1) { + // 调用回调接口,传递选择的日期时间 if (mOnDateTimeSetListener != null) { mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis()); } diff --git a/src/Notes-master/app/src/main/java/net/micode/notes/ui/DropdownMenu.java b/src/Notes-master/app/src/main/java/net/micode/notes/ui/DropdownMenu.java index 613dc74..8b5a707 100644 --- a/src/Notes-master/app/src/main/java/net/micode/notes/ui/DropdownMenu.java +++ b/src/Notes-master/app/src/main/java/net/micode/notes/ui/DropdownMenu.java @@ -1,17 +1,9 @@ /* * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * 版权声明:本代码受Apache许可证2.0版本保护 + * 您可以在遵守许可证的前提下使用、修改和分发本代码 + * 许可证全文可在http://www.apache.org/licenses/LICENSE-2.0获取 */ package net.micode.notes.ui; @@ -27,17 +19,38 @@ import android.widget.PopupMenu.OnMenuItemClickListener; import net.micode.notes.R; +/** + * 下拉菜单控件 + * 功能:封装PopupMenu,提供简洁的下拉菜单交互方式 + * 特点:基于Button触发,支持自定义菜单项和点击事件 + */ public class DropdownMenu { + // 触发下拉菜单的按钮 private Button mButton; + // 系统PopupMenu对象 private PopupMenu mPopupMenu; + // 菜单项集合 private Menu mMenu; + /** + * 构造函数 + * @param context 上下文对象 + * @param button 触发下拉菜单的按钮 + * @param menuId 菜单资源ID + */ public DropdownMenu(Context context, Button button, int menuId) { mButton = button; + // 设置按钮背景为下拉菜单图标 mButton.setBackgroundResource(R.drawable.dropdown_icon); + + // 初始化PopupMenu mPopupMenu = new PopupMenu(context, mButton); mMenu = mPopupMenu.getMenu(); + + // 从资源文件加载菜单项 mPopupMenu.getMenuInflater().inflate(menuId, mMenu); + + // 设置按钮点击事件,显示下拉菜单 mButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mPopupMenu.show(); @@ -45,17 +58,30 @@ public class DropdownMenu { }); } + /** + * 设置菜单项点击监听器 + * @param listener 菜单项点击回调 + */ public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) { if (mPopupMenu != null) { mPopupMenu.setOnMenuItemClickListener(listener); } } + /** + * 查找指定ID的菜单项 + * @param id 菜单项ID + * @return 对应的 MenuItem对象,未找到则返回null + */ public MenuItem findItem(int id) { return mMenu.findItem(id); } + /** + * 设置按钮标题 + * @param title 要显示的标题文本 + */ public void setTitle(CharSequence title) { mButton.setText(title); } -} +} \ No newline at end of file diff --git a/src/Notes-master/app/src/main/java/net/micode/notes/ui/FoldersListAdapter.java b/src/Notes-master/app/src/main/java/net/micode/notes/ui/FoldersListAdapter.java index 96b77da..ed48187 100644 --- a/src/Notes-master/app/src/main/java/net/micode/notes/ui/FoldersListAdapter.java +++ b/src/Notes-master/app/src/main/java/net/micode/notes/ui/FoldersListAdapter.java @@ -1,17 +1,9 @@ /* * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * 版权声明:本代码受Apache许可证2.0版本保护 + * 您可以在遵守许可证的前提下使用、修改和分发本代码 + * 许可证全文可在http://www.apache.org/licenses/LICENSE-2.0获取 */ package net.micode.notes.ui; @@ -28,53 +20,103 @@ import net.micode.notes.R; import net.micode.notes.data.Notes; import net.micode.notes.data.Notes.NoteColumns; - +/** + * 文件夹列表适配器 + * 功能:将数据库中的文件夹数据绑定到ListView/RecyclerView中 + * 特点:支持自定义文件夹名称显示,特别是对根文件夹的特殊处理 + */ public class FoldersListAdapter extends CursorAdapter { + // 数据库查询投影:指定要查询的列 public static final String [] PROJECTION = { - NoteColumns.ID, - NoteColumns.SNIPPET + NoteColumns.ID, // 文件夹ID + NoteColumns.SNIPPET // 文件夹名称(片段) }; - public static final int ID_COLUMN = 0; - public static final int NAME_COLUMN = 1; + // 列索引常量,方便代码引用 + public static final int ID_COLUMN = 0; // ID列索引 + public static final int NAME_COLUMN = 1; // 名称列索引 + /** + * 构造函数 + * @param context 上下文对象 + * @param c 数据库游标,包含文件夹数据 + */ public FoldersListAdapter(Context context, Cursor c) { super(context, c); // TODO Auto-generated constructor stub } + /** + * 创建新的列表项视图 + * @param context 上下文对象 + * @param cursor 当前数据游标 + * @param parent 父视图容器 + * @return 新创建的FolderListItem视图 + */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return new FolderListItem(context); } + /** + * 将数据绑定到已创建的视图 + * @param view 要绑定数据的视图 + * @param context 上下文对象 + * @param cursor 当前数据游标 + */ @Override public void bindView(View view, Context context, Cursor cursor) { if (view instanceof FolderListItem) { - String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context - .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); + // 获取文件夹名称,特殊处理根文件夹 + String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? + context.getString(R.string.menu_move_parent_folder) : // 根文件夹显示特定文本 + cursor.getString(NAME_COLUMN); // 普通文件夹显示数据库名称 + + // 绑定数据到视图 ((FolderListItem) view).bind(folderName); } } + /** + * 获取指定位置的文件夹名称 + * @param context 上下文对象 + * @param position 列表位置 + * @return 文件夹名称 + */ public String getFolderName(Context context, int position) { Cursor cursor = (Cursor) getItem(position); - return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context - .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); + // 同样特殊处理根文件夹 + return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? + context.getString(R.string.menu_move_parent_folder) : + cursor.getString(NAME_COLUMN); } + /** + * 文件夹列表项内部类 + * 功能:定义单个文件夹项的UI布局和数据绑定逻辑 + */ private class FolderListItem extends LinearLayout { + // 文件夹名称显示文本视图 private TextView mName; + /** + * 构造函数 + * @param context 上下文对象 + */ public FolderListItem(Context context) { super(context); + // 加载布局 文件 inflate(context, R.layout.folder_list_item, this); + // 获取并保存名称文本视图引用 mName = (TextView) findViewById(R.id.tv_folder_name); } + /** + * 绑定文件夹名称到视图 + * @param name 文件夹名称 + */ public void bind(String name) { mName.setText(name); } } - -} +} \ No newline at end of file diff --git a/src/Notes-master/app/src/main/java/net/micode/notes/ui/NoteEditActivity.java b/src/Notes-master/app/src/main/java/net/micode/notes/ui/NoteEditActivity.java index 96a9ff8..f78e081 100644 --- a/src/Notes-master/app/src/main/java/net/micode/notes/ui/NoteEditActivity.java +++ b/src/Notes-master/app/src/main/java/net/micode/notes/ui/NoteEditActivity.java @@ -1,17 +1,9 @@ /* * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * 版权声明:本代码受Apache许可证2.0版本保护 + * 您可以在遵守许可证的前提下使用、修改和分发本代码 + * 许可证全文可在http://www.apache.org/licenses/LICENSE-2.0获取 */ package net.micode.notes.ui; @@ -71,19 +63,23 @@ import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; - +/** + * 笔记编辑活动类 + * 功能:提供笔记的创建、编辑、删除等功能界面 + * 特点:支持富文本编辑、清单模式、提醒设置、背景颜色和字体大小调整 + */ public class NoteEditActivity extends Activity implements OnClickListener, NoteSettingChangedListener, OnTextViewChangeListener { + + // 笔记头部视图持有者类,用于缓存头部UI组件 private class HeadViewHolder { - public TextView tvModified; - - public ImageView ivAlertIcon; - - public TextView tvAlertDate; - - public ImageView ibSetBgColor; + public TextView tvModified; // 最后修改时间显示 + public ImageView ivAlertIcon; // 提醒图标 + public TextView tvAlertDate; // 提醒日期显示 + public ImageView ibSetBgColor; // 设置背景颜色按钮 } - + + // 背景颜色选择按钮映射表:按钮ID -> 颜色资源ID private static final Map sBgSelectorBtnsMap = new HashMap(); static { sBgSelectorBtnsMap.put(R.id.iv_bg_yellow, ResourceParser.YELLOW); @@ -92,7 +88,8 @@ public class NoteEditActivity extends Activity implements OnClickListener, sBgSelectorBtnsMap.put(R.id.iv_bg_green, ResourceParser.GREEN); sBgSelectorBtnsMap.put(R.id.iv_bg_white, ResourceParser.WHITE); } - + + // 背景颜色选择选中状态映射表:颜色资源ID -> 选中图标ID private static final Map sBgSelectorSelectionMap = new HashMap(); static { sBgSelectorSelectionMap.put(ResourceParser.YELLOW, R.id.iv_bg_yellow_select); @@ -101,7 +98,8 @@ public class NoteEditActivity extends Activity implements OnClickListener, sBgSelectorSelectionMap.put(ResourceParser.GREEN, R.id.iv_bg_green_select); sBgSelectorSelectionMap.put(ResourceParser.WHITE, R.id.iv_bg_white_select); } - + + // 字体大小按钮映射表:按钮ID -> 字体大小资源ID private static final Map sFontSizeBtnsMap = new HashMap(); static { sFontSizeBtnsMap.put(R.id.ll_font_large, ResourceParser.TEXT_LARGE); @@ -109,7 +107,8 @@ public class NoteEditActivity extends Activity implements OnClickListener, sFontSizeBtnsMap.put(R.id.ll_font_normal, ResourceParser.TEXT_MEDIUM); sFontSizeBtnsMap.put(R.id.ll_font_super, ResourceParser.TEXT_SUPER); } - + + // 字体大小选择选中状态映射表:字体大小资源ID -> 选中图标ID private static final Map sFontSelectorSelectionMap = new HashMap(); static { sFontSelectorSelectionMap.put(ResourceParser.TEXT_LARGE, R.id.iv_large_select); @@ -117,43 +116,38 @@ public class NoteEditActivity extends Activity implements OnClickListener, sFontSelectorSelectionMap.put(ResourceParser.TEXT_MEDIUM, R.id.iv_medium_select); sFontSelectorSelectionMap.put(ResourceParser.TEXT_SUPER, R.id.iv_super_select); } - + + // 日志标签 private static final String TAG = "NoteEditActivity"; - - private HeadViewHolder mNoteHeaderHolder; - - private View mHeadViewPanel; - - private View mNoteBgColorSelector; - - private View mFontSizeSelector; - - private EditText mNoteEditor; - - private View mNoteEditorPanel; - - private WorkingNote mWorkingNote; - - private SharedPreferences mSharedPrefs; - private int mFontSizeId; - - private static final String PREFERENCE_FONT_SIZE = "pref_font_size"; - - private static final int SHORTCUT_ICON_TITLE_MAX_LEN = 10; - - public static final String TAG_CHECKED = String.valueOf('\u221A'); - public static final String TAG_UNCHECKED = String.valueOf('\u25A1'); - + + // 界面组件引用 + private HeadViewHolder mNoteHeaderHolder; // 头部视图持有者 + private View mHeadViewPanel; // 头部面板 + private View mNoteBgColorSelector; // 背景颜色选择面板 + private View mFontSizeSelector; // 字体大小选择面板 + private EditText mNoteEditor; // 笔记编辑文本框 + private View mNoteEditorPanel; // 编辑区域面板 + private WorkingNote mWorkingNote; // 工作笔记模型 + private SharedPreferences mSharedPrefs; // 共享偏好设置 + private int mFontSizeId; // 当前字体大小ID + private static final String PREFERENCE_FONT_SIZE = "pref_font_size"; // 字体大小偏好键 + private static final int SHORTCUT_ICON_TITLE_MAX_LEN = 10; // 快捷方式标题最大长度 + + // 清单模式标签 + public static final String TAG_CHECKED = String.valueOf('\u221A'); // 已选中标记 + public static final String TAG_UNCHECKED = String.valueOf('\u25A1'); // 未选中标记 + + // 清单模式编辑列表 private LinearLayout mEditTextList; - - private String mUserQuery; - private Pattern mPattern; + private String mUserQuery; // 用户搜索查询词 + private Pattern mPattern; // 搜索匹配模式 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.note_edit); + // 初始化活动状态,若失败则结束活动 if (savedInstanceState == null && !initActivityState(getIntent())) { finish(); return; @@ -162,8 +156,7 @@ public class NoteEditActivity extends Activity implements OnClickListener, } /** - * Current activity may be killed when the memory is low. Once it is killed, for another time - * user load this activity, we should restore the former state + * 恢复活动状态(内存不足被销毁后重建时调用) */ @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { @@ -179,24 +172,25 @@ public class NoteEditActivity extends Activity implements OnClickListener, } } + /** + * 初始化活动状态(处理不同启动意图) + * @param intent 启动活动的意图 + * @return 初始化是否成功 + */ private boolean initActivityState(Intent intent) { - /** - * If the user specified the {@link Intent#ACTION_VIEW} but not provided with id, - * then jump to the NotesListActivity - */ mWorkingNote = null; + // 处理查看笔记的意图 if (TextUtils.equals(Intent.ACTION_VIEW, intent.getAction())) { long noteId = intent.getLongExtra(Intent.EXTRA_UID, 0); mUserQuery = ""; - /** - * Starting from the searched result - */ + // 处理搜索结果中打开的笔记 if (intent.hasExtra(SearchManager.EXTRA_DATA_KEY)) { noteId = Long.parseLong(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY)); mUserQuery = intent.getStringExtra(SearchManager.USER_QUERY); } + // 检查笔记是否存在且可见 if (!DataUtils.visibleInNoteDatabase(getContentResolver(), noteId, Notes.TYPE_NOTE)) { Intent jump = new Intent(this, NotesListActivity.class); startActivity(jump); @@ -211,11 +205,14 @@ public class NoteEditActivity extends Activity implements OnClickListener, return false; } } + // 设置软键盘模式为隐藏并调整布局 getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); - } else if(TextUtils.equals(Intent.ACTION_INSERT_OR_EDIT, intent.getAction())) { - // New note + } + // 处理插入或编辑笔记的意图 + else if(TextUtils.equals(Intent.ACTION_INSERT_OR_EDIT, intent.getAction())) { + // 新建笔记 long folderId = intent.getLongExtra(Notes.INTENT_EXTRA_FOLDER_ID, 0); int widgetId = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); @@ -224,7 +221,7 @@ public class NoteEditActivity extends Activity implements OnClickListener, int bgResId = intent.getIntExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, ResourceParser.getDefaultBgId(this)); - // Parse call-record note + // 处理通话记录笔记 String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER); long callDate = intent.getLongExtra(Notes.INTENT_EXTRA_CALL_DATE, 0); if (callDate != 0 && phoneNumber != null) { @@ -232,6 +229,7 @@ public class NoteEditActivity extends Activity implements OnClickListener, Log.w(TAG, "The call record number is null"); } long noteId = 0; + // 检查是否已存在该通话记录笔记 if ((noteId = DataUtils.getNoteIdByPhoneNumberAndCallDate(getContentResolver(), phoneNumber, callDate)) > 0) { mWorkingNote = WorkingNote.load(this, noteId); @@ -250,6 +248,7 @@ public class NoteEditActivity extends Activity implements OnClickListener, bgResId); } + // 设置软键盘模式为可见并调整布局 getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); @@ -258,6 +257,7 @@ public class NoteEditActivity extends Activity implements OnClickListener, finish(); return false; } + // 设置笔记设置变化监听器 mWorkingNote.setOnSettingStatusChangedListener(this); return true; } @@ -268,33 +268,44 @@ public class NoteEditActivity extends Activity implements OnClickListener, initNoteScreen(); } + /** + * 初始化笔记编辑界面 + */ private void initNoteScreen() { + // 设置编辑框文本样式 mNoteEditor.setTextAppearance(this, TextAppearanceResources .getTexAppearanceResource(mFontSizeId)); + + // 根据笔记模式切换界面 if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { switchToListMode(mWorkingNote.getContent()); } else { mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery)); mNoteEditor.setSelection(mNoteEditor.getText().length()); } + + // 重置背景颜色选择状态 for (Integer id : sBgSelectorSelectionMap.keySet()) { findViewById(sBgSelectorSelectionMap.get(id)).setVisibility(View.GONE); } + + // 应用背景和标题样式 mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId()); mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId()); - + + // 设置最后修改时间 mNoteHeaderHolder.tvModified.setText(DateUtils.formatDateTime(this, mWorkingNote.getModifiedDate(), DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_YEAR)); - - /** - * TODO: Add the menu for setting alert. Currently disable it because the DateTimePicker - * is not ready - */ + + // 显示提醒信息 showAlertHeader(); } + /** + * 显示提醒头部信息 + */ private void showAlertHeader() { if (mWorkingNote.hasClockAlert()) { long time = System.currentTimeMillis(); @@ -321,11 +332,7 @@ public class NoteEditActivity extends Activity implements OnClickListener, @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); - /** - * For new note without note id, we should firstly save it to - * generate a id. If the editing note is not worth saving, there - * is no id which is equivalent to create new note - */ + // 保存新笔记到数据库以生成ID if (!mWorkingNote.existInDatabase()) { saveNote(); } @@ -335,12 +342,14 @@ public class NoteEditActivity extends Activity implements OnClickListener, @Override public boolean dispatchTouchEvent(MotionEvent ev) { + // 点击背景时隐藏颜色选择面板 if (mNoteBgColorSelector.getVisibility() == View.VISIBLE && !inRangeOfView(mNoteBgColorSelector, ev)) { mNoteBgColorSelector.setVisibility(View.GONE); return true; } + // 点击背景时隐藏字体大小选择面板 if (mFontSizeSelector.getVisibility() == View.VISIBLE && !inRangeOfView(mFontSizeSelector, ev)) { mFontSizeSelector.setVisibility(View.GONE); @@ -349,6 +358,9 @@ public class NoteEditActivity extends Activity implements OnClickListener, return super.dispatchTouchEvent(ev); } + /** + * 检查触摸事件是否在指定视图范围内 + */ private boolean inRangeOfView(View view, MotionEvent ev) { int []location = new int[2]; view.getLocationOnScreen(location); @@ -358,11 +370,14 @@ public class NoteEditActivity extends Activity implements OnClickListener, || ev.getX() > (x + view.getWidth()) || ev.getY() < y || ev.getY() > (y + view.getHeight())) { - return false; - } + return false; + } return true; } + /** + * 初始化界面资源 + */ private void initResources() { mHeadViewPanel = findViewById(R.id.note_title); mNoteHeaderHolder = new HeadViewHolder(); @@ -374,500 +389,16 @@ public class NoteEditActivity extends Activity implements OnClickListener, mNoteEditor = (EditText) findViewById(R.id.note_edit_view); mNoteEditorPanel = findViewById(R.id.sv_note_edit); mNoteBgColorSelector = findViewById(R.id.note_bg_color_selector); + + // 设置背景颜色 选择按钮点击事件 for (int id : sBgSelectorBtnsMap.keySet()) { ImageView iv = (ImageView) findViewById(id); iv.setOnClickListener(this); } mFontSizeSelector = findViewById(R.id.font_size_selector); + // 设置字体大小选择按钮点击事件 for (int id : sFontSizeBtnsMap.keySet()) { View view = findViewById(id); view.setOnClickListener(this); - }; - mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); - mFontSizeId = mSharedPrefs.getInt(PREFERENCE_FONT_SIZE, ResourceParser.BG_DEFAULT_FONT_SIZE); - /** - * HACKME: Fix bug of store the resource id in shared preference. - * The id may larger than the length of resources, in this case, - * return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE} - */ - if(mFontSizeId >= TextAppearanceResources.getResourcesSize()) { - mFontSizeId = ResourceParser.BG_DEFAULT_FONT_SIZE; - } - mEditTextList = (LinearLayout) findViewById(R.id.note_edit_list); - } - - @Override - protected void onPause() { - super.onPause(); - if(saveNote()) { - Log.d(TAG, "Note data was saved with length:" + mWorkingNote.getContent().length()); - } - clearSettingState(); - } - - private void updateWidget() { - Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE); - if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_2X) { - intent.setClass(this, NoteWidgetProvider_2x.class); - } else if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_4X) { - intent.setClass(this, NoteWidgetProvider_4x.class); - } else { - Log.e(TAG, "Unspported widget type"); - return; - } - - intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { - mWorkingNote.getWidgetId() - }); - - sendBroadcast(intent); - setResult(RESULT_OK, intent); - } - - public void onClick(View v) { - int id = v.getId(); - if (id == R.id.btn_set_bg_color) { - mNoteBgColorSelector.setVisibility(View.VISIBLE); - findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( - - View.VISIBLE); - } else if (sBgSelectorBtnsMap.containsKey(id)) { - findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( - View.GONE); - mWorkingNote.setBgColorId(sBgSelectorBtnsMap.get(id)); - mNoteBgColorSelector.setVisibility(View.GONE); - } else if (sFontSizeBtnsMap.containsKey(id)) { - findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.GONE); - mFontSizeId = sFontSizeBtnsMap.get(id); - mSharedPrefs.edit().putInt(PREFERENCE_FONT_SIZE, mFontSizeId).commit(); - findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.VISIBLE); - if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { - getWorkingText(); - switchToListMode(mWorkingNote.getContent()); - } else { - mNoteEditor.setTextAppearance(this, - TextAppearanceResources.getTexAppearanceResource(mFontSizeId)); - } - mFontSizeSelector.setVisibility(View.GONE); - } - } - - @Override - public void onBackPressed() { - if(clearSettingState()) { - return; - } - - saveNote(); - super.onBackPressed(); - } - - private boolean clearSettingState() { - if (mNoteBgColorSelector.getVisibility() == View.VISIBLE) { - mNoteBgColorSelector.setVisibility(View.GONE); - return true; - } else if (mFontSizeSelector.getVisibility() == View.VISIBLE) { - mFontSizeSelector.setVisibility(View.GONE); - return true; - } - return false; - } - - public void onBackgroundColorChanged() { - findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( - View.VISIBLE); - mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId()); - mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId()); - } - - @Override - public boolean onPrepareOptionsMenu(Menu menu) { - if (isFinishing()) { - return true; - } - clearSettingState(); - menu.clear(); - if (mWorkingNote.getFolderId() == Notes.ID_CALL_RECORD_FOLDER) { - getMenuInflater().inflate(R.menu.call_note_edit, menu); - } else { - getMenuInflater().inflate(R.menu.note_edit, menu); - } - if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { - menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_normal_mode); - } else { - menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_list_mode); - } - if (mWorkingNote.hasClockAlert()) { - menu.findItem(R.id.menu_alert).setVisible(false); - } else { - menu.findItem(R.id.menu_delete_remind).setVisible(false); - } - return true; - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case R.id.menu_new_note: - createNewNote(); - break; - case R.id.menu_delete: - AlertDialog.Builder builder = new AlertDialog.Builder(this); - builder.setTitle(getString(R.string.alert_title_delete)); - builder.setIcon(android.R.drawable.ic_dialog_alert); - builder.setMessage(getString(R.string.alert_message_delete_note)); - builder.setPositiveButton(android.R.string.ok, - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int which) { - deleteCurrentNote(); - finish(); - } - }); - builder.setNegativeButton(android.R.string.cancel, null); - builder.show(); - break; - case R.id.menu_font_size: - mFontSizeSelector.setVisibility(View.VISIBLE); - findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.VISIBLE); - break; - case R.id.menu_list_mode: - mWorkingNote.setCheckListMode(mWorkingNote.getCheckListMode() == 0 ? - TextNote.MODE_CHECK_LIST : 0); - break; - case R.id.menu_share: - getWorkingText(); - sendTo(this, mWorkingNote.getContent()); - break; - case R.id.menu_send_to_desktop: - sendToDesktop(); - break; - case R.id.menu_alert: - setReminder(); - break; - case R.id.menu_delete_remind: - mWorkingNote.setAlertDate(0, false); - break; - default: - break; - } - return true; - } - - private void setReminder() { - DateTimePickerDialog d = new DateTimePickerDialog(this, System.currentTimeMillis()); - d.setOnDateTimeSetListener(new OnDateTimeSetListener() { - public void OnDateTimeSet(AlertDialog dialog, long date) { - mWorkingNote.setAlertDate(date , true); - } - }); - d.show(); - } - - /** - * Share note to apps that support {@link Intent#ACTION_SEND} action - * and {@text/plain} type - */ - private void sendTo(Context context, String info) { - Intent intent = new Intent(Intent.ACTION_SEND); - intent.putExtra(Intent.EXTRA_TEXT, info); - intent.setType("text/plain"); - context.startActivity(intent); - } - - private void createNewNote() { - // Firstly, save current editing notes - saveNote(); - - // For safety, start a new NoteEditActivity - finish(); - Intent intent = new Intent(this, NoteEditActivity.class); - intent.setAction(Intent.ACTION_INSERT_OR_EDIT); - intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mWorkingNote.getFolderId()); - startActivity(intent); - } - - private void deleteCurrentNote() { - if (mWorkingNote.existInDatabase()) { - HashSet ids = new HashSet(); - long id = mWorkingNote.getNoteId(); - if (id != Notes.ID_ROOT_FOLDER) { - ids.add(id); - } else { - Log.d(TAG, "Wrong note id, should not happen"); - } - if (!isSyncMode()) { - if (!DataUtils.batchDeleteNotes(getContentResolver(), ids)) { - Log.e(TAG, "Delete Note error"); - } - } else { - if (!DataUtils.batchMoveToFolder(getContentResolver(), ids, Notes.ID_TRASH_FOLER)) { - Log.e(TAG, "Move notes to trash folder error, should not happens"); - } - } - } - mWorkingNote.markDeleted(true); - } - - private boolean isSyncMode() { - return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; - } - - public void onClockAlertChanged(long date, boolean set) { - /** - * User could set clock to an unsaved note, so before setting the - * alert clock, we should save the note first - */ - if (!mWorkingNote.existInDatabase()) { - saveNote(); - } - if (mWorkingNote.getNoteId() > 0) { - Intent intent = new Intent(this, AlarmReceiver.class); - intent.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mWorkingNote.getNoteId())); - PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0); - AlarmManager alarmManager = ((AlarmManager) getSystemService(ALARM_SERVICE)); - showAlertHeader(); - if(!set) { - alarmManager.cancel(pendingIntent); - } else { - alarmManager.set(AlarmManager.RTC_WAKEUP, date, pendingIntent); - } - } else { - /** - * There is the condition that user has input nothing (the note is - * not worthy saving), we have no note id, remind the user that he - * should input something - */ - Log.e(TAG, "Clock alert setting error"); - showToast(R.string.error_note_empty_for_clock); - } - } - - public void onWidgetChanged() { - updateWidget(); - } - - public void onEditTextDelete(int index, String text) { - int childCount = mEditTextList.getChildCount(); - if (childCount == 1) { - return; - } - - for (int i = index + 1; i < childCount; i++) { - ((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text)) - .setIndex(i - 1); - } - - mEditTextList.removeViewAt(index); - NoteEditText edit = null; - if(index == 0) { - edit = (NoteEditText) mEditTextList.getChildAt(0).findViewById( - R.id.et_edit_text); - } else { - edit = (NoteEditText) mEditTextList.getChildAt(index - 1).findViewById( - R.id.et_edit_text); - } - int length = edit.length(); - edit.append(text); - edit.requestFocus(); - edit.setSelection(length); - } - - public void onEditTextEnter(int index, String text) { - /** - * Should not happen, check for debug - */ - if(index > mEditTextList.getChildCount()) { - Log.e(TAG, "Index out of mEditTextList boundrary, should not happen"); - } - - View view = getListItem(text, index); - mEditTextList.addView(view, index); - NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); - edit.requestFocus(); - edit.setSelection(0); - for (int i = index + 1; i < mEditTextList.getChildCount(); i++) { - ((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text)) - .setIndex(i); - } - } - - private void switchToListMode(String text) { - mEditTextList.removeAllViews(); - String[] items = text.split("\n"); - int index = 0; - for (String item : items) { - if(!TextUtils.isEmpty(item)) { - mEditTextList.addView(getListItem(item, index)); - index++; - } - } - mEditTextList.addView(getListItem("", index)); - mEditTextList.getChildAt(index).findViewById(R.id.et_edit_text).requestFocus(); - - mNoteEditor.setVisibility(View.GONE); - mEditTextList.setVisibility(View.VISIBLE); - } - - private Spannable getHighlightQueryResult(String fullText, String userQuery) { - SpannableString spannable = new SpannableString(fullText == null ? "" : fullText); - if (!TextUtils.isEmpty(userQuery)) { - mPattern = Pattern.compile(userQuery); - Matcher m = mPattern.matcher(fullText); - int start = 0; - while (m.find(start)) { - spannable.setSpan( - new BackgroundColorSpan(this.getResources().getColor( - R.color.user_query_highlight)), m.start(), m.end(), - Spannable.SPAN_INCLUSIVE_EXCLUSIVE); - start = m.end(); - } - } - return spannable; - } - - private View getListItem(String item, int index) { - View view = LayoutInflater.from(this).inflate(R.layout.note_edit_list_item, null); - final NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); - edit.setTextAppearance(this, TextAppearanceResources.getTexAppearanceResource(mFontSizeId)); - CheckBox cb = ((CheckBox) view.findViewById(R.id.cb_edit_item)); - cb.setOnCheckedChangeListener(new OnCheckedChangeListener() { - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - if (isChecked) { - edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); - } else { - edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG); - } - } - }); - - if (item.startsWith(TAG_CHECKED)) { - cb.setChecked(true); - edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); - item = item.substring(TAG_CHECKED.length(), item.length()).trim(); - } else if (item.startsWith(TAG_UNCHECKED)) { - cb.setChecked(false); - edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG); - item = item.substring(TAG_UNCHECKED.length(), item.length()).trim(); - } - - edit.setOnTextViewChangeListener(this); - edit.setIndex(index); - edit.setText(getHighlightQueryResult(item, mUserQuery)); - return view; - } - - public void onTextChange(int index, boolean hasText) { - if (index >= mEditTextList.getChildCount()) { - Log.e(TAG, "Wrong index, should not happen"); - return; - } - if(hasText) { - mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.VISIBLE); - } else { - mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.GONE); - } - } - - public void onCheckListModeChanged(int oldMode, int newMode) { - if (newMode == TextNote.MODE_CHECK_LIST) { - switchToListMode(mNoteEditor.getText().toString()); - } else { - if (!getWorkingText()) { - mWorkingNote.setWorkingText(mWorkingNote.getContent().replace(TAG_UNCHECKED + " ", - "")); - } - mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery)); - mEditTextList.setVisibility(View.GONE); - mNoteEditor.setVisibility(View.VISIBLE); - } - } - - private boolean getWorkingText() { - boolean hasChecked = false; - if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < mEditTextList.getChildCount(); i++) { - View view = mEditTextList.getChildAt(i); - NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); - if (!TextUtils.isEmpty(edit.getText())) { - if (((CheckBox) view.findViewById(R.id.cb_edit_item)).isChecked()) { - sb.append(TAG_CHECKED).append(" ").append(edit.getText()).append("\n"); - hasChecked = true; - } else { - sb.append(TAG_UNCHECKED).append(" ").append(edit.getText()).append("\n"); - } - } - } - mWorkingNote.setWorkingText(sb.toString()); - } else { - mWorkingNote.setWorkingText(mNoteEditor.getText().toString()); - } - return hasChecked; - } - - private boolean saveNote() { - getWorkingText(); - boolean saved = mWorkingNote.saveNote(); - if (saved) { - /** - * There are two modes from List view to edit view, open one note, - * create/edit a node. Opening node requires to the original - * position in the list when back from edit view, while creating a - * new node requires to the top of the list. This code - * {@link #RESULT_OK} is used to identify the create/edit state - */ - setResult(RESULT_OK); - } - return saved; - } - - private void sendToDesktop() { - /** - * Before send message to home, we should make sure that current - * editing note is exists in databases. So, for new note, firstly - * save it - */ - if (!mWorkingNote.existInDatabase()) { - saveNote(); - } - - if (mWorkingNote.getNoteId() > 0) { - Intent sender = new Intent(); - Intent shortcutIntent = new Intent(this, NoteEditActivity.class); - shortcutIntent.setAction(Intent.ACTION_VIEW); - shortcutIntent.putExtra(Intent.EXTRA_UID, mWorkingNote.getNoteId()); - sender.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); - sender.putExtra(Intent.EXTRA_SHORTCUT_NAME, - makeShortcutIconTitle(mWorkingNote.getContent())); - sender.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, - Intent.ShortcutIconResource.fromContext(this, R.drawable.icon_app)); - sender.putExtra("duplicate", true); - sender.setAction("com.android.launcher.action.INSTALL_SHORTCUT"); - showToast(R.string.info_note_enter_desktop); - sendBroadcast(sender); - } else { - /** - * There is the condition that user has input nothing (the note is - * not worthy saving), we have no note id, remind the user that he - * should input something - */ - Log.e(TAG, "Send to desktop error"); - showToast(R.string.error_note_empty_for_send_to_desktop); - } - } - - private String makeShortcutIconTitle(String content) { - content = content.replace(TAG_CHECKED, ""); - content = content.replace(TAG_UNCHECKED, ""); - return content.length() > SHORTCUT_ICON_TITLE_MAX_LEN ? content.substring(0, - SHORTCUT_ICON_TITLE_MAX_LEN) : content; - } - - private void showToast(int resId) { - showToast(resId, Toast.LENGTH_SHORT); - } - - private void showToast(int resId, int duration) { - Toast.makeText(this, resId, duration).show(); - } -} + }; \ No newline at end of file diff --git a/src/Notes-master/app/src/main/java/net/micode/notes/ui/NoteEditText.java b/src/Notes-master/app/src/main/java/net/micode/notes/ui/NoteEditText.java index 2afe2a8..91de473 100644 --- a/src/Notes-master/app/src/main/java/net/micode/notes/ui/NoteEditText.java +++ b/src/Notes-master/app/src/main/java/net/micode/notes/ui/NoteEditText.java @@ -1,17 +1,9 @@ /* * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * 版权声明:本代码受Apache许可证2.0版本保护 + * 您可以在遵守许可证的前提下使用、修改和分发本代码 + * 许可证全文可在http://www.apache.org/licenses/LICENSE-2.0获取 */ package net.micode.notes.ui; @@ -37,63 +29,90 @@ import net.micode.notes.R; import java.util.HashMap; import java.util.Map; +/** + * 笔记编辑文本框 + * 功能:自定义EditText,扩展了特殊功能,如链接识别、清单模式编辑等 + * 特点:支持处理Enter和Delete按键事件、URL链接上下文菜单、焦点变化监听 + */ public class NoteEditText extends EditText { private static final String TAG = "NoteEditText"; - private int mIndex; - private int mSelectionStartBeforeDelete; + private int mIndex; // 当前编辑文本框在列表中的索引 + private int mSelectionStartBeforeDelete; // 删除操作前的光标位置 - private static final String SCHEME_TEL = "tel:" ; - private static final String SCHEME_HTTP = "http:" ; - private static final String SCHEME_EMAIL = "mailto:" ; + // 支持的URL协议前缀 + private static final String SCHEME_TEL = "tel:" ; // 电话协议 + private static final String SCHEME_HTTP = "http:" ; // HTTP协议 + private static final String SCHEME_EMAIL = "mailto:" ; // 邮件协议 + // URL协议与菜单项文本资源映射 private static final Map sSchemaActionResMap = new HashMap(); static { - sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel); - sSchemaActionResMap.put(SCHEME_HTTP, R.string.note_link_web); - sSchemaActionResMap.put(SCHEME_EMAIL, R.string.note_link_email); + sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel); // 电话链接菜单项 + sSchemaActionResMap.put(SCHEME_HTTP, R.string.note_link_web); // 网页链接菜单项 + sSchemaActionResMap.put(SCHEME_EMAIL, R.string.note_link_email); // 邮件链接菜单项 } /** - * Call by the {@link NoteEditActivity} to delete or add edit text + * 文本视图变化监听器接口 + * 用于与父容器(如NoteEditActivity)通信,处理特殊的编辑操作 */ public interface OnTextViewChangeListener { /** - * Delete current edit text when {@link KeyEvent#KEYCODE_DEL} happens - * and the text is null + * 当按下删除键且文本为空时,删除当前编辑文本框 + * @param index 当前编辑文本框索引 + * @param text 当前文本内容 */ void onEditTextDelete(int index, String text); /** - * Add edit text after current edit text when {@link KeyEvent#KEYCODE_ENTER} - * happen + * 当按下回车键时,在当前位置后添加新的编辑文本框 + * @param index 当前编辑文本框索引 + * @param text 当前光标后的文本内容 */ void onEditTextEnter(int index, String text); /** - * Hide or show item option when text change + * 当文本内容变化时,隐藏或显示项目选项 + * @param index 当前编辑文本框索引 + * @param hasText 是否有文本内容 */ void onTextChange(int index, boolean hasText); } private OnTextViewChangeListener mOnTextViewChangeListener; + /** + * 构造函数(单参数) + */ public NoteEditText(Context context) { super(context, null); mIndex = 0; } + /** + * 设置当前编辑文本框在列表中的索引 + */ public void setIndex(int index) { mIndex = index; } + /** + * 设置文本视图变化监听器 + */ public void setOnTextViewChangeListener(OnTextViewChangeListener listener) { mOnTextViewChangeListener = listener; } + /** + * 构造函数(双参数) + */ public NoteEditText(Context context, AttributeSet attrs) { super(context, attrs, android.R.attr.editTextStyle); } + /** + * 构造函数(三参数) + */ public NoteEditText(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // TODO Auto-generated constructor stub @@ -101,9 +120,10 @@ public class NoteEditText extends EditText { @Override public boolean onTouchEvent(MotionEvent event) { + // 处理触摸事件,主要用于精确定位文本选择位置 switch (event.getAction()) { case MotionEvent.ACTION_DOWN: - + // 计算触摸点对应的文本位置 int x = (int) event.getX(); int y = (int) event.getY(); x -= getTotalPaddingLeft(); @@ -123,13 +143,16 @@ public class NoteEditText extends EditText { @Override public boolean onKeyDown(int keyCode, KeyEvent event) { + // 处理按键按下事件 switch (keyCode) { case KeyEvent.KEYCODE_ENTER: + // 回车键由onKeyUp处理,这里返回false if (mOnTextViewChangeListener != null) { return false; } break; case KeyEvent.KEYCODE_DEL: + // 记录删除前的光标位置 mSelectionStartBeforeDelete = getSelectionStart(); break; default: @@ -140,8 +163,10 @@ public class NoteEditText extends EditText { @Override public boolean onKeyUp(int keyCode, KeyEvent event) { + // 处理按键释放事件 switch(keyCode) { case KeyEvent.KEYCODE_DEL: + // 处理删除键:当光标在文本开始位置且不是第一个编辑框时,删除当前编辑框 if (mOnTextViewChangeListener != null) { if (0 == mSelectionStartBeforeDelete && mIndex != 0) { mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString()); @@ -152,6 +177,7 @@ public class NoteEditText extends EditText { } break; case KeyEvent.KEYCODE_ENTER: + // 处理回车键:将当前文本在光标处分割,后半部分传递给下一个编辑框 if (mOnTextViewChangeListener != null) { int selectionStart = getSelectionStart(); String text = getText().subSequence(selectionStart, length()).toString(); @@ -169,6 +195,7 @@ public class NoteEditText extends EditText { @Override protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { + // 处理焦点变化事件,通知监听器当前文本状态 if (mOnTextViewChangeListener != null) { if (!focused && TextUtils.isEmpty(getText())) { mOnTextViewChangeListener.onTextChange(mIndex, false); @@ -181,6 +208,7 @@ public class NoteEditText extends EditText { @Override protected void onCreateContextMenu(ContextMenu menu) { + // 创建上下文菜单,处理URL链接 if (getText() instanceof Spanned) { int selStart = getSelectionStart(); int selEnd = getSelectionEnd(); @@ -188,9 +216,11 @@ public class NoteEditText extends EditText { int min = Math.min(selStart, selEnd); int max = Math.max(selStart, selEnd); + // 获取选中文本中的URLSpan final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class); if (urls.length == 1) { int defaultResId = 0; + // 根据URL协议选择合适的菜单项文本 for(String schema: sSchemaActionResMap.keySet()) { if(urls[0].getURL().indexOf(schema) >= 0) { defaultResId = sSchemaActionResMap.get(schema); @@ -202,10 +232,11 @@ public class NoteEditText extends EditText { defaultResId = R.string.note_link_other; } + // 添加菜单项 并设置点击监听器 menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener( new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { - // goto a new intent + // 点击菜单项时执行URLSpan的onClick方法 urls[0].onClick(NoteEditText.this); return true; } @@ -214,4 +245,4 @@ public class NoteEditText extends EditText { } super.onCreateContextMenu(menu); } -} +} \ No newline at end of file diff --git a/src/Notes-master/app/src/main/java/net/micode/notes/ui/NoteItemData.java b/src/Notes-master/app/src/main/java/net/micode/notes/ui/NoteItemData.java index 0f5a878..11ece95 100644 --- a/src/Notes-master/app/src/main/java/net/micode/notes/ui/NoteItemData.java +++ b/src/Notes-master/app/src/main/java/net/micode/notes/ui/NoteItemData.java @@ -1,17 +1,9 @@ /* * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * 版权声明:本代码受Apache许可证2.0版本保护 + * 您可以在遵守许可证的前提下使用、修改和分发本代码 + * 许可证全文可在http://www.apache.org/licenses/LICENSE-2.0获取 */ package net.micode.notes.ui; @@ -25,58 +17,72 @@ import net.micode.notes.data.Notes; import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.tool.DataUtils; - +/** + * 笔记项数据类 + * 功能:封装笔记列表项的数据模型,提供笔记信息的存储和访问接口 + * 特点:包含笔记基本信息、位置标识、类型判断等功能 + */ public class NoteItemData { - static final String [] PROJECTION = new String [] { - NoteColumns.ID, - NoteColumns.ALERTED_DATE, - NoteColumns.BG_COLOR_ID, - NoteColumns.CREATED_DATE, - NoteColumns.HAS_ATTACHMENT, - NoteColumns.MODIFIED_DATE, - NoteColumns.NOTES_COUNT, - NoteColumns.PARENT_ID, - NoteColumns.SNIPPET, - NoteColumns.TYPE, - NoteColumns.WIDGET_ID, - NoteColumns.WIDGET_TYPE, + // 数据库查询投影:指定要查询的列 + static final String[] PROJECTION = new String[]{ + NoteColumns.ID, // 笔记ID + NoteColumns.ALERTED_DATE, // 提醒日期 + NoteColumns.BG_COLOR_ID, // 背景颜色ID + NoteColumns.CREATED_DATE, // 创建日期 + NoteColumns.HAS_ATTACHMENT, // 是否有附件 + NoteColumns.MODIFIED_DATE, // 修改日期 + NoteColumns.NOTES_COUNT, // 子笔记数量(用于文件夹) + NoteColumns.PARENT_ID, // 父文件夹ID + NoteColumns.SNIPPET, // 笔记摘要 + NoteColumns.TYPE, // 笔记类型 + NoteColumns.WIDGET_ID, // 桌面小部件ID + NoteColumns.WIDGET_TYPE, // 桌面小部件类型 }; - private static final int ID_COLUMN = 0; - private static final int ALERTED_DATE_COLUMN = 1; - private static final int BG_COLOR_ID_COLUMN = 2; - private static final int CREATED_DATE_COLUMN = 3; - private static final int HAS_ATTACHMENT_COLUMN = 4; - private static final int MODIFIED_DATE_COLUMN = 5; - private static final int NOTES_COUNT_COLUMN = 6; - private static final int PARENT_ID_COLUMN = 7; - private static final int SNIPPET_COLUMN = 8; - private static final int TYPE_COLUMN = 9; - private static final int WIDGET_ID_COLUMN = 10; - private static final int WIDGET_TYPE_COLUMN = 11; - - private long mId; - private long mAlertDate; - private int mBgColorId; - private long mCreatedDate; - private boolean mHasAttachment; - private long mModifiedDate; - private int mNotesCount; - private long mParentId; - private String mSnippet; - private int mType; - private int mWidgetId; - private int mWidgetType; - private String mName; - private String mPhoneNumber; - - private boolean mIsLastItem; - private boolean mIsFirstItem; - private boolean mIsOnlyOneItem; - private boolean mIsOneNoteFollowingFolder; - private boolean mIsMultiNotesFollowingFolder; - + // 列索引常量,便于代码引用 + private static final int ID_COLUMN = 0; // 笔记ID列索引 + private static final int ALERTED_DATE_COLUMN = 1; // 提醒日期列索引 + private static final int BG_COLOR_ID_COLUMN = 2; // 背景颜色ID列索引 + private static final int CREATED_DATE_COLUMN = 3; // 创建日期列索引 + private static final int HAS_ATTACHMENT_COLUMN = 4; // 附件标志列索引 + private static final int MODIFIED_DATE_COLUMN = 5; // 修改日期列索引 + private static final int NOTES_COUNT_COLUMN = 6; // 子笔记数量列索引 + private static final int PARENT_ID_COLUMN = 7; // 父文件夹ID列索引 + private static final int SNIPPET_COLUMN = 8; // 摘要列索引 + private static final int TYPE_COLUMN = 9; // 类型列索引 + private static final int WIDGET_ID_COLUMN = 10; // 小部件ID列索引 + private static final int WIDGET_TYPE_COLUMN = 11; // 小部件类型列索引 + + // 笔记基本信息 + private long mId; // 笔记ID + private long mAlertDate; // 提醒日期 + private int mBgColorId; // 背景颜色ID + private long mCreatedDate; // 创建日期 + private boolean mHasAttachment; // 是否有附件 + private long mModifiedDate; // 修改日期 + private int mNotesCount; // 子笔记数量(文件夹) + private long mParentId; // 父文件夹ID + private String mSnippet; // 笔记摘要 + private int mType; // 笔记类型 + private int mWidgetId; // 桌面小部件ID + private int mWidgetType; // 桌面小部件类型 + private String mName; // 联系人名称(通话记录笔记) + private String mPhoneNumber; // 电话号码(通话记录笔记) + + // 列表位置标识 + private boolean mIsLastItem; // 是否为列表最后一项 + private boolean mIsFirstItem; // 是否为列表第一项 + private boolean mIsOnlyOneItem; // 是否为列表唯一一项 + private boolean mIsOneNoteFollowingFolder; // 是否为文件夹后的单条笔记 + private boolean mIsMultiNotesFollowingFolder; // 是否为文件夹后的多条笔记 + + /** + * 构造函数 + * @param context 上下文对象 + * @param cursor 包含笔记数据的数据库游标 + */ public NoteItemData(Context context, Cursor cursor) { + // 从游标中获取基本笔记信息 mId = cursor.getLong(ID_COLUMN); mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN); mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN); @@ -86,13 +92,17 @@ public class NoteItemData { mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN); mParentId = cursor.getLong(PARENT_ID_COLUMN); mSnippet = cursor.getString(SNIPPET_COLUMN); + + // 处理清单模式标签 mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace( NoteEditActivity.TAG_UNCHECKED, ""); + mType = cursor.getInt(TYPE_COLUMN); mWidgetId = cursor.getInt(WIDGET_ID_COLUMN); mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN); mPhoneNumber = ""; + // 处理通话记录笔记 if (mParentId == Notes.ID_CALL_RECORD_FOLDER) { mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId); if (!TextUtils.isEmpty(mPhoneNumber)) { @@ -106,9 +116,14 @@ public class NoteItemData { if (mName == null) { mName = ""; } + // 检查并设置列表位置标识 checkPostion(cursor); } + /** + * 检查并设置笔记在列表中的位置标识 + * @param cursor 数据库游标 + */ private void checkPostion(Cursor cursor) { mIsLastItem = cursor.isLast() ? true : false; mIsFirstItem = cursor.isFirst() ? true : false; @@ -116,6 +131,7 @@ public class NoteItemData { mIsMultiNotesFollowingFolder = false; mIsOneNoteFollowingFolder = false; + // 检查是否为文件夹后的笔记项 if (mType == Notes.TYPE_NOTE && !mIsFirstItem) { int position = cursor.getPosition(); if (cursor.moveToPrevious()) { @@ -134,91 +150,180 @@ public class NoteItemData { } } + /** + * 判断是否为文件夹后的单条笔记 + * @return true表示是文件夹后的单条笔记 + */ public boolean isOneFollowingFolder() { return mIsOneNoteFollowingFolder; } + /** + * 判断是否为文件夹后的多条笔记 + * @return true表示是文件夹后的多条笔记 + */ public boolean isMultiFollowingFolder() { return mIsMultiNotesFollowingFolder; } + /** + * 判断是否为列表最后一项 + * @return true表示是列表最后一项 + */ public boolean isLast() { return mIsLastItem; } + /** + * 获取通话记录的联系人名称 + * @return 联系人名称或电话号码 + */ public String getCallName() { return mName; } + /** + * 判断是否为列表第一项 + * @return true表示是列表第一项 + */ public boolean isFirst() { return mIsFirstItem; } + /** + * 判断是否为列表唯一一项 + * @return true表示是列表唯一一项 + */ public boolean isSingle() { return mIsOnlyOneItem; } + /** + * 获取笔记ID + * @return 笔记ID + */ public long getId() { return mId; } + /** + * 获取提醒日期 + * @return 提醒日期(毫秒值) + */ public long getAlertDate() { return mAlertDate; } + /** + * 获取创建日期 + * @return 创建日期(毫秒值) + */ public long getCreatedDate() { return mCreatedDate; } + /** + * 判断是否有附件 + * @return true表示有附件 + */ public boolean hasAttachment() { return mHasAttachment; } + /** + * 获取修改日期 + * @return 修改日期(毫秒值) + */ public long getModifiedDate() { return mModifiedDate; } + /** + * 获取背景颜色ID + * @return 背景颜色ID + */ public int getBgColorId() { return mBgColorId; } + /** + * 获取父文件夹ID + * @return 父文件夹ID + */ public long getParentId() { return mParentId; } + /** + * 获取子笔记数量(用于文件夹) + * @return 子笔记数量 + */ public int getNotesCount() { return mNotesCount; } - public long getFolderId () { + /** + * 获取文件夹ID(与父文件夹ID相同) + * @return 文件夹ID + */ + public long getFolderId() { return mParentId; } + /** + * 获取笔记类型 + * @return 笔记类型 + */ public int getType() { return mType; } + /** + * 获取桌面小部件类型 + * @return 小部件类型 + */ public int getWidgetType() { return mWidgetType; } + /** + * 获取桌面小部件ID + * @return 小部件ID + */ public int getWidgetId() { return mWidgetId; } + /** + * 获取笔记摘要 + * @return 笔记摘要 + */ public String getSnippet() { return mSnippet; } + /** + * 判断是否设置了提醒 + * @return true表示设置了提醒 + */ public boolean hasAlert() { return (mAlertDate > 0); } + /** + * 判断是否为通话 记录笔记 + * @return true表示是通话记录笔记 + */ public boolean isCallRecord() { return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber)); } + /** + * 从游标中获取笔记类型 + * @param cursor 数据库游标 + * @return 笔记类型 + */ public static int getNoteType(Cursor cursor) { return cursor.getInt(TYPE_COLUMN); } -} +} \ No newline at end of file diff --git a/src/Notes-master/app/src/main/java/net/micode/notes/ui/NotesListActivity.java b/src/Notes-master/app/src/main/java/net/micode/notes/ui/NotesListActivity.java index e843aec..5501816 100644 --- a/src/Notes-master/app/src/main/java/net/micode/notes/ui/NotesListActivity.java +++ b/src/Notes-master/app/src/main/java/net/micode/notes/ui/NotesListActivity.java @@ -1,17 +1,14 @@ /* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * 版权声明:2010-2011年,MiCode开源社区(www.micode.net)保留所有权利 * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * 本代码基于Apache许可证2.0版本发布("许可证"); + * 您可以在遵守许可证的前提下使用本文件; + * 您可以从以下地址获取许可证副本: * * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * 除非法律要求或书面同意,否则本软件根据许可证分发时按"原样"提供, + * 不附带任何明示或暗示的保证或条件。请查看许可证,了解具体的权限和限制。 */ package net.micode.notes.ui; @@ -56,7 +53,6 @@ import android.widget.AdapterView.OnItemLongClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; -import android.widget.PopupMenu; import android.widget.TextView; import android.widget.Toast; @@ -78,96 +74,99 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashSet; +/** + * 便签列表主活动类 + * 负责展示便签列表、处理便签文件夹操作、实现便签的增删改查功能 + */ public class NotesListActivity extends Activity implements OnClickListener, OnItemLongClickListener { + + // 查询令牌常量,用于标识不同的异步查询操作 private static final int FOLDER_NOTE_LIST_QUERY_TOKEN = 0; - - private static final int FOLDER_LIST_QUERY_TOKEN = 1; - + private static final int FOLDER_LIST_QUERY_TOKEN = 1; + + // 上下文菜单选项ID private static final int MENU_FOLDER_DELETE = 0; - private static final int MENU_FOLDER_VIEW = 1; - private static final int MENU_FOLDER_CHANGE_NAME = 2; - + + // 首选项键:用于标记是否已添加应用介绍便签 private static final String PREFERENCE_ADD_INTRODUCTION = "net.micode.notes.introduction"; - + + // 列表编辑状态枚举 private enum ListEditState { - NOTE_LIST, SUB_FOLDER, CALL_RECORD_FOLDER + NOTE_LIST, // 主便签列表状态 + SUB_FOLDER, // 子文件夹状态 + CALL_RECORD_FOLDER // 通话记录文件夹状态 }; - - private ListEditState mState; - - private BackgroundQueryHandler mBackgroundQueryHandler; - - private NotesListAdapter mNotesListAdapter; - - private ListView mNotesListView; - - private Button mAddNewNote; - - private boolean mDispatch; - - private int mOriginY; - - private int mDispatchY; - - private TextView mTitleBar; - - private long mCurrentFolderId; - - private ContentResolver mContentResolver; - - private ModeCallback mModeCallBack; - - private static final String TAG = "NotesListActivity"; - - public static final int NOTES_LISTVIEW_SCROLL_RATE = 30; - - private NoteItemData mFocusNoteDataItem; - + + // 成员变量定义 + private ListEditState mState; // 当前列表状态 + private BackgroundQueryHandler mBackgroundQueryHandler; // 异步查询处理器 + private NotesListAdapter mNotesListAdapter; // 便签列表适配器 + private ListView mNotesListView; // 便签列表视图 + private Button mAddNewNote; // 添加新便签按钮 + private boolean mDispatch; // 触摸事件分发标记 + private int mOriginY; // 触摸事件原始Y坐标 + private int mDispatchY; // 触摸事件分发Y坐标 + private TextView mTitleBar; // 标题栏文本 + private long mCurrentFolderId; // 当前文件夹ID + private ContentResolver mContentResolver; // 内容解析器 + private ModeCallback mModeCallBack; // 多选择模式回调 + private static final String TAG = "NotesListActivity"; // 日志标签 + public static final int NOTES_LISTVIEW_SCROLL_RATE = 30; // 列表滚动速率 + private NoteItemData mFocusNoteDataItem; // 聚焦的便签数据项 + + // 数据库查询条件常量 private static final String NORMAL_SELECTION = NoteColumns.PARENT_ID + "=?"; - private static final String ROOT_FOLDER_SELECTION = "(" + NoteColumns.TYPE + "<>" + Notes.TYPE_SYSTEM + " AND " + NoteColumns.PARENT_ID + "=?)" + " OR (" + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER + " AND " + NoteColumns.NOTES_COUNT + ">0)"; - + + // 活动结果请求码 private final static int REQUEST_CODE_OPEN_NODE = 102; - private final static int REQUEST_CODE_NEW_NODE = 103; + private final static int REQUEST_CODE_NEW_NODE = 103; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.note_list); - initResources(); - + initResources(); // 初始化资源 + /** - * Insert an introduction when user firstly use this application + * 当用户首次使用应用时插入介绍便签 + * 从raw资源文件读取介绍内容并保存为新便签 */ setAppInfoFromRawRes(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { + // 处理便签编辑活动返回结果 if (resultCode == RESULT_OK && (requestCode == REQUEST_CODE_OPEN_NODE || requestCode == REQUEST_CODE_NEW_NODE)) { - mNotesListAdapter.changeCursor(null); + mNotesListAdapter.changeCursor(null); // 刷新列表数据 } else { super.onActivityResult(requestCode, resultCode, data); } } + /** + * 从原始资源文件设置应用介绍信息 + * 首次启动时创建一个包含介绍内容的便签 + */ private void setAppInfoFromRawRes() { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); if (!sp.getBoolean(PREFERENCE_ADD_INTRODUCTION, false)) { StringBuilder sb = new StringBuilder(); InputStream in = null; try { - in = getResources().openRawResource(R.raw.introduction); + // 读取raw资源中的介绍文本 + in = getResources().openRawResource(R.raw.introduction); if (in != null) { InputStreamReader isr = new InputStreamReader(in); BufferedReader br = new BufferedReader(isr); - char [] buf = new char[1024]; + char[] buf = new char[1024]; int len = 0; while ((len = br.read(buf)) > 0) { sb.append(buf, 0, len); @@ -180,21 +179,22 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt e.printStackTrace(); return; } finally { - if(in != null) { + if (in != null) { try { in.close(); } catch (IOException e) { - // TODO Auto-generated catch block e.printStackTrace(); } } } + // 创建并保存介绍便签 WorkingNote note = WorkingNote.createEmptyNote(this, Notes.ID_ROOT_FOLDER, AppWidgetManager.INVALID_APPWIDGET_ID, Notes.TYPE_WIDGET_INVALIDE, ResourceParser.RED); note.setWorkingText(sb.toString()); if (note.saveNote()) { + // 标记已添加介绍便签 sp.edit().putBoolean(PREFERENCE_ADD_INTRODUCTION, true).commit(); } else { Log.e(TAG, "Save introduction note error"); @@ -206,13 +206,19 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt @Override protected void onStart() { super.onStart(); - startAsyncNotesListQuery(); + startAsyncNotesListQuery(); // 启动异步便签列表查询 } + /** + * 初始化界面资源和组件 + * 包括视图绑定、事件监听设置等 + */ private void initResources() { mContentResolver = this.getContentResolver(); mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver()); - mCurrentFolderId = Notes.ID_ROOT_FOLDER; + mCurrentFolderId = Notes.ID_ROOT_FOLDER; // 设置默认文件夹为根文件夹 + + // 初始化列表视图 mNotesListView = (ListView) findViewById(R.id.notes_list); mNotesListView.addFooterView(LayoutInflater.from(this).inflate(R.layout.note_list_footer, null), null, false); @@ -220,9 +226,13 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt mNotesListView.setOnItemLongClickListener(this); mNotesListAdapter = new NotesListAdapter(this); mNotesListView.setAdapter(mNotesListAdapter); + + // 初始化添加新便签按钮 mAddNewNote = (Button) findViewById(R.id.btn_new_note); mAddNewNote.setOnClickListener(this); mAddNewNote.setOnTouchListener(new NewNoteOnTouchListener()); + + // 初始化其他状态变量 mDispatch = false; mDispatchY = 0; mOriginY = 0; @@ -231,14 +241,23 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt mModeCallBack = new ModeCallback(); } + /** + * 多选择模式回调类 + * 实现ListView.MultiChoiceModeListener接口处理批量操作 + */ private class ModeCallback implements ListView.MultiChoiceModeListener, OnMenuItemClickListener { - private DropdownMenu mDropDownMenu; - private ActionMode mActionMode; - private MenuItem mMoveMenu; - + private DropdownMenu mDropDownMenu; // 下拉菜单 + private ActionMode mActionMode; // 操作模式 + + /** + * 创建操作模式时调用 + * 初始化操作模式菜单和自定义视图 + */ public boolean onCreateActionMode(ActionMode mode, Menu menu) { getMenuInflater().inflate(R.menu.note_list_options, menu); menu.findItem(R.id.delete).setOnMenuItemClickListener(this); + + // 设置移动菜单可见性 mMoveMenu = menu.findItem(R.id.move); if (mFocusNoteDataItem.getParentId() == Notes.ID_CALL_RECORD_FOLDER || DataUtils.getUserFolderCount(mContentResolver) == 0) { @@ -247,33 +266,40 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt mMoveMenu.setVisible(true); mMoveMenu.setOnMenuItemClickListener(this); } + mActionMode = mode; - mNotesListAdapter.setChoiceMode(true); + mNotesListAdapter.setChoiceMode(true); // 启用列表选择模式 mNotesListView.setLongClickable(false); - mAddNewNote.setVisibility(View.GONE); - + mAddNewNote.setVisibility(View.GONE); // 隐藏添加按钮 + + // 设置自定义操作模式视图 View customView = LayoutInflater.from(NotesListActivity.this).inflate( R.layout.note_list_dropdown_menu, null); mode.setCustomView(customView); mDropDownMenu = new DropdownMenu(NotesListActivity.this, (Button) customView.findViewById(R.id.selection_menu), R.menu.note_list_dropdown); - mDropDownMenu.setOnDropdownMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){ + mDropDownMenu.setOnDropdownMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { mNotesListAdapter.selectAll(!mNotesListAdapter.isAllSelected()); - updateMenu(); + updateMenu(); // 更新菜单状态 return true; } - }); return true; } + /** + * 更新菜单状态 + * 显示当前选中的便签数量 + */ private void updateMenu() { int selectedCount = mNotesListAdapter.getSelectedCount(); - // Update dropdown menu + // 更新下拉菜单标题 String format = getResources().getString(R.string.menu_select_title, selectedCount); mDropDownMenu.setTitle(format); + + // 更新全选/反选菜单项 MenuItem item = mDropDownMenu.findItem(R.id.action_select_all); if (item != null) { if (mNotesListAdapter.isAllSelected()) { @@ -287,15 +313,17 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt } public boolean onPrepareActionMode(ActionMode mode, Menu menu) { - // TODO Auto-generated method stub return false; } public boolean onActionItemClicked(ActionMode mode, MenuItem item) { - // TODO Auto-generated method stub return false; } + /** + * 操作模式销毁时调用 + * 恢复列表视图正常状态 + */ public void onDestroyActionMode(ActionMode mode) { mNotesListAdapter.setChoiceMode(false); mNotesListView.setLongClickable(true); @@ -306,12 +334,20 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt mActionMode.finish(); } + /** + * 项目选中状态改变时调用 + * 更新选中状态和菜单显示 + */ public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) { mNotesListAdapter.setCheckedItem(position, checked); updateMenu(); } + /** + * 菜单项点击处理 + * 处理删除和移动便签操作 + */ public boolean onMenuItemClick(MenuItem item) { if (mNotesListAdapter.getSelectedCount() == 0) { Toast.makeText(NotesListActivity.this, getString(R.string.menu_select_none), @@ -321,6 +357,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt switch (item.getItemId()) { case R.id.delete: + // 显示删除确认对话框 AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); builder.setTitle(getString(R.string.alert_title_delete)); builder.setIcon(android.R.drawable.ic_dialog_alert); @@ -330,14 +367,14 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { - batchDelete(); + batchDelete(); // 批量删除便签 } }); builder.setNegativeButton(android.R.string.cancel, null); builder.show(); break; case R.id.move: - startQueryDestinationFolders(); + startQueryDestinationFolders(); // 查询目标文件夹 break; default: return false; @@ -346,31 +383,32 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt } } + /** + * 新便签按钮触摸事件监听器 + * 处理按钮透明区域的触摸事件分发 + */ private class NewNoteOnTouchListener implements OnTouchListener { public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: { + // 获取屏幕和按钮尺寸 Display display = getWindowManager().getDefaultDisplay(); int screenHeight = display.getHeight(); int newNoteViewHeight = mAddNewNote.getHeight(); int start = screenHeight - newNoteViewHeight; int eventY = start + (int) event.getY(); - /** - * Minus TitleBar's height - */ + + // 调整标题栏高度 if (mState == ListEditState.SUB_FOLDER) { eventY -= mTitleBar.getHeight(); start -= mTitleBar.getHeight(); } + /** - * HACKME:When click the transparent part of "New Note" button, dispatch - * the event to the list view behind this button. The transparent part of - * "New Note" button could be expressed by formula y=-0.12x+94(Unit:pixel) - * and the line top of the button. The coordinate based on left of the "New - * Note" button. The 94 represents maximum height of the transparent part. - * Notice that, if the background of the button changes, the formula should - * also change. This is very bad, just for the UI designer's strong requirement. + * 特殊处理:当点击"新建便签"按钮的透明部分时, + * 将事件分发给背后的列表视图。 + * 透明区域由公式 y=-0.12x+94(单位:像素)和按钮上边界定义。 */ if (event.getY() < (event.getX() * (-0.12) + 94)) { View view = mNotesListView.getChildAt(mNotesListView.getChildCount() - 1 @@ -387,6 +425,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt break; } case MotionEvent.ACTION_MOVE: { + // 处理移动事件的分发 if (mDispatch) { mDispatchY += (int) event.getY() - mOriginY; event.setLocation(event.getX(), mDispatchY); @@ -395,6 +434,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt break; } default: { + // 处理事件结束 if (mDispatch) { event.setLocation(event.getX(), mDispatchY); mDispatch = false; @@ -408,6 +448,10 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt }; + /** + * 启动异步便签列表查询 + * 根据当前文件夹ID构建查询条件 + */ private void startAsyncNotesListQuery() { String selection = (mCurrentFolderId == Notes.ID_ROOT_FOLDER) ? ROOT_FOLDER_SELECTION : NORMAL_SELECTION; @@ -417,6 +461,10 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt }, NoteColumns.TYPE + " DESC," + NoteColumns.MODIFIED_DATE + " DESC"); } + /** + * 异步查询处理器内部类 + * 处理数据库查询结果回调 + */ private final class BackgroundQueryHandler extends AsyncQueryHandler { public BackgroundQueryHandler(ContentResolver contentResolver) { super(contentResolver); @@ -426,11 +474,11 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt protected void onQueryComplete(int token, Object cookie, Cursor cursor) { switch (token) { case FOLDER_NOTE_LIST_QUERY_TOKEN: - mNotesListAdapter.changeCursor(cursor); + mNotesListAdapter.changeCursor(cursor); // 更新列表适配器数据 break; case FOLDER_LIST_QUERY_TOKEN: if (cursor != null && cursor.getCount() > 0) { - showFolderListMenu(cursor); + showFolderListMenu(cursor); // 显示文件夹选择菜单 } else { Log.e(TAG, "Query folder failed"); } @@ -441,6 +489,10 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt } } + /** + * 显示文件夹列表菜单 + * 用于选择移动便签的目标文件夹 + */ private void showFolderListMenu(Cursor cursor) { AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); builder.setTitle(R.string.menu_title_select_folder); @@ -448,6 +500,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt builder.setAdapter(adapter, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { + // 批量移动便签到目标文件夹 DataUtils.batchMoveToFolder(mContentResolver, mNotesListAdapter.getSelectedItemIds(), adapter.getItemId(which)); Toast.makeText( @@ -456,12 +509,16 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt mNotesListAdapter.getSelectedCount(), adapter.getFolderName(NotesListActivity.this, which)), Toast.LENGTH_SHORT).show(); - mModeCallBack.finishActionMode(); + mModeCallBack.finishActionMode(); // 结束操作模式 } }); builder.show(); } + /** + * 创建新便签 + * 启动便签编辑活动 + */ private void createNewNote() { Intent intent = new Intent(this, NoteEditActivity.class); intent.setAction(Intent.ACTION_INSERT_OR_EDIT); @@ -469,20 +526,24 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt this.startActivityForResult(intent, REQUEST_CODE_NEW_NODE); } + /** + * 批量删除便签 + * 在后台线程中执行删除操作并更新桌面小部件 + */ private void batchDelete() { new AsyncTask>() { protected HashSet doInBackground(Void... unused) { + // 获取选中便签关联的桌面小部件 HashSet widgets = mNotesListAdapter.getSelectedWidget(); if (!isSyncMode()) { - // if not synced, delete notes directly + // 非同步模式下直接删除便签 if (DataUtils.batchDeleteNotes(mContentResolver, mNotesListAdapter .getSelectedItemIds())) { } else { Log.e(TAG, "Delete notes error, should not happens"); } } else { - // in sync mode, we'll move the deleted note into the trash - // folder + // 同步模式下将便签移动到废纸篓 if (!DataUtils.batchMoveToFolder(mContentResolver, mNotesListAdapter .getSelectedItemIds(), Notes.ID_TRASH_FOLER)) { Log.e(TAG, "Move notes to trash folder error, should not happens"); @@ -494,6 +555,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt @Override protected void onPostExecute(HashSet widgets) { if (widgets != null) { + // 更新受影响的桌面小部件 for (AppWidgetAttribute widget : widgets) { if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID && widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) { @@ -501,11 +563,15 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt } } } - mModeCallBack.finishActionMode(); + mModeCallBack.finishActionMode(); // 结束操作模式 } }.execute(); } + /** + * 删除文件夹 + * @param folderId 要删除的文件夹ID + */ private void deleteFolder(long folderId) { if (folderId == Notes.ID_ROOT_FOLDER) { Log.e(TAG, "Wrong folder id, should not happen " + folderId); @@ -514,16 +580,18 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt HashSet ids = new HashSet(); ids.add(folderId); + // 获取文件夹内便签关联的桌面小部件 HashSet widgets = DataUtils.getFolderNoteWidget(mContentResolver, folderId); if (!isSyncMode()) { - // if not synced, delete folder directly + // 非同步模式下直接删除文件夹 DataUtils.batchDeleteNotes(mContentResolver, ids); } else { - // in sync mode, we'll move the deleted folder into the trash folder + // 同步模式下将文件夹移动到废纸篓 DataUtils.batchMoveToFolder(mContentResolver, ids, Notes.ID_TRASH_FOLER); } if (widgets != null) { + // 更新受影响的桌面小部件 for (AppWidgetAttribute widget : widgets) { if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID && widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) { @@ -533,6 +601,10 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt } } + /** + * 打开便签详情 + * @param data 要打开的便签数据项 + */ private void openNode(NoteItemData data) { Intent intent = new Intent(this, NoteEditActivity.class); intent.setAction(Intent.ACTION_VIEW); @@ -540,15 +612,23 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt this.startActivityForResult(intent, REQUEST_CODE_OPEN_NODE); } + /** + * 打开文件夹 + * @param data 要打开的文件夹数据项 + */ private void openFolder(NoteItemData data) { - mCurrentFolderId = data.getId(); - startAsyncNotesListQuery(); + mCurrentFolderId = data.getId(); // 更新当前文件夹ID + startAsyncNotesListQuery(); // 重新查询当前文件夹下的便签 + + // 根据文件夹类型更新界面状态 if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { mState = ListEditState.CALL_RECORD_FOLDER; mAddNewNote.setVisibility(View.GONE); } else { mState = ListEditState.SUB_FOLDER; } + + // 更新标题栏显示 if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { mTitleBar.setText(R.string.call_record_folder_name); } else { @@ -557,16 +637,21 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt mTitleBar.setVisibility(View.VISIBLE); } + @Override public void onClick(View v) { + // 按钮点击事件处理 switch (v.getId()) { case R.id.btn_new_note: - createNewNote(); + createNewNote(); // 创建新便签 break; default: break; } } + /** + * 显示软键盘 + */ private void showSoftInput() { InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); if (inputMethodManager != null) { @@ -574,16 +659,26 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt } } + /** + * 隐藏软键盘 + * @param view 用于获取窗口令牌的视图 + */ private void hideSoftInput(View view) { InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0); } + /** + * 显示创建或修改文件夹对话框 + * @param create 是否为创建新文件夹 + */ private void showCreateOrModifyFolderDialog(final boolean create) { final AlertDialog.Builder builder = new AlertDialog.Builder(this); View view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_text, null); final EditText etName = (EditText) view.findViewById(R.id.et_foler_name); - showSoftInput(); + showSoftInput(); // 显示软键盘 + + // 设置对话框标题和初始文本 if (!create) { if (mFocusNoteDataItem != null) { etName.setText(mFocusNoteDataItem.getSnippet()); @@ -600,7 +695,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt builder.setPositiveButton(android.R.string.ok, null); builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { - hideSoftInput(etName); + hideSoftInput(etName); // 隐藏软键盘 } }); @@ -608,14 +703,18 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt final Button positive = (Button)dialog.findViewById(android.R.id.button1); positive.setOnClickListener(new OnClickListener() { public void onClick(View v) { - hideSoftInput(etName); + hideSoftInput(etName); // 隐藏软键盘 String name = etName.getText().toString(); + + // 检查文件夹名称是否已存在 if (DataUtils.checkVisibleFolderName(mContentResolver, name)) { Toast.makeText(NotesListActivity.this, getString(R.string.folder_exist, name), Toast.LENGTH_LONG).show(); etName.setSelection(0, etName.length()); return; } + + // 执行文件夹创建或修改操作 if (!create) { if (!TextUtils.isEmpty(name)) { ContentValues values = new ContentValues(); @@ -637,16 +736,12 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt } }); + // 根据输入框内容启用/禁用确定按钮 if (TextUtils.isEmpty(etName.getText())) { positive.setEnabled(false); } - /** - * When the name edit text is null, disable the positive button - */ etName.addTextChangedListener(new TextWatcher() { public void beforeTextChanged(CharSequence s, int start, int count, int after) { - // TODO Auto-generated method stub - } public void onTextChanged(CharSequence s, int start, int before, int count) { @@ -658,22 +753,23 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt } public void afterTextChanged(Editable s) { - // TODO Auto-generated method stub - } }); } @Override public void onBackPressed() { + // 处理返回键事件 switch (mState) { case SUB_FOLDER: + // 从子文件夹返回根目录 mCurrentFolderId = Notes.ID_ROOT_FOLDER; mState = ListEditState.NOTE_LIST; startAsyncNotesListQuery(); mTitleBar.setVisibility(View.GONE); break; case CALL_RECORD_FOLDER: + // 从通话记录文件夹返回根目录 mCurrentFolderId = Notes.ID_ROOT_FOLDER; mState = ListEditState.NOTE_LIST; mAddNewNote.setVisibility(View.VISIBLE); @@ -681,15 +777,21 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt startAsyncNotesListQuery(); break; case NOTE_LIST: - super.onBackPressed(); + super.onBackPressed(); // 根目录直接退出活动 break; default: break; } } + /** + * 更新桌面小部件 + * @param appWidgetId 小部件ID + * @param appWidgetType 小部件类型 + */ private void updateWidget(int appWidgetId, int appWidgetType) { Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE); + // 根据小部件类型设置对应的提供者类 if (appWidgetType == Notes.TYPE_WIDGET_2X) { intent.setClass(this, NoteWidgetProvider_2x.class); } else if (appWidgetType == Notes.TYPE_WIDGET_4X) { @@ -703,10 +805,14 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt appWidgetId }); - sendBroadcast(intent); + sendBroadcast(intent); // 发送更新广播 setResult(RESULT_OK, intent); } + /** + * 文件夹上下文菜单创建监听器 + * 用于显示文件夹操作菜单 + */ private final OnCreateContextMenuListener mFolderOnCreateContextMenuListener = new OnCreateContextMenuListener() { public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { if (mFocusNoteDataItem != null) { @@ -721,7 +827,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt @Override public void onContextMenuClosed(Menu menu) { if (mNotesListView != null) { - mNotesListView.setOnCreateContextMenuListener(null); + mNotesListView.setOnCreateContextMenuListener(null); // 清除上下文菜单监听器 } super.onContextMenuClosed(menu); } @@ -732,11 +838,13 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt Log.e(TAG, "The long click data item is null"); return false; } + // 处理文件夹上下文菜单项点击 switch (item.getItemId()) { case MENU_FOLDER_VIEW: - openFolder(mFocusNoteDataItem); + openFolder(mFocusNoteDataItem); // 打开文件夹 break; case MENU_FOLDER_DELETE: + // 显示删除文件夹确认对话框 AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(getString(R.string.alert_title_delete)); builder.setIcon(android.R.drawable.ic_dialog_alert); @@ -744,14 +852,14 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { - deleteFolder(mFocusNoteDataItem.getId()); + deleteFolder(mFocusNoteDataItem.getId()); // 删除文件夹 } }); builder.setNegativeButton(android.R.string.cancel, null); builder.show(); break; case MENU_FOLDER_CHANGE_NAME: - showCreateOrModifyFolderDialog(false); + showCreateOrModifyFolderDialog(false); // 显示修改文件夹名称对话框 break; default: break; @@ -763,9 +871,10 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt @Override public boolean onPrepareOptionsMenu(Menu menu) { menu.clear(); + // 根据当前状态加载不同的选项菜单 if (mState == ListEditState.NOTE_LIST) { getMenuInflater().inflate(R.menu.note_list, menu); - // set sync or sync_cancel + // 设置同步/取消同步菜单项标题 menu.findItem(R.id.menu_sync).setTitle( GTaskSyncService.isSyncing() ? R.string.menu_sync_cancel : R.string.menu_sync); } else if (mState == ListEditState.SUB_FOLDER) { @@ -780,16 +889,18 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt @Override public boolean onOptionsItemSelected(MenuItem item) { + // 处理选项菜单点击事件 switch (item.getItemId()) { case R.id.menu_new_folder: { - showCreateOrModifyFolderDialog(true); + showCreateOrModifyFolderDialog(true); // 显示创建文件夹对话框 break; } case R.id.menu_export_text: { - exportNoteToText(); + exportNoteToText(); // 导出便签为文本文件 break; } case R.id.menu_sync: { + // 处理同步/取消同步操作 if (isSyncMode()) { if (TextUtils.equals(item.getTitle(), getString(R.string.menu_sync))) { GTaskSyncService.startSync(this); @@ -797,20 +908,19 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt GTaskSyncService.cancelSync(this); } } else { - startPreferenceActivity(); + startPreferenceActivity(); // 启动设置活动 } break; - } case R.id.menu_setting: { - startPreferenceActivity(); + startPreferenceActivity(); // 启动设置活动 break; } case R.id.menu_new_note: { - createNewNote(); + createNewNote(); // 创建新便签 break; } case R.id.menu_search: - onSearchRequested(); + onSearchRequested(); // 启动搜索 break; default: break; @@ -824,17 +934,22 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt return true; } + /** + * 导出便签为文本文件 + * 在后台线程中执行导出操作并显示结果 + */ private void exportNoteToText() { final BackupUtils backup = BackupUtils.getInstance(NotesListActivity.this); new AsyncTask() { @Override protected Integer doInBackground(Void... unused) { - return backup.exportToText(); + return backup.exportToText(); // 执行导出操作 } @Override protected void onPostExecute(Integer result) { + // 根据导出结果显示不同的提示对话框 if (result == BackupUtils.STATE_SD_CARD_UNMOUONTED) { AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); builder.setTitle(NotesListActivity.this @@ -866,21 +981,34 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt }.execute(); } + /** + * 检查是否处于同步模式 + * @return 如果已设置同步账户则返回true,否则返回false + */ private boolean isSyncMode() { return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; } + /** + * 启动设置活动 + */ private void startPreferenceActivity() { Activity from = getParent() != null ? getParent() : this; Intent intent = new Intent(from, NotesPreferenceActivity.class); from.startActivityIfNeeded(intent, -1); } + /** + * 列表项点击事件监听器 + * 处理便签和文件夹的点击操作 + */ private class OnListItemClickListener implements OnItemClickListener { public void onItemClick(AdapterView parent, View view, int position, long id) { if (view instanceof NotesListItem) { NoteItemData item = ((NotesListItem) view).getItemData(); + + // 如果处于选择模式,处理便签选择 if (mNotesListAdapter.isInChoiceMode()) { if (item.getType() == Notes.TYPE_NOTE) { position = position - mNotesListView.getHeaderViewsCount(); @@ -890,13 +1018,14 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt return; } + // 根据当前状态和项类型处理不同的点击操作 switch (mState) { case NOTE_LIST: if (item.getType() == Notes.TYPE_FOLDER || item.getType() == Notes.TYPE_SYSTEM) { - openFolder(item); + openFolder(item); // 打开文件夹 } else if (item.getType() == Notes.TYPE_NOTE) { - openNode(item); + openNode(item); // 打开便签 } else { Log.e(TAG, "Wrong note type in NOTE_LIST"); } @@ -904,7 +1033,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt case SUB_FOLDER: case CALL_RECORD_FOLDER: if (item.getType() == Notes.TYPE_NOTE) { - openNode(item); + openNode(item); // 打开便签 } else { Log.e(TAG, "Wrong note type in SUB_FOLDER"); } @@ -917,11 +1046,16 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt } + /** + * 启动查询目标文件夹 + * 用于便签移动操作 + */ private void startQueryDestinationFolders() { String selection = NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>? AND " + NoteColumns.ID + "<>?"; selection = (mState == ListEditState.NOTE_LIST) ? selection: "(" + selection + ") OR (" + NoteColumns.ID + "=" + Notes.ID_ROOT_FOLDER + ")"; + // 查询可移动到的目标文件夹 mBackgroundQueryHandler.startQuery(FOLDER_LIST_QUERY_TOKEN, null, Notes.CONTENT_NOTE_URI, @@ -935,10 +1069,17 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt NoteColumns.MODIFIED_DATE + " DESC"); } + /** + * 列表项长按事件处理 + * 处理便签多选和文件夹 上下文菜单 + */ public boolean onItemLongClick(AdapterView parent, View view, int position, long id) { if (view instanceof NotesListItem) { mFocusNoteDataItem = ((NotesListItem) view).getItemData(); + + // 根据项类型处理不同的长按操作 if (mFocusNoteDataItem.getType() == Notes.TYPE_NOTE && !mNotesListAdapter.isInChoiceMode()) { + // 便签长按启动多选模式 if (mNotesListView.startActionMode(mModeCallBack) != null) { mModeCallBack.onItemCheckedStateChanged(null, position, id, true); mNotesListView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); @@ -946,9 +1087,10 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt Log.e(TAG, "startActionMode fails"); } } else if (mFocusNoteDataItem.getType() == Notes.TYPE_FOLDER) { + // 文件夹长按显示上下文菜单 mNotesListView.setOnCreateContextMenuListener(mFolderOnCreateContextMenuListener); } } return false; } -} +} \ No newline at end of file diff --git a/src/Notes-master/app/src/main/java/net/micode/notes/ui/NotesListAdapter.java b/src/Notes-master/app/src/main/java/net/micode/notes/ui/NotesListAdapter.java index 51c9cb9..f10aa67 100644 --- a/src/Notes-master/app/src/main/java/net/micode/notes/ui/NotesListAdapter.java +++ b/src/Notes-master/app/src/main/java/net/micode/notes/ui/NotesListAdapter.java @@ -1,17 +1,14 @@ /* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * 版权声明:2010-2011年,MiCode开源社区(www.micode.net)保留所有权利 * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * 本代码基于Apache许可证2.0版本发布("许可证"); + * 您可以在遵守许可证的前提下使用本文件; + * 您可以从以下地址获取许可证副本: * * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * 除非法律要求或书面同意,否则本软件根据许可证分发时按"原样"提供, + * 不附带任何明示或暗示的保证或条件。请查看许可证,了解具体的权限和限制。 */ package net.micode.notes.ui; @@ -30,19 +27,31 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; - +/** + * 便签列表适配器 + * 继承自CursorAdapter,负责将数据库中的便签数据绑定到ListView上 + * 支持多选模式、数据筛选和小部件关联信息获取 + */ public class NotesListAdapter extends CursorAdapter { private static final String TAG = "NotesListAdapter"; - private Context mContext; - private HashMap mSelectedIndex; - private int mNotesCount; - private boolean mChoiceMode; - + private Context mContext; // 上下文环境 + private HashMap mSelectedIndex; // 存储选中项的索引 + private int mNotesCount; // 便签总数 + private boolean mChoiceMode; // 是否处于选择模式 + + /** + * 桌面小部件属性类 + * 用于存储便签关联的桌面小部件信息 + */ public static class AppWidgetAttribute { - public int widgetId; - public int widgetType; + public int widgetId; // 小部件ID + public int widgetType; // 小部件类型 }; + /** + * 构造函数 + * 初始化适配器,创建选中项索引映射表 + */ public NotesListAdapter(Context context) { super(context, null); mSelectedIndex = new HashMap(); @@ -50,38 +59,65 @@ public class NotesListAdapter extends CursorAdapter { mNotesCount = 0; } + /** + * 创建新视图 + * 当ListView需要创建新的便签项视图时调用 + */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return new NotesListItem(context); } + /** + * 绑定数据到视图 + * 将便签数据绑定到对应的视图上 + */ @Override public void bindView(View view, Context context, Cursor cursor) { if (view instanceof NotesListItem) { + // 创建便签数据项 NoteItemData itemData = new NoteItemData(context, cursor); + // 绑定数据到便签项视图,设置选择状态 ((NotesListItem) view).bind(context, itemData, mChoiceMode, isSelectedItem(cursor.getPosition())); } } + /** + * 设置项的选中状态 + * 更新选中项索引映射表并通知适配器数据已改变 + */ public void setCheckedItem(final int position, final boolean checked) { mSelectedIndex.put(position, checked); notifyDataSetChanged(); } + /** + * 判断是否处于选择模式 + * @return 处于选择模式返回true,否则返回false + */ public boolean isInChoiceMode() { return mChoiceMode; } + /** + * 设置选择模式 + * 切换适配器的选择模式状态 + */ public void setChoiceMode(boolean mode) { mSelectedIndex.clear(); mChoiceMode = mode; } + /** + * 全选或取消全选 + * 遍历所有便签项,设置它们的选中状态 + */ public void selectAll(boolean checked) { Cursor cursor = getCursor(); for (int i = 0; i < getCount(); i++) { if (cursor.moveToPosition(i)) { + // 只处理类型为便签的项 if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) { setCheckedItem(i, checked); } @@ -89,6 +125,10 @@ public class NotesListAdapter extends CursorAdapter { } } + /** + * 获取选中项的ID集合 + * @return 包含所有选中项ID的HashSet + */ public HashSet getSelectedItemIds() { HashSet itemSet = new HashSet(); for (Integer position : mSelectedIndex.keySet()) { @@ -105,6 +145,10 @@ public class NotesListAdapter extends CursorAdapter { return itemSet; } + /** + * 获取选中项关联的桌面小部件 + * @return 包含所有选中项关联小部件属性的HashSet + */ public HashSet getSelectedWidget() { HashSet itemSet = new HashSet(); for (Integer position : mSelectedIndex.keySet()) { @@ -117,7 +161,7 @@ public class NotesListAdapter extends CursorAdapter { widget.widgetType = item.getWidgetType(); itemSet.add(widget); /** - * Don't close cursor here, only the adapter could close it + * 注意:不要在这里关闭cursor,只有适配器才能关闭它 */ } else { Log.e(TAG, "Invalid cursor"); @@ -128,6 +172,10 @@ public class NotesListAdapter extends CursorAdapter { return itemSet; } + /** + * 获取选中项数量 + * 统计选中项索引映射表中值为true的项数 + */ public int getSelectedCount() { Collection values = mSelectedIndex.values(); if (null == values) { @@ -143,11 +191,19 @@ public class NotesListAdapter extends CursorAdapter { return count; } + /** + * 判断是否全选 + * 检查是否所有便签都被选中 + */ public boolean isAllSelected() { int checkedCount = getSelectedCount(); return (checkedCount != 0 && checkedCount == mNotesCount); } + /** + * 判断指定位置的项是否被选中 + * @return 选中返回true,否则返回false + */ public boolean isSelectedItem(final int position) { if (null == mSelectedIndex.get(position)) { return false; @@ -155,18 +211,30 @@ public class NotesListAdapter extends CursorAdapter { return mSelectedIndex.get(position); } + /** + * 内容变化时的回调 + * 当数据内容发生变化时调用,重新计算便签数量 + */ @Override protected void onContentChanged() { super.onContentChanged(); calcNotesCount(); } + /** + * 更改游标 + * 当数据源变化时调用,重新计算便签数量 + */ @Override public void changeCursor(Cursor cursor) { super.changeCursor(cursor); calcNotesCount(); } + /** + * 计算便签数量 + * 遍历游 标,统计类型为便签的项数 + */ private void calcNotesCount() { mNotesCount = 0; for (int i = 0; i < getCount(); i++) { @@ -181,4 +249,4 @@ public class NotesListAdapter extends CursorAdapter { } } } -} +} \ No newline at end of file diff --git a/src/Notes-master/app/src/main/java/net/micode/notes/ui/NotesListItem.java b/src/Notes-master/app/src/main/java/net/micode/notes/ui/NotesListItem.java index 1221e80..aec0271 100644 --- a/src/Notes-master/app/src/main/java/net/micode/notes/ui/NotesListItem.java +++ b/src/Notes-master/app/src/main/java/net/micode/notes/ui/NotesListItem.java @@ -1,17 +1,14 @@ /* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * 版权声明:2010-2011年,MiCode开源社区(www.micode.net)保留所有权利 * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * 本代码基于Apache许可证2.0版本发布("许可证"); + * 您可以在遵守许可证的前提下使用本文件; + * 您可以从以下地址获取许可证副本: * * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * 除非法律要求或书面同意,否则本软件根据许可证分发时按"原样"提供, + * 不附带任何明示或暗示的保证或条件。请查看许可证,了解具体的权限和限制。 */ package net.micode.notes.ui; @@ -29,15 +26,23 @@ import net.micode.notes.data.Notes; import net.micode.notes.tool.DataUtils; import net.micode.notes.tool.ResourceParser.NoteItemBgResources; - +/** + * 便签列表项视图类 + * 继承自LinearLayout,负责渲染单个便签或文件夹项的UI界面 + * 根据便签类型和状态显示不同的布局和样式 + */ public class NotesListItem extends LinearLayout { - private ImageView mAlert; - private TextView mTitle; - private TextView mTime; - private TextView mCallName; - private NoteItemData mItemData; - private CheckBox mCheckBox; + private ImageView mAlert; // 提醒图标 + private TextView mTitle; // 标题文本 + private TextView mTime; // 时间文本 + private TextView mCallName; // 通话记录名称 + private NoteItemData mItemData; // 便签数据 + private CheckBox mCheckBox; // 多选模式下的复选框 + /** + * 构造函数 + * 初始化视图组件,加载布局文件 + */ public NotesListItem(Context context) { super(context); inflate(context, R.layout.note_item, this); @@ -48,7 +53,12 @@ public class NotesListItem extends LinearLayout { mCheckBox = (CheckBox) findViewById(android.R.id.checkbox); } + /** + * 绑定数据到视图 + * 根据便签类型和状态设置不同的UI显示 + */ public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) { + // 处理多选模式下的复选框显示 if (choiceMode && data.getType() == Notes.TYPE_NOTE) { mCheckBox.setVisibility(View.VISIBLE); mCheckBox.setChecked(checked); @@ -57,7 +67,10 @@ public class NotesListItem extends LinearLayout { } mItemData = data; + + // 根据便签类型和父文件夹设置不同的UI显示 if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { + // 通话记录文件夹 mCallName.setVisibility(View.GONE); mAlert.setVisibility(View.VISIBLE); mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); @@ -65,6 +78,7 @@ public class NotesListItem extends LinearLayout { + context.getString(R.string.format_folder_files_count, data.getNotesCount())); mAlert.setImageResource(R.drawable.call_record); } else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) { + // 通话记录便签 mCallName.setVisibility(View.VISIBLE); mCallName.setText(data.getCallName()); mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem); @@ -80,11 +94,13 @@ public class NotesListItem extends LinearLayout { mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); if (data.getType() == Notes.TYPE_FOLDER) { + // 普通文件夹 mTitle.setText(data.getSnippet() + context.getString(R.string.format_folder_files_count, data.getNotesCount())); mAlert.setVisibility(View.GONE); } else { + // 普通便签 mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); if (data.hasAlert()) { mAlert.setImageResource(R.drawable.clock); @@ -94,14 +110,22 @@ public class NotesListItem extends LinearLayout { } } } + + // 设置便签修改时间,使用相对时间格式(如"2小时前") mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate())); + // 设置便签背景 setBackground(data); } + /** + * 设置便签背景 + * 根据便签类型、颜色和位置设置不同的背景资源 + */ private void setBackground(NoteItemData data) { int id = data.getBgColorId(); if (data.getType() == Notes.TYPE_NOTE) { + // 根据便签在列表中的位置设置不同的背景样式 if (data.isSingle() || data.isOneFollowingFolder()) { setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id)); } else if (data.isLast()) { @@ -112,11 +136,16 @@ public class NotesListItem extends LinearLayout { setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id)); } } else { + // 文件夹使用 统一的背景样式 setBackgroundResource(NoteItemBgResources.getFolderBgRes()); } } + /** + * 获取便签数据 + * @return 便签数据对象 + */ public NoteItemData getItemData() { return mItemData; } -} +} \ No newline at end of file diff --git a/src/Notes-master/app/src/main/java/net/micode/notes/ui/NotesPreferenceActivity.java b/src/Notes-master/app/src/main/java/net/micode/notes/ui/NotesPreferenceActivity.java index 07c5f7e..e5a4b5a 100644 --- a/src/Notes-master/app/src/main/java/net/micode/notes/ui/NotesPreferenceActivity.java +++ b/src/Notes-master/app/src/main/java/net/micode/notes/ui/NotesPreferenceActivity.java @@ -1,17 +1,14 @@ /* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * 版权声明:2010-2011年,MiCode开源社区(www.micode.net)保留所有权利 * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * 本代码基于Apache许可证2.0版本发布("许可证"); + * 您可以在遵守许可证的前提下使用本文件; + * 您可以从以下地址获取许可证副本: * * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * 除非法律要求或书面同意,否则本软件根据许可证分发时按"原样"提供, + * 不附带任何明示或暗示的保证或条件。请查看许可证,了解具体的权限和限制。 */ package net.micode.notes.ui; @@ -47,53 +44,68 @@ import net.micode.notes.data.Notes; import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.gtask.remote.GTaskSyncService; - +/** + * 便签应用设置界面 + * 继承自PreferenceActivity,提供便签应用的各种设置选项 + * 主要功能包括Google账户同步设置、同步操作和同步状态显示 + */ public class NotesPreferenceActivity extends PreferenceActivity { + // 偏好设置名称 public static final String PREFERENCE_NAME = "notes_preferences"; - + // 同步账户名称偏好键 public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name"; - + // 上次同步时间偏好键 public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time"; - + // 背景颜色随机显示偏好键 public static final String PREFERENCE_SET_BG_COLOR_KEY = "pref_key_bg_random_appear"; - + + // 同步账户偏好类别键 private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key"; - + // 账户权限过滤键 private static final String AUTHORITIES_FILTER_KEY = "authorities"; - private PreferenceCategory mAccountCategory; - - private GTaskReceiver mReceiver; - - private Account[] mOriAccounts; - - private boolean mHasAddedAccount; + private PreferenceCategory mAccountCategory; // 账户设置类别 + private GTaskReceiver mReceiver; // Google任务同步广播接收器 + private Account[] mOriAccounts; // 原始账户列表 + private boolean mHasAddedAccount; // 是否添加了新账户 + /** + * 活动创建时调用 + * 初始化界面和数据 + */ @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); - /* using the app icon for navigation */ + /* 设置ActionBar可返回导航 */ getActionBar().setDisplayHomeAsUpEnabled(true); + // 加载偏好设置布局 addPreferencesFromResource(R.xml.preferences); mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY); mReceiver = new GTaskReceiver(); + + // 注册广播接收器,监听Google任务同步服务状态 IntentFilter filter = new IntentFilter(); filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME); registerReceiver(mReceiver, filter); mOriAccounts = null; + + // 添加设置页面头部视图 View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null); getListView().addHeaderView(header, null, true); } + /** + * 活动恢复时调用 + * 刷新UI并处理新添加的账户 + */ @Override protected void onResume() { super.onResume(); - // need to set sync account automatically if user has added a new - // account + // 如果添加了新账户,自动设置为同步账户 if (mHasAddedAccount) { Account[] accounts = getGoogleAccounts(); if (mOriAccounts != null && accounts.length > mOriAccounts.length) { @@ -116,6 +128,10 @@ public class NotesPreferenceActivity extends PreferenceActivity { refreshUI(); } + /** + * 活动销毁时调用 + * 注销广播接收器 + */ @Override protected void onDestroy() { if (mReceiver != null) { @@ -124,6 +140,10 @@ public class NotesPreferenceActivity extends PreferenceActivity { super.onDestroy(); } + /** + * 加载账户设置偏好项 + * 创建并配置账户选择偏好项 + */ private void loadAccountPreference() { mAccountCategory.removeAll(); @@ -135,11 +155,10 @@ public class NotesPreferenceActivity extends PreferenceActivity { public boolean onPreferenceClick(Preference preference) { if (!GTaskSyncService.isSyncing()) { if (TextUtils.isEmpty(defaultAccount)) { - // the first time to set account + // 首次设置账户 showSelectAccountAlertDialog(); } else { - // if the account has already been set, we need to promp - // user about the risk + // 已设置账户,需要提示用户更改账户的风险 showChangeAccountConfirmAlertDialog(); } } else { @@ -154,11 +173,15 @@ public class NotesPreferenceActivity extends PreferenceActivity { mAccountCategory.addPreference(accountPref); } + /** + * 加载同步按钮和状态 + * 配置同步按钮和上次同步时间显示 + */ private void loadSyncButton() { Button syncButton = (Button) findViewById(R.id.preference_sync_button); TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview); - // set button state + // 设置按钮状态 if (GTaskSyncService.isSyncing()) { syncButton.setText(getString(R.string.preferences_button_sync_cancel)); syncButton.setOnClickListener(new View.OnClickListener() { @@ -176,7 +199,7 @@ public class NotesPreferenceActivity extends PreferenceActivity { } syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this))); - // set last sync time + // 设置上次同步时间 if (GTaskSyncService.isSyncing()) { lastSyncTimeView.setText(GTaskSyncService.getProgressString()); lastSyncTimeView.setVisibility(View.VISIBLE); @@ -193,14 +216,23 @@ public class NotesPreferenceActivity extends PreferenceActivity { } } + /** + * 刷新UI + * 更新设置界面的所有元素 + */ private void refreshUI() { loadAccountPreference(); loadSyncButton(); } + /** + * 显示选择账户对话框 + * 提供现有Google账户选择或添加新账户选项 + */ private void showSelectAccountAlertDialog() { AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); + // 设置对话框标题和提示信息 View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title); titleTextView.setText(getString(R.string.preferences_dialog_select_account_title)); @@ -217,6 +249,7 @@ public class NotesPreferenceActivity extends PreferenceActivity { mHasAddedAccount = false; if (accounts.length > 0) { + // 显示现有账户列表供选择 CharSequence[] items = new CharSequence[accounts.length]; final CharSequence[] itemMapping = items; int checkedItem = -1; @@ -237,6 +270,7 @@ public class NotesPreferenceActivity extends PreferenceActivity { }); } + // 添加"添加账户"选项 View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null); dialogBuilder.setView(addAccountView); @@ -244,6 +278,7 @@ public class NotesPreferenceActivity extends PreferenceActivity { addAccountView.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mHasAddedAccount = true; + // 启动添加账户设置界面 Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS"); intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] { "gmail-ls" @@ -254,9 +289,14 @@ public class NotesPreferenceActivity extends PreferenceActivity { }); } + /** + * 显示更改账户确认对话框 + * 提示用户更改账户的风险并提供选项 + */ private void showChangeAccountConfirmAlertDialog() { AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); + // 设置对话框标题和警告信息 View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title); titleTextView.setText(getString(R.string.preferences_dialog_change_account_title, @@ -265,6 +305,7 @@ public class NotesPreferenceActivity extends PreferenceActivity { subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg)); dialogBuilder.setCustomTitle(titleView); + // 提供三个选项:更改账户、移除账户、取消 CharSequence[] menuItemArray = new CharSequence[] { getString(R.string.preferences_menu_change_account), getString(R.string.preferences_menu_remove_account), @@ -283,13 +324,22 @@ public class NotesPreferenceActivity extends PreferenceActivity { dialogBuilder.show(); } + /** + * 获取Google账户列表 + * @return 返回设备上所有Google账户 + */ private Account[] getGoogleAccounts() { AccountManager accountManager = AccountManager.get(this); return accountManager.getAccountsByType("com.google"); } + /** + * 设置同步账户 + * 保存选定的同步账户并重置同步状态 + */ private void setSyncAccount(String account) { if (!getSyncAccountName(this).equals(account)) { + // 保存账户名称到偏好设置 SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); if (account != null) { @@ -299,10 +349,10 @@ public class NotesPreferenceActivity extends PreferenceActivity { } editor.commit(); - // clean up last sync time + // 重置上次同步时间 setLastSyncTime(this, 0); - // clean up local gtask related info + // 清除本地Google任务相关信息 new Thread(new Runnable() { public void run() { ContentValues values = new ContentValues(); @@ -318,6 +368,10 @@ public class NotesPreferenceActivity extends PreferenceActivity { } } + /** + * 移除同步账户 + * 删除同步账户设置并清除相关数据 + */ private void removeSyncAccount() { SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); @@ -329,7 +383,7 @@ public class NotesPreferenceActivity extends PreferenceActivity { } editor.commit(); - // clean up local gtask related info + // 清除本地Google任务相关信息 new Thread(new Runnable() { public void run() { ContentValues values = new ContentValues(); @@ -340,12 +394,20 @@ public class NotesPreferenceActivity extends PreferenceActivity { }).start(); } + /** + * 获取同步账户名称 + * 静态方法,可从任何地方获取当前设置的同步账户 + */ public static String getSyncAccountName(Context context) { SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); } + /** + * 设置上次同步时间 + * 静态方法,保存同步完成的时间戳 + */ public static void setLastSyncTime(Context context, long time) { SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); @@ -354,12 +416,20 @@ public class NotesPreferenceActivity extends PreferenceActivity { editor.commit(); } + /** + * 获取上次同步时间 + * 静态方法,返回上次同步完成的时间戳 + */ public static long getLastSyncTime(Context context) { SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0); } + /** + * Google任务同步广播接收器 + * 接收同步服务状态变化的广播并更新UI + */ private class GTaskReceiver extends BroadcastReceiver { @Override @@ -370,13 +440,17 @@ public class NotesPreferenceActivity extends PreferenceActivity { syncStatus.setText(intent .getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG)); } - } } + /** + * 选项菜单点击处理 + * 处理ActionBar上的 导航按钮 + */ public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: + // 返回主界面 Intent intent = new Intent(this, NotesListActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); @@ -385,4 +459,4 @@ public class NotesPreferenceActivity extends PreferenceActivity { return false; } } -} +} \ No newline at end of file diff --git a/src/Notes-master/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider.java b/src/Notes-master/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider.java index ec6f819..63c1f23 100644 --- a/src/Notes-master/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider.java +++ b/src/Notes-master/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider.java @@ -15,6 +15,7 @@ */ package net.micode.notes.widget; + import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; @@ -32,23 +33,36 @@ import net.micode.notes.tool.ResourceParser; import net.micode.notes.ui.NoteEditActivity; import net.micode.notes.ui.NotesListActivity; +/** + * 便签小部件的抽象基类,提供通用的小部件功能实现 + * 所有便签小部件类型都应继承此类并实现抽象方法 + */ public abstract class NoteWidgetProvider extends AppWidgetProvider { + // 查询便签信息时使用的投影列 public static final String [] PROJECTION = new String [] { - NoteColumns.ID, - NoteColumns.BG_COLOR_ID, - NoteColumns.SNIPPET + NoteColumns.ID, // 便签ID + NoteColumns.BG_COLOR_ID, // 便签背景颜色ID + NoteColumns.SNIPPET // 便签摘要内容 }; + // 投影列索引常量 public static final int COLUMN_ID = 0; public static final int COLUMN_BG_COLOR_ID = 1; public static final int COLUMN_SNIPPET = 2; private static final String TAG = "NoteWidgetProvider"; + /** + * 当小部件被删除时调用,负责清理数据库中相关的小部件ID引用 + * + * @param context 应用上下文 + * @param appWidgetIds 被删除的小部件ID数组 + */ @Override public void onDeleted(Context context, int[] appWidgetIds) { ContentValues values = new ContentValues(); values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); + // 更新数据库中所有关联这些小部件ID的便签记录,将其widget_id设为无效值 for (int i = 0; i < appWidgetIds.length; i++) { context.getContentResolver().update(Notes.CONTENT_NOTE_URI, values, @@ -57,7 +71,15 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider { } } + /** + * 获取与指定小部件ID关联的便签信息 + * + * @param context 应用上下文 + * @param widgetId 小部件ID + * @return 包含便签信息的Cursor对象 + */ private Cursor getNoteWidgetInfo(Context context, int widgetId) { + // 查询数据库,获取与指定小部件ID关联且不在回收站中的便签 return context.getContentResolver().query(Notes.CONTENT_NOTE_URI, PROJECTION, NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>?", @@ -65,68 +87,117 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider { null); } + /** + * 更新指定的便签小部件,使用默认模式(非隐私模式) + * + * @param context 应用上下文 + * @param appWidgetManager 小部件管理器 + * @param appWidgetIds 需要更新的小部件ID数组 + */ protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { update(context, appWidgetManager, appWidgetIds, false); } + /** + * 更新指定的便签小部件 + * + * @param context 应用上下文 + * @param appWidgetManager 小部件管理器 + * @param appWidgetIds 需要更新的小部件ID数组 + * @param privacyMode 是否使用隐私模式 + */ private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds, boolean privacyMode) { + // 遍历所有需要更新的小部件ID for (int i = 0; i < appWidgetIds.length; i++) { if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) { + // 设置默认值 int bgId = ResourceParser.getDefaultBgId(context); String snippet = ""; + + // 创建用于启动便签编辑界面的Intent Intent intent = new Intent(context, NoteEditActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, appWidgetIds[i]); intent.putExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, getWidgetType()); + // 查询与当前小部件关联的便签信息 Cursor c = getNoteWidgetInfo(context, appWidgetIds[i]); if (c != null && c.moveToFirst()) { + // 检查是否有多个便签关联到同一个小部件ID(这是异常情况) if (c.getCount() > 1) { Log.e(TAG, "Multiple message with same widget id:" + appWidgetIds[i]); c.close(); return; } + + // 从Cursor中获取便签内容和背景色 snippet = c.getString(COLUMN_SNIPPET); bgId = c.getInt(COLUMN_BG_COLOR_ID); intent.putExtra(Intent.EXTRA_UID, c.getLong(COLUMN_ID)); intent.setAction(Intent.ACTION_VIEW); } else { + // 如果没有找到关联的便签,显示默认提示文本 snippet = context.getResources().getString(R.string.widget_havenot_content); intent.setAction(Intent.ACTION_INSERT_OR_EDIT); } + // 关闭Cursor释放资源 if (c != null) { c.close(); } + // 创建RemoteViews对象用于更新小部件UI RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId()); rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId)); intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId); + /** - * Generate the pending intent to start host for the widget + * 生成用于启动小部件宿主应用的PendingIntent */ PendingIntent pendingIntent = null; if (privacyMode) { + // 隐私模式下显示提示文本,并跳转到便签列表 rv.setTextViewText(R.id.widget_text, context.getString(R.string.widget_under_visit_mode)); pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], new Intent( context, NotesListActivity.class), PendingIntent.FLAG_UPDATE_CURRENT); } else { + // 正常模式下显示便签内容,并跳转到便签编辑界面 rv.setTextViewText(R.id.widget_text, snippet); pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], intent, PendingIntent.FLAG_UPDATE_CURRENT); } + // 设置点击事件并更新小部件 rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent); appWidgetManager.updateAppWidget(appWidgetIds[i], rv); } } } + /** + * 根据背景颜色ID获取对应的背景资源ID + * 子类必须实现此方法以提供具体的背景资源映射 + * + * @param bgId 背景颜色ID + * @return 对应的背景资源ID + */ protected abstract int getBgResourceId(int bgId); + /** + * 获取小部件的布局资源ID + * 子类必须实现此方法以指定具体的布局文件 + * + * @return 布局资源ID + */ protected abstract int getLayoutId(); + /** + * 获取小部件类型 + * 子类必须实现此方法以返回具体的小部件类型标识 + * + * @return 小部件类型 + */ protected abstract int getWidgetType(); } diff --git a/src/Notes-master/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider_2x.java b/src/Notes-master/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider_2x.java index adcb2f7..3fc3ad5 100644 --- a/src/Notes-master/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider_2x.java +++ b/src/Notes-master/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider_2x.java @@ -23,23 +23,55 @@ import net.micode.notes.R; import net.micode.notes.data.Notes; import net.micode.notes.tool.ResourceParser; - +/** + * 2x大小便签小部件的具体实现类 + * 继承自NoteWidgetProvider,负责2x大小便签小部件的初始化和更新 + */ public class NoteWidgetProvider_2x extends NoteWidgetProvider { + /** + * 小部件更新回调方法 + * 当小部件需要更新时,系统会调用此方法 + * + * @param context 应用上下文 + * @param appWidgetManager 小部件管理器 + * @param appWidgetIds 需要更新的小部件ID数组 + */ @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { + // 调用父类的更新方法处理小部件更新逻辑 super.update(context, appWidgetManager, appWidgetIds); } + /** + * 获取小部件的布局资源ID + * 实现父类的抽象方法,指定2x大小便签小部件使用的布局文件 + * + * @return 布局资源ID,对应R.layout.widget_2x + */ @Override protected int getLayoutId() { return R.layout.widget_2x; } + /** + * 根据背景颜色ID获取对应的背景资源ID + * 实现父类的抽象方法,提供2x大小便签小部件的背景资源映射 + * + * @param bgId 背景颜色ID + * @return 对应的背景资源ID + */ @Override protected int getBgResourceId(int bgId) { + // 使用ResourceParser工具类获取2x大小便签的背景资源 return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId); } + /** + * 获取小部件类型 + * 实现父类的抽象方法,指定当前小部件的类型为2x大小便签 + * + * @return 小部件类型常量,对应Notes.TYPE_WIDGET_2X + */ @Override protected int getWidgetType() { return Notes.TYPE_WIDGET_2X; diff --git a/src/Notes-master/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider_4x.java b/src/Notes-master/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider_4x.java index c12a02e..72373b1 100644 --- a/src/Notes-master/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider_4x.java +++ b/src/Notes-master/app/src/main/java/net/micode/notes/widget/NoteWidgetProvider_4x.java @@ -23,22 +23,55 @@ import net.micode.notes.R; import net.micode.notes.data.Notes; import net.micode.notes.tool.ResourceParser; - +/** + * 4x大小便签小部件的具体实现类 + * 继承自NoteWidgetProvider,负责4x大小便签小部件的初始化和更新 + */ public class NoteWidgetProvider_4x extends NoteWidgetProvider { + /** + * 小部件更新回调方法 + * 当小部件需要更新时,系统会调用此方法 + * + * @param context 应用上下文 + * @param appWidgetManager 小部件管理器 + * @param appWidgetIds 需要更新的小部件ID数组 + */ @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { + // 调用父类的更新方法处理小部件更新逻辑 super.update(context, appWidgetManager, appWidgetIds); } + /** + * 获取小部件的布局资源ID + * 实现父类的抽象方法,指定4x大小便签小部件使用的布局文件 + * + * @return 布局资源ID,对应R.layout.widget_4x + */ + @Override protected int getLayoutId() { return R.layout.widget_4x; } + /** + * 根据背景颜色ID获取对应的背景资源ID + * 实现父类的抽象方法,提供4x大小便签小部件的背景资源映射 + * + * @param bgId 背景颜色ID + * @return 对应的背景资源ID + */ @Override protected int getBgResourceId(int bgId) { + // 使用ResourceParser工具类获取4x大小便签的背景资源 return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId); } + /** + * 获取小部件类型 + * 实现父类的抽象方法,指定当前小部件的类型为4x大小便签 + * + * @return 小部件类型常量,对应Notes.TYPE_WIDGET_4X + */ @Override protected int getWidgetType() { return Notes.TYPE_WIDGET_4X;