From 9e73668904794158b307a7abe983f52f3047cb0f Mon Sep 17 00:00:00 2001 From: fangzheng <13929869895@163.com> Date: Sat, 17 Jan 2026 16:56:56 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8E=A8=E9=80=81=E5=AE=8C=E6=95=B4=E4=BB=A3?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ui/AlarmAlertActivity.java | 203 +++ src/ui/AlarmInitReceiver.java | 100 ++ src/ui/AlarmReceiver.java | 46 + src/ui/DateTimePicker.java | 576 ++++++++ src/ui/DateTimePickerDialog.java | 137 ++ src/ui/DropdownMenu.java | 92 ++ src/ui/FoldersListAdapter.java | 130 ++ src/ui/NoteEditActivity.java | 1161 ++++++++++++++++ src/ui/NoteEditText.java | 288 ++++ src/ui/NoteItemData.java | 319 +++++ src/ui/NotesListActivity.java | 1232 +++++++++++++++++ src/ui/NotesListAdapter.java | 259 ++++ src/ui/NotesListItem.java | 169 +++ src/ui/NotesPreferenceActivity.java | 463 +++++++ src/widget/NoteWidgetProvider.java | 187 +++ src/widget/NoteWidgetProvider_2x.java | 76 + src/widget/NoteWidgetProvider_4x.java | 72 + src/新建文件夹/AlarmAlertActivity.java | 203 +++ src/新建文件夹/AlarmInitReceiver.java | 100 ++ src/新建文件夹/AlarmReceiver.java | 46 + src/新建文件夹/BackupUtils.java | 436 ++++++ src/新建文件夹/DataUtils.java | 381 +++++ src/新建文件夹/DateTimePicker.java | 576 ++++++++ src/新建文件夹/DateTimePickerDialog.java | 137 ++ src/新建文件夹/DropdownMenu.java | 92 ++ src/新建文件夹/FoldersListAdapter.java | 130 ++ src/新建文件夹/GTaskStringUtils.java | 169 +++ src/新建文件夹/NoteEditActivity.java | 1161 ++++++++++++++++ src/新建文件夹/NoteEditText.java | 288 ++++ src/新建文件夹/NoteItemData.java | 319 +++++ src/新建文件夹/NoteWidgetProvider.java | 187 +++ .../NoteWidgetProvider_2x.java | 76 + .../NoteWidgetProvider_4x.java | 72 + src/新建文件夹/NotesListActivity.java | 1232 +++++++++++++++++ src/新建文件夹/NotesListAdapter.java | 259 ++++ src/新建文件夹/NotesListItem.java | 169 +++ .../NotesPreferenceActivity.java | 463 +++++++ src/新建文件夹/ResourceParser.java | 272 ++++ 38 files changed, 12278 insertions(+) create mode 100644 src/ui/AlarmAlertActivity.java create mode 100644 src/ui/AlarmInitReceiver.java create mode 100644 src/ui/AlarmReceiver.java create mode 100644 src/ui/DateTimePicker.java create mode 100644 src/ui/DateTimePickerDialog.java create mode 100644 src/ui/DropdownMenu.java create mode 100644 src/ui/FoldersListAdapter.java create mode 100644 src/ui/NoteEditActivity.java create mode 100644 src/ui/NoteEditText.java create mode 100644 src/ui/NoteItemData.java create mode 100644 src/ui/NotesListActivity.java create mode 100644 src/ui/NotesListAdapter.java create mode 100644 src/ui/NotesListItem.java create mode 100644 src/ui/NotesPreferenceActivity.java create mode 100644 src/widget/NoteWidgetProvider.java create mode 100644 src/widget/NoteWidgetProvider_2x.java create mode 100644 src/widget/NoteWidgetProvider_4x.java create mode 100644 src/新建文件夹/AlarmAlertActivity.java create mode 100644 src/新建文件夹/AlarmInitReceiver.java create mode 100644 src/新建文件夹/AlarmReceiver.java create mode 100644 src/新建文件夹/BackupUtils.java create mode 100644 src/新建文件夹/DataUtils.java create mode 100644 src/新建文件夹/DateTimePicker.java create mode 100644 src/新建文件夹/DateTimePickerDialog.java create mode 100644 src/新建文件夹/DropdownMenu.java create mode 100644 src/新建文件夹/FoldersListAdapter.java create mode 100644 src/新建文件夹/GTaskStringUtils.java create mode 100644 src/新建文件夹/NoteEditActivity.java create mode 100644 src/新建文件夹/NoteEditText.java create mode 100644 src/新建文件夹/NoteItemData.java create mode 100644 src/新建文件夹/NoteWidgetProvider.java create mode 100644 src/新建文件夹/NoteWidgetProvider_2x.java create mode 100644 src/新建文件夹/NoteWidgetProvider_4x.java create mode 100644 src/新建文件夹/NotesListActivity.java create mode 100644 src/新建文件夹/NotesListAdapter.java create mode 100644 src/新建文件夹/NotesListItem.java create mode 100644 src/新建文件夹/NotesPreferenceActivity.java create mode 100644 src/新建文件夹/ResourceParser.java diff --git a/src/ui/AlarmAlertActivity.java b/src/ui/AlarmAlertActivity.java new file mode 100644 index 0000000..c0e7362 --- /dev/null +++ b/src/ui/AlarmAlertActivity.java @@ -0,0 +1,203 @@ +/* + * 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. + */ + +package net.micode.notes.ui; + +import android.app.Activity; +import android.app.AlertDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.DialogInterface.OnClickListener; +import android.content.DialogInterface.OnDismissListener; +import android.content.Intent; +import android.media.AudioManager; +import android.media.MediaPlayer; +import android.media.RingtoneManager; +import android.net.Uri; +import android.os.Bundle; +import android.os.PowerManager; +import android.provider.Settings; +import android.view.Window; +import android.view.WindowManager; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +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 + | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON + | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR); + } + + // 获取启动当前Activity的Intent(由AlarmReceiver传递) + Intent intent = getIntent(); + + try { + // 从Intent的Data中解析便签ID(Data格式为content://.../notes/{id},取路径的第2段) + mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1)); + // 通过便签ID获取内容摘要(用于提醒展示) + 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; + } catch (IllegalArgumentException e) { + e.printStackTrace(); + return; + } + + // 初始化媒体播放器 + mPlayer = new MediaPlayer(); + // 检查便签是否存在且可见(未被删除) + if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) { + // 显示提醒对话框 + showActionDialog(); + // 播放闹钟声音 + playAlarmSound(); + } else { + // 便签不存在则直接结束活动 + finish(); + } + } + + /** + * 判断屏幕是否处于亮屏状态 + * @return 屏幕亮着返回true,否则返回false + */ + 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.start(); + } catch (IllegalArgumentException | SecurityException | IllegalStateException | IOException e) { + 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); + // 若屏幕亮着,添加“进入”按钮(跳转到便签编辑页) + if (isScreenOn()) { + dialog.setNegativeButton(R.string.notealert_enter, this); + } + // 显示对话框,并设置消失监听(用于停止铃声) + dialog.show().setOnDismissListener(this); + } + + /** + * 处理对话框按钮点击事件 + * @param dialog 对话框实例 + * @param which 点击的按钮标识(BUTTON_POSITIVE/BUTTON_NEGATIVE) + */ + 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); // 传递便签ID + startActivity(intent); + break; + // 点击“确定”按钮:默认不做额外操作,对话框消失后会停止铃声并结束活动 + default: + break; + } + } + + /** + * 对话框消失时触发:停止铃声并结束活动 + * @param dialog 对话框实例 + */ + public void onDismiss(DialogInterface dialog) { + stopAlarmSound(); + finish(); + } + + /** + * 停止闹钟铃声并释放媒体播放器资源 + */ + private void stopAlarmSound() { + if (mPlayer != null) { + mPlayer.stop(); // 停止播放 + mPlayer.release(); // 释放资源 + mPlayer = null; + } + } +} \ No newline at end of file diff --git a/src/ui/AlarmInitReceiver.java b/src/ui/AlarmInitReceiver.java new file mode 100644 index 0000000..919d47b --- /dev/null +++ b/src/ui/AlarmInitReceiver.java @@ -0,0 +1,100 @@ +/* + * 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. + */ + +package net.micode.notes.ui; + +import android.app.AlarmManager; +import android.app.PendingIntent; +import android.content.BroadcastReceiver; +import android.content.ContentUris; +import android.content.Context; +import android.content.Intent; +import android.database.Cursor; + +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; + +/** + * 便签提醒初始化接收器 + * 用于在系统启动或特定事件触发时,重新注册所有未过期的便签提醒闹钟 + * 确保用户设置的便签提醒不会因系统重启等原因丢失 + */ +public class AlarmInitReceiver extends BroadcastReceiver { + + /** + * 数据库查询字段投影:只查询便签ID和提醒时间 + * 优化查询效率,避免获取不必要的字段 + */ + private static final String [] PROJECTION = new String [] { + NoteColumns.ID, // 便签ID + NoteColumns.ALERTED_DATE // 提醒时间戳 + }; + + // 字段索引常量,用于快速访问Cursor中的数据 + private static final int COLUMN_ID = 0; // 便签ID在投影中的索引 + private static final int COLUMN_ALERTED_DATE = 1; // 提醒时间在投影中的索引 + + /** + * 接收广播时触发的回调方法 + * 负责查询所有未过期的便签提醒,并重新注册到AlarmManager + * @param context 上下文对象 + * @param intent 接收到的广播意图 + */ + @Override + public void onReceive(Context context, Intent intent) { + // 获取当前系统时间,用于筛选未过期的提醒 + long currentDate = System.currentTimeMillis(); + + // 查询数据库中所有未过期的便签提醒 + // 条件:提醒时间 > 当前时间 且 便签类型为普通便签(TYPE_NOTE) + Cursor c = context.getContentResolver().query( + Notes.CONTENT_NOTE_URI, // 查询的内容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); + // 创建触发提醒时的意图(指向AlarmReceiver) + Intent sender = new Intent(context, AlarmReceiver.class); + // 为意图附加便签ID,便于后续定位具体便签 + sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, + c.getLong(COLUMN_ID))); + + // 创建延迟执行的PendingIntent(用于触发提醒) + PendingIntent pendingIntent = PendingIntent.getBroadcast( + context, 0, sender, 0); + + // 获取AlarmManager服务,用于设置系统闹钟 + AlarmManager alermManager = (AlarmManager) context + .getSystemService(Context.ALARM_SERVICE); + + // 注册闹钟:在指定时间(alertDate)唤醒设备并发送广播 + // RTC_WAKEUP模式确保在设备休眠时也能触发 + alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent); + } while (c.moveToNext()); // 继续处理下一个便签 + } + // 关闭Cursor,释放资源 + c.close(); + } + } +} \ No newline at end of file diff --git a/src/ui/AlarmReceiver.java b/src/ui/AlarmReceiver.java new file mode 100644 index 0000000..722b750 --- /dev/null +++ b/src/ui/AlarmReceiver.java @@ -0,0 +1,46 @@ +/* + * 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. + */ + +package net.micode.notes.ui; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; + +/** + * 便签提醒广播接收器,负责接收系统闹钟触发的广播,并启动提醒展示界面 + * 是小米便签提醒流程中连接闹钟触发与提醒展示的中间组件 + */ +public class AlarmReceiver extends BroadcastReceiver { + /** + * 接收广播时触发的回调方法 + * @param context 上下文环境,用于启动Activity + * @param intent 接收到的意图,包含触发提醒的便签信息(如便签ID) + */ + @Override + public void onReceive(Context context, Intent intent) { + // 将意图的目标组件设置为AlarmAlertActivity(便签提醒展示界面) + // 确保广播中携带的便签信息(如Data中的便签ID)被传递给目标界面 + intent.setClass(context, AlarmAlertActivity.class); + + // 添加FLAG_ACTIVITY_NEW_TASK标志:在BroadcastReceiver中启动Activity必须设置此标志 + // 因为BroadcastReceiver本身没有任务栈,需要为启动的Activity创建新任务栈 + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + + // 启动AlarmAlertActivity,展示便签提醒对话框并播放铃声 + context.startActivity(intent); + } +} \ No newline at end of file diff --git a/src/ui/DateTimePicker.java b/src/ui/DateTimePicker.java new file mode 100644 index 0000000..906261f --- /dev/null +++ b/src/ui/DateTimePicker.java @@ -0,0 +1,576 @@ +/* + * 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. + */ + +package net.micode.notes.ui; + +import java.text.DateFormatSymbols; +import java.util.Calendar; + +import net.micode.notes.R; + + +import android.content.Context; +import android.text.format.DateFormat; +import android.view.View; +import android.widget.FrameLayout; +import android.widget.NumberPicker; + +/** + * 日期时间选择器组件 + * 用于小米便签中设置提醒时间,支持日期、小时、分钟的选择,以及12/24小时制切换 + */ +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 HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW = 0; // 24小时制小时最小值 + private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23; // 24小时制小时最大值 + private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1; // 12小时制小时最小值 + private static final int HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW = 12; // 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; // 上下午选择器(12小时制用) + private Calendar mDate; // 日期时间计算工具 + + // 日期显示值数组(存储近一周的日期文本) + private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK]; + + // 时间状态变量 + 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(); + } + }; + + /** + * 小时选择器值变化监听器 + * 处理小时变更逻辑,包括跨天情况(如23点到0点)和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(); + + if (!mIs24HourView) { + // 12小时制处理:跨天情况(如11PM到12AM需加一天,12AM到11PM需减一天) + 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) { + cal.setTimeInMillis(mDate.getTimeInMillis()); + cal.add(Calendar.DAY_OF_YEAR, -1); + isDateChanged = true; + } + // 12点和11点切换时,切换上下午状态 + 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小时制处理:跨天情况(如23点到0点加一天,0点到23点减一天) + 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) { + cal.setTimeInMillis(mDate.getTimeInMillis()); + cal.add(Calendar.DAY_OF_YEAR, -1); + isDateChanged = true; + } + } + + // 更新小时并触发事件 + 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)); + setCurrentDay(cal.get(Calendar.DAY_OF_MONTH)); + } + } + }; + + /** + * 分钟选择器值变化监听器 + * 处理分钟变更逻辑,包括跨小时情况(如59分到0分需加1小时) + */ + 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; + + // 判断是否跨小时(59->0加1小时,0->59减1小时) + if (oldVal == maxValue && newVal == minValue) { + offset += 1; + } else if (oldVal == minValue && newVal == maxValue) { + offset -= 1; + } + + if (offset != 0) { + // 调整小时并更新相关控件 + mDate.add(Calendar.HOUR_OF_DAY, offset); + mHourSpinner.setValue(getCurrentHour()); + updateDateControl(); + + // 更新上下午状态(12小时制) + int newHour = getCurrentHourOfDay(); + if (newHour >= HOURS_IN_HALF_DAY) { + mIsAm = false; + } else { + mIsAm = true; + } + updateAmPmControl(); + } + + // 更新分钟并触发事件 + mDate.set(Calendar.MINUTE, newVal); + onDateTimeChanged(); + } + }; + + /** + * 上下午选择器值变化监听器 + * 切换上午/下午状态,并调整小时(加减12小时) + */ + private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() { + @Override + public void onValueChange(NumberPicker picker, int oldVal, int newVal) { + mIsAm = !mIsAm; + // 切换上下午时调整小时(上午转下午加12小时,反之减12小时) + if (mIsAm) { + mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY); + } else { + mDate.add(Calendar.HOUR_OF_DAY, HOURS_IN_HALF_DAY); + } + updateAmPmControl(); + onDateTimeChanged(); + } + }; + + /** + * 日期时间变更监听器接口 + * 当用户修改日期或时间时回调 + */ + public interface OnDateTimeChangedListener { + void onDateTimeChanged(DateTimePicker view, int year, int month, + int dayOfMonth, int hourOfDay, int minute); + } + + /** + * 构造方法:使用当前时间初始化,默认使用系统时间格式(12/24小时制) + * @param context 上下文 + */ + public DateTimePicker(Context context) { + this(context, System.currentTimeMillis()); + } + + /** + * 构造方法:使用指定时间初始化,默认使用系统时间格式(12/24小时制) + * @param context 上下文 + * @param date 初始化时间戳(毫秒) + */ + public DateTimePicker(Context context, long date) { + this(context, date, DateFormat.is24HourFormat(context)); + } + + /** + * 构造方法:使用指定时间和时间格式初始化 + * @param context 上下文 + * @param date 初始化时间戳(毫秒) + * @param is24HourView 是否使用24小时制 + */ + public DateTimePicker(Context context, long date, boolean is24HourView) { + super(context); + 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.setOnValueChangedListener(mOnMinuteChangedListener); + + // 初始化上下午选择器(使用系统本地化的AM/PM文本) + 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.setOnValueChangedListener(mOnAmPmChangedListener); + + // 更新控件到初始状态 + updateDateControl(); + updateHourControl(); + updateAmPmControl(); + + // 设置时间格式(12/24小时制) + set24HourView(is24HourView); + + // 设置初始时间 + setCurrentDate(date); + + // 设置启用状态 + setEnabled(isEnabled()); + + // 初始化完成 + mInitialising = false; + } + + /** + * 设置组件启用状态 + * @param enabled 是否启用 + */ + @Override + public void setEnabled(boolean enabled) { + if (mIsEnabled == enabled) { + return; + } + super.setEnabled(enabled); + mDateSpinner.setEnabled(enabled); + mMinuteSpinner.setEnabled(enabled); + mHourSpinner.setEnabled(enabled); + mAmPmSpinner.setEnabled(enabled); + mIsEnabled = enabled; + } + + /** + * 获取组件启用状态 + * @return 是否启用 + */ + @Override + public boolean isEnabled() { + return mIsEnabled; + } + + /** + * 获取当前选中的日期时间(毫秒时间戳) + * @return 时间戳 + */ + public long getCurrentDateInTimeMillis() { + return mDate.getTimeInMillis(); + } + + /** + * 设置当前日期时间(通过时间戳) + * @param date 时间戳(毫秒) + */ + 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)); + } + + /** + * 设置当前日期时间(通过年月日时分) + * @param year 年 + * @param month 月(0-11) + * @param dayOfMonth 日 + * @param hourOfDay 时(24小时制,0-23) + * @param minute 分 + */ + public void setCurrentDate(int year, int month, + int dayOfMonth, int hourOfDay, int minute) { + setCurrentYear(year); + setCurrentMonth(month); + setCurrentDay(dayOfMonth); + setCurrentHour(hourOfDay); + setCurrentMinute(minute); + } + + /** + * 获取当前年份 + * @return 年份 + */ + public int getCurrentYear() { + return mDate.get(Calendar.YEAR); + } + + /** + * 设置当前年份 + * @param year 年份 + */ + public void setCurrentYear(int year) { + if (!mInitialising && year == getCurrentYear()) { + return; + } + mDate.set(Calendar.YEAR, year); + updateDateControl(); + onDateTimeChanged(); + } + + /** + * 获取当前月份(0-11) + * @return 月份 + */ + public int getCurrentMonth() { + return mDate.get(Calendar.MONTH); + } + + /** + * 设置当前月份 + * @param month 月份(0-11) + */ + public void setCurrentMonth(int month) { + if (!mInitialising && month == getCurrentMonth()) { + return; + } + mDate.set(Calendar.MONTH, month); + updateDateControl(); + onDateTimeChanged(); + } + + /** + * 获取当前日 + * @return 日 + */ + public int getCurrentDay() { + return mDate.get(Calendar.DAY_OF_MONTH); + } + + /** + * 设置当前日 + * @param dayOfMonth 日 + */ + public void setCurrentDay(int dayOfMonth) { + if (!mInitialising && dayOfMonth == getCurrentDay()) { + return; + } + mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth); + updateDateControl(); + onDateTimeChanged(); + } + + /** + * 获取当前小时(24小时制,0-23) + * @return 小时 + */ + public int getCurrentHourOfDay() { + return mDate.get(Calendar.HOUR_OF_DAY); + } + + /** + * 根据当前时间格式(12/24小时制)获取小时显示值 + * @return 小时显示值 + */ + private int getCurrentHour() { + if (mIs24HourView){ + return getCurrentHourOfDay(); + } else { + int hour = getCurrentHourOfDay(); + // 12小时制转换:13->1,0->12 + if (hour > HOURS_IN_HALF_DAY) { + return hour - HOURS_IN_HALF_DAY; + } else { + return hour == 0 ? HOURS_IN_HALF_DAY : hour; + } + } + } + + /** + * 设置当前小时(24小时制) + * @param hourOfDay 小时(0-23) + */ + public void setCurrentHour(int hourOfDay) { + if (!mInitialising && hourOfDay == getCurrentHourOfDay()) { + return; + } + mDate.set(Calendar.HOUR_OF_DAY, hourOfDay); + + if (!mIs24HourView) { + // 12小时制处理:更新上下午状态和小时显示值 + 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(); + } + + /** + * 获取当前分钟 + * @return 分钟 + */ + public int getCurrentMinute() { + return mDate.get(Calendar.MINUTE); + } + + /** + * 设置当前分钟 + * @param minute 分钟(0-59) + */ + public void setCurrentMinute(int minute) { + if (!mInitialising && minute == getCurrentMinute()) { + return; + } + mMinuteSpinner.setValue(minute); + mDate.set(Calendar.MINUTE, minute); + onDateTimeChanged(); + } + + /** + * 判断是否为24小时制显示 + * @return 是否为24小时制 + */ + public boolean is24HourView () { + return mIs24HourView; + } + + /** + * 设置时间显示格式(24小时制/12小时制) + * @param is24HourView true为24小时制,false为12小时制 + */ + public void set24HourView(boolean is24HourView) { + if (mIs24HourView == is24HourView) { + return; + } + mIs24HourView = is24HourView; + // 24小时制隐藏上下午选择器,12小时制显示 + 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()); + // 计算起始日期(当前日期减去3天,用于显示近一周) + 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(); + } + + /** + * 更新上下午选择器状态(根据12小时制和当前上下午状态) + */ + private void updateAmPmControl() { + if (mIs24HourView) { + mAmPmSpinner.setVisibility(View.GONE); + } else { + int index = mIsAm ? Calendar.AM : Calendar.PM; + mAmPmSpinner.setValue(index); + mAmPmSpinner.setVisibility(View.VISIBLE); + } + } + + /** + * 更新小时选择器的范围(根据12/24小时制) + */ + 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); + } + } + + /** + * 设置日期时间变更监听器 + * @param callback 监听器实例 + */ + public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) { + mOnDateTimeChangedListener = callback; + } + + /** + * 触发日期时间变更事件(通知监听器) + */ + private void onDateTimeChanged() { + if (mOnDateTimeChangedListener != null) { + mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(), + getCurrentMonth(), getCurrentDay(), getCurrentHourOfDay(), getCurrentMinute()); + } + } +} \ No newline at end of file diff --git a/src/ui/DateTimePickerDialog.java b/src/ui/DateTimePickerDialog.java new file mode 100644 index 0000000..309d989 --- /dev/null +++ b/src/ui/DateTimePickerDialog.java @@ -0,0 +1,137 @@ +/* + * 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. + */ + +package net.micode.notes.ui; + +import java.util.Calendar; + +import net.micode.notes.R; +import net.micode.notes.ui.DateTimePicker; +import net.micode.notes.ui.DateTimePicker.OnDateTimeChangedListener; + +import android.app.AlertDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.DialogInterface.OnClickListener; +import android.text.format.DateFormat; +import android.text.format.DateUtils; + +/** + * 日期时间选择对话框,用于小米便签中设置提醒时间的交互界面 + * 继承自AlertDialog,内部集成DateTimePicker作为选择视图,提供日期和时间的可视化选择 + */ +public class DateTimePickerDialog extends AlertDialog implements OnClickListener { + + // 用于维护当前选中的日期时间 + private Calendar mDate = Calendar.getInstance(); + // 是否采用24小时制显示时间 + private boolean mIs24HourView; + // 日期时间选择完成后的回调监听器(由调用者实现,如NoteEditActivity) + private OnDateTimeSetListener mOnDateTimeSetListener; + // 自定义的日期时间选择器视图,负责用户选择交互 + private DateTimePicker mDateTimePicker; + + /** + * 日期时间选择完成的回调接口 + * 当用户点击"确定"后,通过此接口将选中的时间(毫秒级时间戳)传递给调用者 + */ + public interface OnDateTimeSetListener { + void OnDateTimeSet(AlertDialog dialog, long date); + } + + /** + * 构造方法:初始化日期时间选择对话框 + * @param context 上下文环境(如NoteEditActivity) + * @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()); + + // 设置对话框按钮:"确定"按钮触发onClick方法,"取消"按钮不执行操作 + setButton(context.getString(R.string.datetime_dialog_ok), this); + setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null); + + // 根据系统设置初始化24小时制显示模式 + set24HourView(DateFormat.is24HourFormat(this.getContext())); + // 初始化对话框标题为初始日期时间 + updateTitle(mDate.getTimeInMillis()); + } + + /** + * 设置时间显示模式(24小时制/12小时制) + * @param is24HourView true为24小时制,false为12小时制 + */ + public void set24HourView(boolean is24HourView) { + mIs24HourView = is24HourView; + } + + /** + * 设置日期时间选择完成后的回调监听器 + * @param callBack 实现了OnDateTimeSetListener的对象(通常为调用对话框的Activity) + */ + 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小时制模式调整显示格式 + flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_12HOUR; + // 格式化时间并设置为对话框标题 + setTitle(DateUtils.formatDateTime(this.getContext(), date, flag)); + } + + /** + * 处理"确定"按钮的点击事件 + * 当用户点击确定后,通过回调接口将选中的时间传递给调用者 + */ + public void onClick(DialogInterface arg0, int arg1) { + if (mOnDateTimeSetListener != null) { + // 回调传递选中的时间(毫秒级时间戳) + mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis()); + } + } + +} \ No newline at end of file diff --git a/src/ui/DropdownMenu.java b/src/ui/DropdownMenu.java new file mode 100644 index 0000000..041b5f6 --- /dev/null +++ b/src/ui/DropdownMenu.java @@ -0,0 +1,92 @@ +/* + * 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. + */ + +package net.micode.notes.ui; + +import android.content.Context; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.view.View.OnClickListener; +import android.widget.Button; +import android.widget.PopupMenu; +import android.widget.PopupMenu.OnMenuItemClickListener; + +import net.micode.notes.R; + +/** + * 下拉菜单工具类,用于在小米便签中实现按钮触发的弹出式菜单 + * 典型场景:笔记列表的批量操作菜单、编辑页的功能选项菜单等 + */ +public class DropdownMenu { + // 触发下拉菜单的按钮 + private Button mButton; + // 系统提供的弹出式菜单组件,负责显示下拉选项 + private PopupMenu mPopupMenu; + // 菜单容器,存储从资源文件加载的菜单项 + private Menu mMenu; + + /** + * 构造方法:初始化下拉菜单 + * @param context 上下文对象,用于访问资源和创建视图 + * @param button 触发下拉菜单的按钮 + * @param menuId 菜单资源ID(定义在res/menu目录下) + */ + 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(); + } + }); + } + + /** + * 设置下拉菜单项的点击事件监听器 + * @param listener 监听器对象,处理菜单项点击逻辑 + */ + public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) { + if (mPopupMenu != null) { + mPopupMenu.setOnMenuItemClickListener(listener); + } + } + + /** + * 根据ID查找菜单中的具体选项 + * @param id 菜单项的资源ID + * @return 对应的MenuItem对象,可用于修改状态(如勾选、隐藏) + */ + public MenuItem findItem(int id) { + return mMenu.findItem(id); + } + + /** + * 设置触发按钮的显示文本 + * @param title 要显示的文本(如"已选择3项") + */ + public void setTitle(CharSequence title) { + mButton.setText(title); + } +} \ No newline at end of file diff --git a/src/ui/FoldersListAdapter.java b/src/ui/FoldersListAdapter.java new file mode 100644 index 0000000..6fee552 --- /dev/null +++ b/src/ui/FoldersListAdapter.java @@ -0,0 +1,130 @@ +/* + * 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. + */ + +package net.micode.notes.ui; + +import android.content.Context; +import android.database.Cursor; +import android.view.View; +import android.view.ViewGroup; +import android.widget.CursorAdapter; +import android.widget.LinearLayout; +import android.widget.TextView; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; + +/** + * 文件夹列表适配器,用于小米便签中展示文件夹列表(如移动便签时选择目标文件夹) + * 继承自CursorAdapter,负责将数据库中的文件夹数据与列表视图绑定 + */ +public class FoldersListAdapter extends CursorAdapter { + /** + * 数据库查询投影:指定需要查询的文件夹字段 + * 包含文件夹ID(用于区分不同文件夹)和文件夹名称(存储在SNIPPET字段) + */ + public static final String [] PROJECTION = { + NoteColumns.ID, // 文件夹ID + NoteColumns.SNIPPET // 文件夹名称(小米便签中文件夹名称存储在此字段) + }; + + /** + * 投影字段对应的索引,用于从Cursor中快速获取数据 + */ + public static final int ID_COLUMN = 0; // PROJECTION中ID字段的索引 + public static final int NAME_COLUMN = 1; // PROJECTION中SNIPPET(名称)字段的索引 + + /** + * 构造方法:初始化文件夹列表适配器 + * @param context 上下文环境(如调用文件夹列表的Activity或对话框) + * @param c 包含文件夹数据的数据库游标(查询结果) + */ + public FoldersListAdapter(Context context, Cursor c) { + super(context, c); + // TODO Auto-generated constructor stub + } + + /** + * 创建新的列表项视图 + * @param context 上下文环境 + * @param cursor 包含当前项数据的游标(此处未直接使用,仅用于创建视图) + * @param parent 父视图容器(通常为ListView) + * @return 自定义的文件夹列表项视图(FolderListItem实例) + */ + @Override + public View newView(Context context, Cursor cursor, ViewGroup parent) { + return new FolderListItem(context); + } + + /** + * 将游标中的文件夹数据绑定到列表项视图 + * @param view 列表项视图(FolderListItem实例) + * @param context 上下文环境 + * @param cursor 包含当前文件夹数据的游标 + */ + @Override + public void bindView(View view, Context context, Cursor cursor) { + if (view instanceof FolderListItem) { + // 处理根文件夹的特殊名称:根文件夹ID为Notes.ID_ROOT_FOLDER,显示为“移动到父文件夹” + 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); + // 根文件夹特殊处理,其他文件夹直接取SNIPPET字段值 + return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context + .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); + } + + /** + * 自定义文件夹列表项视图,继承LinearLayout,用于展示单个文件夹的名称 + */ + private class FolderListItem extends LinearLayout { + private TextView mName; // 用于显示文件夹名称的文本控件 + + /** + * 构造方法:初始化列表项布局和控件 + * @param context 上下文环境 + */ + public FolderListItem(Context context) { + super(context); + // 加载文件夹列表项的布局文件(folder_list_item.xml) + 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/ui/NoteEditActivity.java b/src/ui/NoteEditActivity.java new file mode 100644 index 0000000..e42e69c --- /dev/null +++ b/src/ui/NoteEditActivity.java @@ -0,0 +1,1161 @@ +package net.micode.notes.ui; + +import android.app.Activity; +import android.app.AlarmManager; +import android.app.AlertDialog; +import android.app.PendingIntent; +import android.app.SearchManager; +import android.appwidget.AppWidgetManager; +import android.content.ContentUris; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.Paint; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.text.Spannable; +import android.text.SpannableString; +import android.text.TextUtils; +import android.text.format.DateUtils; +import android.text.style.BackgroundColorSpan; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuItem; +import android.view.MotionEvent; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.WindowManager; +import android.widget.CheckBox; +import android.widget.CompoundButton; +import android.widget.CompoundButton.OnCheckedChangeListener; +import android.widget.EditText; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.TextView; +import android.widget.Toast; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.TextNote; +import net.micode.notes.model.WorkingNote; +import net.micode.notes.model.WorkingNote.NoteSettingChangedListener; +import net.micode.notes.tool.DataUtils; +import net.micode.notes.tool.ResourceParser; +import net.micode.notes.tool.ResourceParser.TextAppearanceResources; +import net.micode.notes.ui.DateTimePickerDialog.OnDateTimeSetListener; +import net.micode.notes.ui.NoteEditText.OnTextViewChangeListener; +import net.micode.notes.widget.NoteWidgetProvider_2x; +import net.micode.notes.widget.NoteWidgetProvider_4x; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + + +/** + * 笔记编辑活动类,负责笔记的创建、编辑、显示等核心功能 + * 实现了点击事件监听、笔记设置变化监听和文本视图变化监听接口 + */ +public class NoteEditActivity extends Activity implements OnClickListener, + NoteSettingChangedListener, OnTextViewChangeListener { + + /** + * 头部视图持有者类,用于缓存头部视图中的控件,优化性能 + */ + private class HeadViewHolder { + public TextView tvModified; // 显示笔记修改时间的文本视图 + public ImageView ivAlertIcon; // 提醒图标 + public TextView tvAlertDate; // 显示提醒日期的文本视图 + public ImageView ibSetBgColor; // 设置背景颜色的按钮 + } + + /** + * 背景颜色选择按钮映射表 + * 键:按钮资源ID,值:对应的背景颜色资源ID(来自ResourceParser) + */ + private static final Map sBgSelectorBtnsMap = new HashMap(); + static { + sBgSelectorBtnsMap.put(R.id.iv_bg_yellow, ResourceParser.YELLOW); + sBgSelectorBtnsMap.put(R.id.iv_bg_red, ResourceParser.RED); + sBgSelectorBtnsMap.put(R.id.iv_bg_blue, ResourceParser.BLUE); + sBgSelectorBtnsMap.put(R.id.iv_bg_green, ResourceParser.GREEN); + sBgSelectorBtnsMap.put(R.id.iv_bg_white, ResourceParser.WHITE); + } + + /** + * 背景颜色选择状态映射表 + * 键:背景颜色资源ID(来自ResourceParser),值:对应的选中状态图标资源ID + */ + private static final Map sBgSelectorSelectionMap = new HashMap(); + static { + sBgSelectorSelectionMap.put(ResourceParser.YELLOW, R.id.iv_bg_yellow_select); + sBgSelectorSelectionMap.put(ResourceParser.RED, R.id.iv_bg_red_select); + sBgSelectorSelectionMap.put(ResourceParser.BLUE, R.id.iv_bg_blue_select); + sBgSelectorSelectionMap.put(ResourceParser.GREEN, R.id.iv_bg_green_select); + sBgSelectorSelectionMap.put(ResourceParser.WHITE, R.id.iv_bg_white_select); + } + + /** + * 字体大小选择按钮映射表 + * 键:按钮资源ID,值:对应的字体大小资源ID(来自ResourceParser) + */ + private static final Map sFontSizeBtnsMap = new HashMap(); + static { + sFontSizeBtnsMap.put(R.id.ll_font_large, ResourceParser.TEXT_LARGE); + sFontSizeBtnsMap.put(R.id.ll_font_small, ResourceParser.TEXT_SMALL); + sFontSizeBtnsMap.put(R.id.ll_font_normal, ResourceParser.TEXT_MEDIUM); + sFontSizeBtnsMap.put(R.id.ll_font_super, ResourceParser.TEXT_SUPER); + } + + /** + * 字体大小选择状态映射表 + * 键:字体大小资源ID(来自ResourceParser),值:对应的选中状态图标资源ID + */ + private static final Map sFontSelectorSelectionMap = new HashMap(); + static { + sFontSelectorSelectionMap.put(ResourceParser.TEXT_LARGE, R.id.iv_large_select); + sFontSelectorSelectionMap.put(ResourceParser.TEXT_SMALL, R.id.iv_small_select); + 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; // 当前字体大小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; // 正则表达式模式(用于查询文本高亮) + + /** + * 活动创建时调用的方法 + * 初始化布局和活动状态 + */ + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + this.setContentView(R.layout.note_edit); // 设置布局文件 + + // 如果没有保存的状态,且初始化活动状态失败,则结束活动 + if (savedInstanceState == null && !initActivityState(getIntent())) { + finish(); + return; + } + initResources(); // 初始化资源和视图 + } + + /** + * 当活动从保存的状态恢复时调用 + * 用于在内存不足导致活动被销毁后,恢复之前的状态 + */ + @Override + protected void onRestoreInstanceState(Bundle savedInstanceState) { + super.onRestoreInstanceState(savedInstanceState); + // 如果保存的状态中包含笔记ID,则恢复对应的笔记 + if (savedInstanceState != null && savedInstanceState.containsKey(Intent.EXTRA_UID)) { + Intent intent = new Intent(Intent.ACTION_VIEW); + intent.putExtra(Intent.EXTRA_UID, savedInstanceState.getLong(Intent.EXTRA_UID)); + // 如果恢复状态失败,则结束活动 + if (!initActivityState(intent)) { + finish(); + return; + } + Log.d(TAG, "Restoring from killed activity"); + } + } + + /** + * 初始化活动状态,根据传入的意图处理笔记的加载或创建 + * @param intent 传入的意图,包含操作类型和相关数据 + * @return 初始化成功返回true,否则返回false + */ + private boolean initActivityState(Intent intent) { + /** + * 如果用户指定了查看操作(ACTION_VIEW)但未提供笔记ID, + * 则跳转到笔记列表活动 + */ + mWorkingNote = null; + // 处理查看已有笔记的操作 + if (TextUtils.equals(Intent.ACTION_VIEW, intent.getAction())) { + long noteId = intent.getLongExtra(Intent.EXTRA_UID, 0); + mUserQuery = ""; + + /** + * 从搜索结果启动的情况 + */ + 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); + showToast(R.string.error_note_not_exist); + finish(); + return false; + } else { + // 加载笔记 + mWorkingNote = WorkingNote.load(this, noteId); + if (mWorkingNote == null) { + Log.e(TAG, "load note failed with note id" + noteId); + finish(); + 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())) { + // 新笔记 + long folderId = intent.getLongExtra(Notes.INTENT_EXTRA_FOLDER_ID, 0); + int widgetId = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_ID, + AppWidgetManager.INVALID_APPWIDGET_ID); + int widgetType = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, + Notes.TYPE_WIDGET_INVALIDE); + int bgResId = intent.getIntExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, + ResourceParser.getDefaultBgId(this)); + + // 解析通话记录笔记 + String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER); + long callDate = intent.getLongExtra(Notes.INTENT_EXTRA_CALL_DATE, 0); + if (callDate != 0 && phoneNumber != null) { + if (TextUtils.isEmpty(phoneNumber)) { + 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); + if (mWorkingNote == null) { + Log.e(TAG, "load call note failed with note id" + noteId); + finish(); + return false; + } + } else { + // 创建新的通话记录笔记 + mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId, + widgetType, bgResId); + mWorkingNote.convertToCallNote(phoneNumber, callDate); + } + } else { + // 创建普通空笔记 + mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId, widgetType, + bgResId); + } + + // 设置软键盘状态:可见且调整布局大小 + getWindow().setSoftInputMode( + WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE + | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); + } else { + Log.e(TAG, "Intent not specified action, should not support"); + finish(); + return false; + } + // 设置笔记设置变化监听器 + mWorkingNote.setOnSettingStatusChangedListener(this); + return true; + } + + /** + * 活动恢复时调用的方法 + * 初始化笔记显示界面 + */ + @Override + protected void onResume() { + super.onResume(); + 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: 添加设置提醒的菜单。目前禁用,因为DateTimePicker尚未准备好 + */ + showAlertHeader(); // 显示提醒信息 + } + + /** + * 显示提醒头部信息 + * 根据提醒时间是否过期显示不同内容 + */ + private void showAlertHeader() { + if (mWorkingNote.hasClockAlert()) { + long time = System.currentTimeMillis(); + if (time > mWorkingNote.getAlertDate()) { + mNoteHeaderHolder.tvAlertDate.setText(R.string.note_alert_expired); // 提醒已过期 + } else { + // 显示相对时间(如"30分钟后") + mNoteHeaderHolder.tvAlertDate.setText(DateUtils.getRelativeTimeSpanString( + mWorkingNote.getAlertDate(), time, DateUtils.MINUTE_IN_MILLIS)); + } + mNoteHeaderHolder.tvAlertDate.setVisibility(View.VISIBLE); + mNoteHeaderHolder.ivAlertIcon.setVisibility(View.VISIBLE); + } else { + // 没有提醒时隐藏相关视图 + mNoteHeaderHolder.tvAlertDate.setVisibility(View.GONE); + mNoteHeaderHolder.ivAlertIcon.setVisibility(View.GONE); + }; + } + + /** + * 当活动收到新的意图时调用 + * 重新初始化活动状态 + */ + @Override + protected void onNewIntent(Intent intent) { + super.onNewIntent(intent); + initActivityState(intent); + } + + /** + * 当活动状态需要保存时调用 + * 保存当前正在编辑的笔记ID + */ + @Override + protected void onSaveInstanceState(Bundle outState) { + super.onSaveInstanceState(outState); + /** + * 对于没有ID的新笔记,应先保存以生成ID。 + * 如果编辑的笔记不值得保存,则没有ID,相当于创建新笔记 + */ + if (!mWorkingNote.existInDatabase()) { + saveNote(); + } + outState.putLong(Intent.EXTRA_UID, mWorkingNote.getNoteId()); + Log.d(TAG, "Save working note id: " + mWorkingNote.getNoteId() + " onSaveInstanceState"); + } + + /** + * 分发触摸事件 + * 用于处理背景颜色选择器和字体大小选择器的点击外部关闭逻辑 + */ + @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); + return true; + } + return super.dispatchTouchEvent(ev); + } + + /** + * 判断触摸事件是否在指定视图范围内 + * @param view 目标视图 + * @param ev 触摸事件 + * @return 触摸点在视图范围内返回true,否则返回false + */ + private boolean inRangeOfView(View view, MotionEvent ev) { + int []location = new int[2]; + view.getLocationOnScreen(location); // 获取视图在屏幕上的位置 + int x = location[0]; + int y = location[1]; + // 判断触摸点是否在视图的边界内 + if (ev.getX() < x + || ev.getX() > (x + view.getWidth()) + || ev.getY() < y + || ev.getY() > (y + view.getHeight())) { + return false; + } + return true; + } + /** + * 初始化界面资源和视图组件 + * 包括标题栏、编辑器、背景颜色选择器、字体大小选择器等 + */ + private void initResources() { + // 获取标题栏面板视图 + mHeadViewPanel = findViewById(R.id.note_title); + // 初始化标题栏视图持有者 + mNoteHeaderHolder = new HeadViewHolder(); + mNoteHeaderHolder.tvModified = (TextView) findViewById(R.id.tv_modified_date); // 最后修改时间文本 + mNoteHeaderHolder.ivAlertIcon = (ImageView) findViewById(R.id.iv_alert_icon); // 提醒图标 + mNoteHeaderHolder.tvAlertDate = (TextView) findViewById(R.id.tv_alert_date); // 提醒日期文本 + mNoteHeaderHolder.ibSetBgColor = (ImageView) findViewById(R.id.btn_set_bg_color); // 设置背景颜色按钮 + mNoteHeaderHolder.ibSetBgColor.setOnClickListener(this); // 绑定点击事件 + + // 获取笔记编辑器和其容器 + 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); + }; + + // 获取SharedPreferences用于存储字体大小设置 + mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); + // 从SharedPreferences读取保存的字体大小ID,默认使用默认字体大小 + mFontSizeId = mSharedPrefs.getInt(PREFERENCE_FONT_SIZE, ResourceParser.BG_DEFAULT_FONT_SIZE); + /** + * 修复SharedPreferences中存储的资源ID可能超出资源长度的问题 + * 若超出则使用默认字体大小 + */ + 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; + } + + // 传入小部件ID并发送广播 + 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); + // 更新笔记的背景颜色ID + mWorkingNote.setBgColorId(sBgSelectorBtnsMap.get(id)); + // 隐藏背景颜色选择器 + mNoteBgColorSelector.setVisibility(View.GONE); + } + // 处理字体大小选择器中的按钮点击 + else if (sFontSizeBtnsMap.containsKey(id)) { + // 隐藏之前选中的字体大小指示器 + findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.GONE); + // 更新字体大小ID并保存到SharedPreferences + 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(); + } + + /** + * 清除设置面板的显示状态 + * 隐藏背景颜色选择器和字体大小选择器 + * @return 若有面板被隐藏则返回true,否则返回false + */ + 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(); + } + + /** + * 分享笔记内容到其他应用 + * 通过ACTION_SEND意图分享纯文本内容 + * @param context 上下文 + * @param info 要分享的文本内容 + */ + 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() { + // 保存当前编辑的笔记 + saveNote(); + + // 安全起见,关闭当前活动并启动新的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(); + // 检查笔记ID是否有效 + 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); + } + + /** + * 判断是否处于同步模式 + * @return 若设置了同步账户则返回true,否则返回false + */ + private boolean isSyncMode() { + return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; + } + + /** + * 提醒时间改变时调用 + * 处理闹钟的设置或取消 + * @param date 提醒时间戳 + * @param set 是否设置提醒(true为设置,false为取消) + */ + public void onClockAlertChanged(long date, boolean set) { + /** + * 用户可能为未保存的笔记设置提醒,因此在设置前需先保存笔记 + */ + if (!mWorkingNote.existInDatabase()) { + saveNote(); + } + // 笔记ID有效时处理闹钟 + 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 { + /** + * 若用户未输入内容(笔记未保存),无有效ID,提示用户输入内容 + */ + Log.e(TAG, "Clock alert setting error"); + showToast(R.string.error_note_empty_for_clock); + } + } + + /** + * 小部件改变时调用 + * 触发小部件更新 + */ + public void onWidgetChanged() { + updateWidget(); + } + + /** + * 处理编辑框删除事件(清单模式下) + * @param index 要删除的编辑框索引 + * @param text 被删除的文本内容 + */ + 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); + } + + /** + * 处理编辑框回车事件(清单模式下) + * 在当前位置插入新的编辑框 + * @param index 当前编辑框索引 + * @param text 编辑框中的文本内容 + */ + public void onEditTextEnter(int index, String text) { + /** + * 理论上不会发生,用于调试检查 + */ + 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); + } + } + + /** + * 切换到清单模式 + * 将普通文本按换行分割为多个清单项 + * @param text 要转换的文本内容 + */ + 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); + } + + /** + * 高亮显示查询结果 + * 对文本中与查询词匹配的部分设置背景色 + * @param fullText 完整文本 + * @param userQuery 用户查询词 + * @return 处理后的带高亮效果的文本 + */ + 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; + } + /** + * 创建并返回列表模式下的列表项视图 + * @param item 列表项的文本内容 + * @param index 列表项的索引位置 + * @return 构建好的列表项视图 + */ + 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; + } + + /** + * 文本内容变化时回调(控制复选框显示/隐藏) + * @param index 列表项索引 + * @param hasText 文本是否有内容 + */ + 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); + } + } + + /** + * 检查列表模式切换时的处理 + * @param oldMode 旧模式 + * @param newMode 新模式 + */ + 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); + } + } + + /** + * 获取当前编辑的文本内容(根据模式处理) + * @return 是否包含已勾选的列表项 + */ + 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; + } + + /** + * 保存笔记内容 + * @return 是否保存成功 + */ + private boolean saveNote() { + // 先获取当前编辑的内容 + getWorkingText(); + // 保存笔记 + boolean saved = mWorkingNote.saveNote(); + if (saved) { + /** + * 从列表页进入编辑页有两种模式: + * 1. 打开已有笔记:返回时需要定位到原位置 + * 2. 创建新笔记:返回时需要定位到列表顶部 + * 通过设置RESULT_OK标识当前是创建/编辑状态 + */ + setResult(RESULT_OK); + } + return saved; + } + + /** + * 将笔记发送到桌面(创建快捷方式) + */ + private void sendToDesktop() { + /** + * 发送到桌面之前确保笔记已保存到数据库 + * 对于新笔记,先执行保存操作 + */ + if (!mWorkingNote.existInDatabase()) { + saveNote(); + } + + // 笔记ID有效时创建快捷方式 + 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 { + /** + * 处理异常情况:用户未输入内容(笔记未保存) + * 此时无有效笔记ID,提示用户输入内容 + */ + Log.e(TAG, "Send to desktop error"); + showToast(R.string.error_note_empty_for_send_to_desktop); + } + } + + /** + * 生成快捷方式图标标题(处理特殊前缀并限制长度) + * @param content 笔记内容 + * @return 处理后的标题 + */ + 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; + } + + /** + * 显示短时长提示信息 + * @param resId 字符串资源ID + */ + private void showToast(int resId) { + showToast(resId, Toast.LENGTH_SHORT); + } + + /** + * 显示指定时长的提示信息 + * @param resId 字符串资源ID + * @param duration 时长(Toast.LENGTH_SHORT/Toast.LENGTH_LONG) + */ + private void showToast(int resId, int duration) { + Toast.makeText(this, resId, duration).show(); + } +} \ No newline at end of file diff --git a/src/ui/NoteEditText.java b/src/ui/NoteEditText.java new file mode 100644 index 0000000..bfcb48d --- /dev/null +++ b/src/ui/NoteEditText.java @@ -0,0 +1,288 @@ +/* + * 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. + */ + +package net.micode.notes.ui; + +import android.content.Context; +import android.graphics.Rect; +import android.text.Layout; +import android.text.Selection; +import android.text.Spanned; +import android.text.TextUtils; +import android.text.style.URLSpan; +import android.util.AttributeSet; +import android.util.Log; +import android.view.ContextMenu; +import android.view.KeyEvent; +import android.view.MenuItem; +import android.view.MenuItem.OnMenuItemClickListener; +import android.view.MotionEvent; +import android.widget.EditText; + +import net.micode.notes.R; + +import java.util.HashMap; +import java.util.Map; + +/** + * 小米便签的自定义文本输入控件,继承自EditText,扩展了便签编辑的核心交互功能 + * 支持多输入框管理、链接识别与交互、精确光标定位等 + */ +public class NoteEditText extends EditText { + private static final String TAG = "NoteEditText"; + // 当前输入框在多输入框列表中的索引(用于区分不同输入框) + private int mIndex; + // 记录删除键按下前的光标起始位置(用于判断是否删除当前输入框) + private int mSelectionStartBeforeDelete; + + // 支持的链接协议常量 + private static final String SCHEME_TEL = "tel:" ; // 电话协议(如"tel:10086") + private static final String SCHEME_HTTP = "http:" ; // 网页协议(如"http://www.micode.net") + private static final String SCHEME_EMAIL = "mailto:" ; // 邮件协议(如"mailto:test@micode.net") + + // 链接协议与对应菜单资源的映射(用于上下文菜单显示对应操作文字) + 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); // 邮件链接对应"发送邮件"菜单 + } + + /** + * 文本视图变化监听器,由{@link NoteEditActivity}实现,用于处理输入框的增删和文本状态变化 + */ + public interface OnTextViewChangeListener { + /** + * 当按下删除键且文本为空时,删除当前输入框 + * @param index 当前输入框的索引 + * @param text 当前输入框的文本内容 + */ + void onEditTextDelete(int index, String text); + + /** + * 当按下回车键时,在当前输入框后新增一个输入框 + * @param index 新增输入框的索引(当前索引+1) + * @param text 回车键后需要移动到新输入框的文本 + */ + void onEditTextEnter(int index, String text); + + /** + * 当文本内容变化时,通知是否显示输入框相关操作选项 + * @param index 当前输入框的索引 + * @param hasText 文本是否非空(用于控制操作选项的显示/隐藏) + */ + void onTextChange(int index, boolean hasText); + } + + // 文本变化监听器实例(由NoteEditActivity设置) + private OnTextViewChangeListener mOnTextViewChangeListener; + + /** + * 构造方法:初始化文本输入控件(仅上下文参数) + * @param context 上下文环境(如NoteEditActivity) + */ + public NoteEditText(Context context) { + super(context, null); + mIndex = 0; // 默认索引为0 + } + + /** + * 设置当前输入框在多输入框列表中的索引 + * @param index 输入框索引 + */ + public void setIndex(int index) { + mIndex = index; + } + + /** + * 设置文本变化监听器,关联到NoteEditActivity + * @param listener 实现了OnTextViewChangeListener的监听器 + */ + public void setOnTextViewChangeListener(OnTextViewChangeListener listener) { + mOnTextViewChangeListener = listener; + } + + /** + * 构造方法:初始化文本输入控件(上下文+属性集) + * @param context 上下文环境 + * @param attrs 布局中定义的属性集合 + */ + public NoteEditText(Context context, AttributeSet attrs) { + super(context, attrs, android.R.attr.editTextStyle); + } + + /** + * 构造方法:初始化文本输入控件(上下文+属性集+样式) + * @param context 上下文环境 + * @param attrs 属性集合 + * @param defStyle 默认样式 + */ + public NoteEditText(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + // TODO Auto-generated constructor stub + } + + /** + * 处理触摸事件,精确设置光标位置(根据触摸坐标计算光标应在的文本位置) + * @param event 触摸事件(包含触摸坐标等信息) + * @return 事件是否被处理 + */ + @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(); + y -= getTotalPaddingTop(); + x += getScrollX(); + y += getScrollY(); + + // 根据坐标获取对应的文本行和偏移量,设置光标位置 + Layout layout = getLayout(); + int line = layout.getLineForVertical(y); // 触摸点所在的文本行 + int off = layout.getOffsetForHorizontal(line, x); // 行内的水平偏移(光标位置) + Selection.setSelection(getText(), off); // 设置光标 + break; + } + return super.onTouchEvent(event); + } + + /** + * 处理键盘按下事件,记录删除键按下前的光标位置 + * @param keyCode 按键代码(如KEYCODE_DEL、KEYCODE_ENTER) + * @param event 键盘事件 + * @return 事件是否被处理 + */ + @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: + break; + } + return super.onKeyDown(keyCode, event); + } + + /** + * 处理键盘抬起事件,触发输入框增删逻辑 + * @param keyCode 按键代码 + * @param event 键盘事件 + * @return 事件是否被处理 + */ + @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()); + return true; + } + } else { + Log.d(TAG, "OnTextViewChangeListener was not seted"); + } + break; + case KeyEvent.KEYCODE_ENTER: + if (mOnTextViewChangeListener != null) { + // 处理回车键:将光标后的文本移至新输入框 + int selectionStart = getSelectionStart(); + String text = getText().subSequence(selectionStart, length()).toString(); // 光标后文本 + setText(getText().subSequence(0, selectionStart)); // 保留光标前文本 + mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text); // 通知新增输入框 + } else { + Log.d(TAG, "OnTextViewChangeListener was not seted"); + } + break; + default: + break; + } + return super.onKeyUp(keyCode, event); + } + + /** + * 处理焦点变化事件,通知监听器文本是否为空(用于控制操作选项显示) + * @param focused 是否获得焦点 + * @param direction 焦点移动方向 + * @param previouslyFocusedRect 上一个焦点区域 + */ + @Override + protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { + if (mOnTextViewChangeListener != null) { + // 失去焦点且文本为空时,通知无文本;否则通知有文本 + if (!focused && TextUtils.isEmpty(getText())) { + mOnTextViewChangeListener.onTextChange(mIndex, false); + } else { + mOnTextViewChangeListener.onTextChange(mIndex, true); + } + } + super.onFocusChanged(focused, direction, previouslyFocusedRect); + } + + /** + * 创建上下文菜单,识别选中的链接并显示对应操作选项(如拨打、打开网页) + * @param menu 上下文菜单实例 + */ + @Override + protected void onCreateContextMenu(ContextMenu menu) { + // 仅处理富文本中的链接 + if (getText() instanceof Spanned) { + int selStart = getSelectionStart(); + int selEnd = getSelectionEnd(); + int min = Math.min(selStart, selEnd); + int max = Math.max(selStart, selEnd); + + // 获取选中区域内的链接 + final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class); + if (urls.length == 1) { // 仅处理单个链接的情况 + int defaultResId = 0; + // 识别链接协议,匹配对应的菜单资源 + for(String schema: sSchemaActionResMap.keySet()) { + if(urls[0].getURL().indexOf(schema) >= 0) { + defaultResId = sSchemaActionResMap.get(schema); + break; + } + } + + // 未匹配到已知协议时,使用默认菜单文本 + if (defaultResId == 0) { + defaultResId = R.string.note_link_other; + } + + // 向菜单添加链接操作项,点击后触发链接的默认行为(如拨号、打开浏览器) + menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener( + new OnMenuItemClickListener() { + public boolean onMenuItemClick(MenuItem item) { + urls[0].onClick(NoteEditText.this); // 触发URLSpan的点击事件 + return true; + } + }); + } + } + super.onCreateContextMenu(menu); + } +} \ No newline at end of file diff --git a/src/ui/NoteItemData.java b/src/ui/NoteItemData.java new file mode 100644 index 0000000..8259487 --- /dev/null +++ b/src/ui/NoteItemData.java @@ -0,0 +1,319 @@ +/* + * 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. + */ + +package net.micode.notes.ui; + +import android.content.Context; +import android.database.Cursor; +import android.text.TextUtils; + +import net.micode.notes.data.Contact; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.tool.DataUtils; + + +/** + * 小米便签列表项的数据模型类,封装单个便签的核心信息及列表位置属性,用于支撑列表UI展示 + */ +public class NoteItemData { + // 数据库查询的列名数组,对应便签表的核心字段 + 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, // 桌面插件类型 + }; + + // 上述PROJECTION数组中各列的索引常量,用于从Cursor中提取数据 + 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; // 类型(Notes.TYPE_NOTE:便签;TYPE_FOLDER:文件夹等) + private int mWidgetId; // 关联的桌面插件ID(无则为无效值) + private int mWidgetType; // 桌面插件类型(无则为无效值) + private String mName; // 通话记录便签的联系人姓名(非通话记录则为空) + private String mPhoneNumber; // 通话记录便签的电话号码(非通话记录则为空) + + // 列表位置属性(用于UI背景样式适配) + 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); + mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN); + mHasAttachment = (cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0) ? true : false; + mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN); + 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)) { + mName = Contact.getContact(context, mPhoneNumber); // 获取联系人姓名 + if (mName == null) { + mName = mPhoneNumber; // 无联系人时显示电话号码 + } + } + } + + if (mName == null) { + mName = ""; + } + // 计算当前项在列表中的位置属性 + checkPostion(cursor); + } + + /** + * 判断当前项在游标中的位置,初始化位置属性(用于UI背景样式适配) + * @param cursor 数据库查询结果游标 + */ + private void checkPostion(Cursor cursor) { + mIsLastItem = cursor.isLast() ? true : false; // 是否为最后一项 + mIsFirstItem = cursor.isFirst() ? true : false; // 是否为第一项 + mIsOnlyOneItem = (cursor.getCount() == 1); // 是否为唯一一项 + + // 初始化文件夹后便签的位置属性 + mIsMultiNotesFollowingFolder = false; + mIsOneNoteFollowingFolder = false; + + // 若当前是便签项且不是第一项,检查前一项是否为文件夹 + if (mType == Notes.TYPE_NOTE && !mIsFirstItem) { + int position = cursor.getPosition(); + if (cursor.moveToPrevious()) { // 移动到前一项 + // 前一项是文件夹或系统文件夹 + if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER + || cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) { + // 若游标总数大于当前位置+1,说明文件夹后有多个便签 + if (cursor.getCount() > (position + 1)) { + mIsMultiNotesFollowingFolder = true; + } else { + // 否则文件夹后只有当前一个便签 + mIsOneNoteFollowingFolder = true; + } + } + // 移回原位置,避免游标错乱 + if (!cursor.moveToNext()) { + throw new IllegalStateException("cursor move to previous but can't move back"); + } + } + } + } + + /** + * 是否为文件夹后的唯一便签项 + */ + public boolean isOneFollowingFolder() { + return mIsOneNoteFollowingFolder; + } + + /** + * 是否为文件夹后的多个便签项之一 + */ + public boolean isMultiFollowingFolder() { + return mIsMultiNotesFollowingFolder; + } + + /** + * 是否为列表最后一项 + */ + public boolean isLast() { + return mIsLastItem; + } + + /** + * 获取通话记录便签的联系人姓名(非通话记录返回空) + */ + public String getCallName() { + return mName; + } + + /** + * 是否为列表第一项 + */ + public boolean isFirst() { + return mIsFirstItem; + } + + /** + * 是否为列表中唯一一项 + */ + public boolean isSingle() { + return mIsOnlyOneItem; + } + + /** + * 获取便签ID + */ + public long getId() { + return mId; + } + + /** + * 获取提醒时间(毫秒时间戳) + */ + public long getAlertDate() { + return mAlertDate; + } + + /** + * 获取创建时间(毫秒时间戳) + */ + public long getCreatedDate() { + return mCreatedDate; + } + + /** + * 是否有附件 + */ + public boolean hasAttachment() { + return mHasAttachment; + } + + /** + * 获取最后修改时间(毫秒时间戳) + */ + public long getModifiedDate() { + return mModifiedDate; + } + + /** + * 获取背景色ID + */ + public int getBgColorId() { + return mBgColorId; + } + + /** + * 获取所属文件夹ID + */ + public long getParentId() { + return mParentId; + } + + /** + * 获取文件夹包含的便签数量(仅文件夹类型有效) + */ + public int getNotesCount() { + return mNotesCount; + } + + /** + * 获取所属文件夹ID(与getParentId一致,兼容不同调用场景) + */ + public long getFolderId () { + return mParentId; + } + + /** + * 获取类型(便签/文件夹/系统文件夹) + */ + public int getType() { + return mType; + } + + /** + * 获取桌面插件类型 + */ + public int getWidgetType() { + return mWidgetType; + } + + /** + * 获取桌面插件ID + */ + public int getWidgetId() { + return mWidgetId; + } + + /** + * 获取内容摘要(文件夹名或便签内容片段) + */ + public String getSnippet() { + return mSnippet; + } + + /** + * 是否设置了提醒(提醒时间>0) + */ + public boolean hasAlert() { + return (mAlertDate > 0); + } + + /** + * 是否为通话记录便签(属于通话记录文件夹且有电话号码) + */ + public boolean isCallRecord() { + return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber)); + } + + /** + * 从游标中获取便签类型 + * @param cursor 数据库查询结果游标 + * @return 便签类型(Notes.TYPE_NOTE等) + */ + public static int getNoteType(Cursor cursor) { + return cursor.getInt(TYPE_COLUMN); + } +} \ No newline at end of file diff --git a/src/ui/NotesListActivity.java b/src/ui/NotesListActivity.java new file mode 100644 index 0000000..b80c6ad --- /dev/null +++ b/src/ui/NotesListActivity.java @@ -0,0 +1,1232 @@ +/* + * 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. + */ + +package net.micode.notes.ui; + +import android.app.Activity; +import android.app.AlertDialog; +import android.app.Dialog; +import android.appwidget.AppWidgetManager; +import android.content.AsyncQueryHandler; +import android.content.ContentResolver; +import android.content.ContentValues; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.database.Cursor; +import android.os.AsyncTask; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.text.Editable; +import android.text.TextUtils; +import android.text.TextWatcher; +import android.util.Log; +import android.view.ActionMode; +import android.view.ContextMenu; +import android.view.ContextMenu.ContextMenuInfo; +import android.view.Display; +import android.view.HapticFeedbackConstants; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuItem; +import android.view.MenuItem.OnMenuItemClickListener; +import android.view.MotionEvent; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.View.OnCreateContextMenuListener; +import android.view.View.OnTouchListener; +import android.view.inputmethod.InputMethodManager; +import android.widget.AdapterView; +import android.widget.AdapterView.OnItemClickListener; +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; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.gtask.remote.GTaskSyncService; +import net.micode.notes.model.WorkingNote; +import net.micode.notes.tool.BackupUtils; +import net.micode.notes.tool.DataUtils; +import net.micode.notes.tool.ResourceParser; +import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute; +import net.micode.notes.widget.NoteWidgetProvider_2x; +import net.micode.notes.widget.NoteWidgetProvider_4x; + +import java.io.BufferedReader; +import java.io.IOException; +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 MENU_FOLDER_DELETE = 0; + // 上下文菜单选项:查看文件夹 + private static final int MENU_FOLDER_VIEW = 1; + // 上下文菜单选项:重命名文件夹 + private static final int MENU_FOLDER_CHANGE_NAME = 2; + + // SharedPreferences键:记录是否已添加应用介绍笔记 + private static final String PREFERENCE_ADD_INTRODUCTION = "net.micode.notes.introduction"; + + /** + * 列表状态枚举: + * - NOTE_LIST:显示普通笔记列表(根目录) + * - SUB_FOLDER:显示子文件夹内容 + * - CALL_RECORD_FOLDER:显示通话记录文件夹内容 + */ + private enum ListEditState { + NOTE_LIST, SUB_FOLDER, CALL_RECORD_FOLDER + }; + + // 当前列表状态 + private ListEditState mState; + // 异步查询处理器,用于处理ContentProvider的查询操作(避免主线程阻塞) + private BackgroundQueryHandler mBackgroundQueryHandler; + // 笔记列表适配器,负责将数据绑定到ListView + private NotesListAdapter mNotesListAdapter; + // 笔记列表视图 + private ListView mNotesListView; + // 新建笔记按钮 + private Button mAddNewNote; + // 触摸事件分发标记:是否将事件分发给ListView + private boolean mDispatch; + // 触摸起始Y坐标(用于处理新建按钮的透明区域点击) + private int mOriginY; + // 分发给ListView的Y坐标(修正偏移后的坐标) + private int mDispatchY; + // 标题栏文本视图 + private TextView mTitleBar; + // 当前所在文件夹ID(默认根目录) + private long mCurrentFolderId; + // 内容解析器,用于操作ContentProvider + private ContentResolver mContentResolver; + // 多选模式回调,处理列表多选状态的逻辑 + private ModeCallback mModeCallBack; + // 日志标记 + private static final String TAG = "NotesListActivity"; + // 列表滚动速率 + public static final int NOTES_LISTVIEW_SCROLL_RATE = 30; + // 当前聚焦的笔记数据项(用于上下文操作) + private NoteItemData mFocusNoteDataItem; + + // 普通文件夹查询条件:按父文件夹ID筛选 + private static final String NORMAL_SELECTION = NoteColumns.PARENT_ID + "=?"; + // 根目录查询条件: + // 1. 非系统类型且父ID为根目录的项 + // 2. 通话记录文件夹且包含笔记的项 + 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; + @Override + /** + * Activity创建时调用的生命周期方法,用于初始化界面和数据 + * @param savedInstanceState 保存的实例状态,用于恢复数据(如屏幕旋转时) + */ + /*Bundle 是一个专门用于存储和传递键值对数据的核心类,设计初衷是为了解决组件间的数据交互问题,尤其适合在生命周期变化时暂存和传递数据*/ + protected void onCreate(Bundle savedInstanceState) { + // 调用父类Activity的onCreate方法,完成基础初始化 + super.onCreate(savedInstanceState); + // 设置当前Activity的布局文件为note_list.xml + // (布局文件定义了便签列表的UI结构,如ListView、添加按钮等) + setContentView(R.layout.note_list); + // 初始化界面资源和成员变量(如列表视图、适配器、事件监听器等) + initResources(); + + /** + * 当用户首次使用应用时,插入一条介绍性便签 + * (引导用户了解应用功能,仅在首次启动时执行) + */ + 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); + } else { + super.onActivityResult(requestCode, resultCode, data); + } + } + + /** + * 首次启动应用时,从raw资源读取引导文本并创建引导便签 + * 仅在用户第一次打开应用时执行,通过SharedPreferences标记避免重复创建 + */ + private void setAppInfoFromRawRes() { + SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); + + // 检查是否已添加过引导便签(通过PREFERENCE_ADD_INTRODUCTION标记判断) + // 若为false,说明是首次使用,需要创建引导便签 + if (!sp.getBoolean(PREFERENCE_ADD_INTRODUCTION, false)) { + // 用于拼接读取到的引导文本内容 + /*StringBuilder 是 Java 中用于动态拼接字符串的类,属于 java.lang 包*/ + StringBuilder sb = new StringBuilder(); + // 输入流,用于读取raw资源文件,InputStream 是 Java 中处理字节输入流的抽象类,属于 java.io 包 + InputStream in = null; + + try { + // 打开raw目录下的introduction文件(引导文本内容) + in = getResources().openRawResource(R.raw.introduction); + + // 若文件打开成功 + if (in != null) { + // 构建字符输入流(指定默认编码) + InputStreamReader isr = new InputStreamReader(in); + // 缓冲字符流,提高读取效率 + BufferedReader br = new BufferedReader(isr); + // 缓冲区,每次读取1024个字符 + char [] buf = new char[1024]; + // 记录每次读取的字符长度 + int len = 0; + + // 循环读取文件内容,直到末尾(len=-1时结束) + while ((len = br.read(buf)) > 0) { + // 将读取到的字符追加到字符串构建器 + sb.append(buf, 0, len); + } + } else { + // 文件打开失败时记录错误日志并返回 + Log.e(TAG, "Read introduction file error"); + return; + } + } catch (IOException e) { + // 读取过程中发生IO异常时,打印堆栈信息并返回 + e.printStackTrace(); + return; + } finally { + // 确保输入流最终被关闭,释放资源 + if(in != null) { + try { + in.close(); + } catch (IOException e) { + // 关闭流时发生异常,打印堆栈信息 + e.printStackTrace(); + } + } + } + + // 创建一个空便签对象 + // 参数说明: + // - 上下文:当前Activity + // - 父文件夹ID:根目录(Notes.ID_ROOT_FOLDER) + // - 桌面部件ID:无效(因为不是桌面部件生成的便签) + // - 部件类型:无效 + // - 背景色:红色(ResourceParser.RED) + 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"); + return; + } + } + } + + @Override + + protected void onStart() { + // 调用父类的onStart()方法,确保Activity生命周期的正常执行 + super.onStart(); + // 启动异步查询笔记列表数据的操作 + startAsyncNotesListQuery(); + } + /** + * 初始化视图资源和监听器 + */ + private void initResources() { + mContentResolver = this.getContentResolver(); + mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver()); + 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); + // 设置列表项点击监听器 + mNotesListView.setOnItemClickListener(new OnListItemClickListener()); + // 设置列表项长按监听器 + 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; + + mTitleBar = (TextView) findViewById(R.id.tv_title_bar); + mState = ListEditState.NOTE_LIST; // 默认状态为普通笔记列表 + mModeCallBack = new ModeCallback(); // 初始化多选模式回调 + } + + /** + * 多选模式回调类,实现列表项的批量操作(删除、移动等) + */ + private class ModeCallback implements ListView.MultiChoiceModeListener, OnMenuItemClickListener { + private DropdownMenu mDropDownMenu; // 下拉菜单(全选/取消全选) + private ActionMode mActionMode; // 动作模式实例 + private MenuItem mMoveMenu; // 移动菜单选项 + + /** + * 创建动作模式时调用,初始化菜单 + */ + 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) { + mMoveMenu.setVisible(false); + } else { + mMoveMenu.setVisible(true); + mMoveMenu.setOnMenuItemClickListener(this); + } + + mActionMode = mode; + mNotesListAdapter.setChoiceMode(true); // 适配器启用多选模式 + mNotesListView.setLongClickable(false); // 多选模式下禁用长按 + 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(){ + public boolean onMenuItemClick(MenuItem item) { + mNotesListAdapter.selectAll(!mNotesListAdapter.isAllSelected()); + updateMenu(); // 更新菜单状态 + return true; + } + }); + return true; + } + + /** + * 更新菜单状态(显示选中数量、切换全选/取消全选文本) + */ + private void updateMenu() { + int selectedCount = mNotesListAdapter.getSelectedCount(); + // 更新下拉菜单标题(显示选中数量) + 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()) { + item.setChecked(true); + item.setTitle(R.string.menu_deselect_all); + } else { + item.setChecked(false); + item.setTitle(R.string.menu_select_all); + } + } + } + + /** + * 准备动作模式时调用(未实现具体逻辑) + */ + public boolean onPrepareActionMode(ActionMode mode, Menu menu) { + return false; + } + + /** + * 动作项点击时调用(未实现具体逻辑) + */ + public boolean onActionItemClicked(ActionMode mode, MenuItem item) { + return false; + } + + /** + * 销毁动作模式时调用,恢复列表状态 + */ + public void onDestroyActionMode(ActionMode mode) { + mNotesListAdapter.setChoiceMode(false); // 关闭多选模式 + mNotesListView.setLongClickable(true); // 恢复长按功能 + mAddNewNote.setVisibility(View.VISIBLE); // 显示新建按钮 + } + + /** + * 结束动作模式 + */ + public void finishActionMode() { + 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), + Toast.LENGTH_SHORT).show(); + return true; + } + + 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); + builder.setMessage(getString(R.string.alert_message_delete_notes, + mNotesListAdapter.getSelectedCount())); + builder.setPositiveButton(android.R.string.ok, + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, + int which) { + batchDelete(); // 执行批量删除 + } + }); + builder.setNegativeButton(android.R.string.cancel, null); + builder.show(); + break; + case R.id.move: + startQueryDestinationFolders(); // 查询目标文件夹列表(用于移动笔记) + break; + default: + return false; + } + return true; + } + } + + /** + * 新建笔记按钮的触摸事件监听器,处理透明区域点击穿透到列表的逻辑 + */ + 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; // 按钮在屏幕中的起始Y坐标 + int eventY = start + (int) event.getY(); // 转换为屏幕坐标 + + // 子文件夹状态下,减去标题栏高度修正坐标 + if (mState == ListEditState.SUB_FOLDER) { + eventY -= mTitleBar.getHeight(); + start -= mTitleBar.getHeight(); + } + + /** + * 特殊处理:新建按钮的透明区域点击需要穿透到下方列表 + * 透明区域由公式 y = -0.12x + 94 界定(基于按钮局部坐标) + * 若点击位置在透明区域内,则将事件分发给ListView + */ + if (event.getY() < (event.getX() * (-0.12) + 94)) { + // 获取列表最后一个可见项 + View view = mNotesListView.getChildAt(mNotesListView.getChildCount() - 1 + - mNotesListView.getFooterViewsCount()); + // 检查点击位置是否在列表项范围内 + if (view != null && view.getBottom() > start + && (view.getTop() < (start + 94))) { + mOriginY = (int) event.getY(); + mDispatchY = eventY; + // 修正事件坐标为列表坐标系 + event.setLocation(event.getX(), mDispatchY); + mDispatch = true; // 标记需要分发事件 + return mNotesListView.dispatchTouchEvent(event); // 分发事件到列表 + } + } + break; + } + case MotionEvent.ACTION_MOVE: { + // 移动时持续分发事件 + if (mDispatch) { + mDispatchY += (int) event.getY() - mOriginY; + event.setLocation(event.getX(), mDispatchY); + return mNotesListView.dispatchTouchEvent(event); + } + break; + } + default: { + // 事件结束时分发最后一次事件并重置标记 + if (mDispatch) { + event.setLocation(event.getX(), mDispatchY); + mDispatch = false; + return mNotesListView.dispatchTouchEvent(event); + } + break; + } + } + return false; + } + + }; + + /** + * 启动异步查询加载笔记列表数据 + */ + private void startAsyncNotesListQuery() { + // 根据当前文件夹ID选择查询条件(根目录或普通文件夹) + String selection = (mCurrentFolderId == Notes.ID_ROOT_FOLDER) ? ROOT_FOLDER_SELECTION + : NORMAL_SELECTION; + // 发起异步查询 + mBackgroundQueryHandler.startQuery(FOLDER_NOTE_LIST_QUERY_TOKEN, null, + Notes.CONTENT_NOTE_URI, NoteItemData.PROJECTION, selection, new String[] { + String.valueOf(mCurrentFolderId) + }, NoteColumns.TYPE + " DESC," + NoteColumns.MODIFIED_DATE + " DESC"); + } + + /** + * 异步查询处理器,继承自AsyncQueryHandler,处理ContentProvider查询 + */ + private final class BackgroundQueryHandler extends AsyncQueryHandler { + public BackgroundQueryHandler(ContentResolver contentResolver) { + super(contentResolver); + } + + /** + * 查询完成时回调 + */ + @Override + protected void onQueryComplete(int token, Object cookie, Cursor cursor) { + switch (token) { + case FOLDER_NOTE_LIST_QUERY_TOKEN: + // 笔记列表查询完成,更新适配器数据 + mNotesListAdapter.changeCursor(cursor); + break; + case FOLDER_LIST_QUERY_TOKEN: + // 文件夹列表查询完成,显示文件夹选择菜单 + if (cursor != null && cursor.getCount() > 0) { + showFolderListMenu(cursor); + } else { + Log.e(TAG, "Query folder failed"); + } + break; + default: + return; + } + } + } + + /** + * 显示文件夹列表菜单(用于移动笔记时选择目标文件夹) + */ + private void showFolderListMenu(Cursor cursor) { + AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); + builder.setTitle(R.string.menu_title_select_folder); + final FoldersListAdapter adapter = new FoldersListAdapter(this, cursor); + // 设置适配器并处理选择事件 + builder.setAdapter(adapter, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + // 批量移动笔记到选中文件夹 + DataUtils.batchMoveToFolder(mContentResolver, + mNotesListAdapter.getSelectedItemIds(), adapter.getItemId(which)); + // 显示移动成功提示 + Toast.makeText( + NotesListActivity.this, + getString(R.string.format_move_notes_to_folder, + mNotesListAdapter.getSelectedCount(), + adapter.getFolderName(NotesListActivity.this, which)), + Toast.LENGTH_SHORT).show(); + mModeCallBack.finishActionMode(); // 结束多选模式 + } + }); + builder.show(); + } + + /** + * 新建笔记,跳转到编辑界面 + */ + private void createNewNote() { + Intent intent = new Intent(this, NoteEditActivity.class); + intent.setAction(Intent.ACTION_INSERT_OR_EDIT); + intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mCurrentFolderId); // 传递当前文件夹ID + this.startActivityForResult(intent, REQUEST_CODE_NEW_NODE); + } + + /** + * 批量删除笔记 + */ + private void batchDelete() { + new AsyncTask>() { + protected HashSet doInBackground(Void... unused) { + // 获取选中项关联的 widget 信息 + HashSet widgets = mNotesListAdapter.getSelectedWidget(); + if (!isSyncMode()) { + // 非同步模式:直接删除笔记 + if (DataUtils.batchDeleteNotes(mContentResolver, mNotesListAdapter + .getSelectedItemIds())) { + } else { + Log.e(TAG, "Delete notes error, should not happens"); + } + } else { + // 同步模式:将笔记移动到回收站 + if (!DataUtils.batchMoveToFolder(mContentResolver, mNotesListAdapter + .getSelectedItemIds(), Notes.ID_TRASH_FOLER)) { + Log.e(TAG, "Move notes to trash folder error, should not happens"); + } + } + return widgets; + } + + @Override + protected void onPostExecute(HashSet widgets) { + // 批量删除操作执行完成后回调 + if (widgets != null) { + // 遍历相关小部件并更新 + for (AppWidgetAttribute widget : widgets) { + // 校验小部件ID和类型有效性 + if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID + && widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) { + updateWidget(widget.widgetId, widget.widgetType); + } + } + } + // 结束动作模式(如批量选择模式) + 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); + return; + } + + // 构建要删除的文件夹ID集合 + HashSet ids = new HashSet(); + ids.add(folderId); + // 获取该文件夹关联的小部件信息 + HashSet widgets = DataUtils.getFolderNoteWidget(mContentResolver, + folderId); + + if (!isSyncMode()) { + // 非同步模式下直接删除文件夹 + DataUtils.batchDeleteNotes(mContentResolver, ids); + } else { + // 同步模式下将文件夹移到回收站 + 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) { + updateWidget(widget.widgetId, widget.widgetType); + } + } + } + } + + /** + * 打开笔记进行查看/编辑 + * @param data 笔记数据对象 + */ + private void openNode(NoteItemData data) { + Intent intent = new Intent(this, NoteEditActivity.class); + intent.setAction(Intent.ACTION_VIEW); + intent.putExtra(Intent.EXTRA_UID, data.getId()); + this.startActivityForResult(intent, REQUEST_CODE_OPEN_NODE); + } + + /** + * 打开文件夹,显示文件夹内的笔记 + * @param data 文件夹数据对象 + */ + private void openFolder(NoteItemData data) { + mCurrentFolderId = data.getId(); + // 异步查询文件夹内的笔记列表 + 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 { + mTitleBar.setText(data.getSnippet()); + } + mTitleBar.setVisibility(View.VISIBLE); + } + + /** + * 点击事件处理 + */ + public void onClick(View v) { + switch (v.getId()) { + case R.id.btn_new_note: + // 点击新建笔记按钮 + createNewNote(); + break; + default: + break; + } + } + + /** + * 显示软键盘 + */ + private void showSoftInput() { + InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); + if (inputMethodManager != null) { + inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); + } + } + + /** + * 隐藏软键盘 + * @param view 触发隐藏的视图 + */ + private void hideSoftInput(View view) { + InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); + inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0); + } + + /** + * 显示创建或修改文件夹的对话框 + * @param create true-创建文件夹,false-修改文件夹 + */ + 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(); // 显示软键盘 + + // 根据操作类型(创建/修改)初始化对话框 + if (!create) { + // 修改文件夹:设置当前文件夹名称 + if (mFocusNoteDataItem != null) { + etName.setText(mFocusNoteDataItem.getSnippet()); + builder.setTitle(getString(R.string.menu_folder_change_name)); + } else { + Log.e(TAG, "The long click data item is null"); + return; + } + } else { + // 创建文件夹:清空输入框 + etName.setText(""); + builder.setTitle(this.getString(R.string.menu_create_folder)); + } + + 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); // 取消时隐藏软键盘 + } + }); + + final Dialog dialog = builder.setView(view).show(); + final Button positive = (Button)dialog.findViewById(android.R.id.button1); + positive.setOnClickListener(new OnClickListener() { + public void onClick(View v) { + 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(); + values.put(NoteColumns.SNIPPET, name); + values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); + values.put(NoteColumns.LOCAL_MODIFIED, 1); // 标记为本地已修改 + mContentResolver.update(Notes.CONTENT_NOTE_URI, values, NoteColumns.ID + + "=?", new String[] { + String.valueOf(mFocusNoteDataItem.getId()) + }); + } + } else if (!TextUtils.isEmpty(name)) { + // 创建新文件夹 + ContentValues values = new ContentValues(); + values.put(NoteColumns.SNIPPET, name); + values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); + mContentResolver.insert(Notes.CONTENT_NOTE_URI, values); + } + dialog.dismiss(); + } + }); + + // 初始状态:输入框为空时禁用确定按钮 + if (TextUtils.isEmpty(etName.getText())) { + positive.setEnabled(false); + } + + // 监听输入框文本变化,控制确定按钮状态 + etName.addTextChangedListener(new TextWatcher() { + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + // 文本变化前回调(未实现) + } + + public void onTextChanged(CharSequence s, int start, int before, int count) { + // 文本变化时:为空则禁用按钮,否则启用 + if (TextUtils.isEmpty(etName.getText())) { + positive.setEnabled(false); + } else { + positive.setEnabled(true); + } + } + + public void afterTextChanged(Editable s) { + // 文本变化后回调(未实现) + } + }); + } + + /** + * 处理返回键事件 + */ + @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); // 显示新建笔记按钮 + mTitleBar.setVisibility(View.GONE); + startAsyncNotesListQuery(); // 重新查询数据 + break; + case NOTE_LIST: + // 根目录下直接返回 + 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) { + intent.setClass(this, NoteWidgetProvider_4x.class); + } else { + Log.e(TAG, "Unspported widget type"); + return; + } + + intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { + appWidgetId + }); + + sendBroadcast(intent); // 发送广播更新小部件 + setResult(RESULT_OK, intent); + } + + /** + * 文件夹长按菜单创建监听器 + */ + private final OnCreateContextMenuListener mFolderOnCreateContextMenuListener = new OnCreateContextMenuListener() { + public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { + if (mFocusNoteDataItem != null) { + menu.setHeaderTitle(mFocusNoteDataItem.getSnippet()); // 菜单标题设为文件夹名称 + // 添加菜单选项 + menu.add(0, MENU_FOLDER_VIEW, 0, R.string.menu_folder_view); // 查看 + menu.add(0, MENU_FOLDER_DELETE, 0, R.string.menu_folder_delete); // 删除 + menu.add(0, MENU_FOLDER_CHANGE_NAME, 0, R.string.menu_folder_change_name); // 重命名 + } + } + }; + + /** + * 上下文菜单关闭时回调 + */ + @Override + public void onContextMenuClosed(Menu menu) { + if (mNotesListView != null) { + // 清除列表的上下文菜单监听器,避免重复触发 + mNotesListView.setOnCreateContextMenuListener(null); + } + super.onContextMenuClosed(menu); + } + + /** + * 上下文菜单项选择事件处理 + */ + @Override + public boolean onContextItemSelected(MenuItem item) { + if (mFocusNoteDataItem == null) { + Log.e(TAG, "The long click data item is null"); + return false; + } + switch (item.getItemId()) { + case MENU_FOLDER_VIEW: + // 查看文件夹 + 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); + builder.setMessage(getString(R.string.alert_message_delete_folder)); + builder.setPositiveButton(android.R.string.ok, + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + deleteFolder(mFocusNoteDataItem.getId()); // 确认删除文件夹 + } + }); + builder.setNegativeButton(android.R.string.cancel, null); + builder.show(); + break; + case MENU_FOLDER_CHANGE_NAME: + // 修改文件夹名称 + showCreateOrModifyFolderDialog(false); + break; + default: + break; + } + + return true; + } + + /** + * 准备选项菜单(根据当前状态动态调整菜单) + */ + @Override + public boolean onPrepareOptionsMenu(Menu menu) { + menu.clear(); // 清空现有菜单 + // 根据当前界面状态加载对应的菜单资源 + if (mState == ListEditState.NOTE_LIST) { + getMenuInflater().inflate(R.menu.note_list, menu); + // 根据同步状态更新同步菜单的文本 + menu.findItem(R.id.menu_sync).setTitle( + GTaskSyncService.isSyncing() ? R.string.menu_sync_cancel : R.string.menu_sync); + } else if (mState == ListEditState.SUB_FOLDER) { + getMenuInflater().inflate(R.menu.sub_folder, menu); + } else if (mState == ListEditState.CALL_RECORD_FOLDER) { + getMenuInflater().inflate(R.menu.call_record_folder, menu); + } else { + Log.e(TAG, "Wrong state:" + mState); + } + return true; + } + + /** + * 选项菜单项选择事件处理 + */ + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case R.id.menu_new_folder: { + // 新建文件夹 + showCreateOrModifyFolderDialog(true); + break; + } + case R.id.menu_export_text: { + // 导出笔记为文本 + exportNoteToText(); + break; + } + case R.id.menu_sync: { + // 同步相关操作 + if (isSyncMode()) { + // 已开启同步模式:根据菜单文本判断是开始还是取消同步 + if (TextUtils.equals(item.getTitle(), getString(R.string.menu_sync))) { // 开始同步 + GTaskSyncService.startSync(this); + } else { + // 取消同步 + GTaskSyncService.cancelSync(this); + } + } else { + // 未开启同步模式:跳转到设置页面 + startPreferenceActivity(); + } + break; + } + case R.id.menu_setting: { + // 跳转到设置页面 + startPreferenceActivity(); + break; + } + case R.id.menu_new_note: { + // 新建笔记 + createNewNote(); + break; + } + case R.id.menu_search: + // 触发搜索功能 + onSearchRequested(); + break; + default: + break; + } + return true; + } + + /** + * 处理搜索请求 + */ + @Override + public boolean onSearchRequested() { + // 启动搜索功能,参数分别为:搜索内容、是否显示搜索框、额外数据、是否全局搜索 + startSearch(null, false, null /* appData */, false); + return true; + } + + /** + * 将笔记导出为文本文件 + */ + private void exportNoteToText() { + // 获取备份工具实例 + final BackupUtils backup = BackupUtils.getInstance(NotesListActivity.this); + // 异步执行导出操作 + new AsyncTask() { + + @Override + protected Integer doInBackground(Void... unused) { + // 后台执行导出逻辑 + return backup.exportToText(); + } + + @Override + protected void onPostExecute(Integer result) { + // 导出完成后根据结果显示对应对话框 + if (result == BackupUtils.STATE_SD_CARD_UNMOUONTED) { + // SD卡未挂载 + AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); + builder.setTitle(NotesListActivity.this + .getString(R.string.failed_sdcard_export)); + builder.setMessage(NotesListActivity.this + .getString(R.string.error_sdcard_unmounted)); + builder.setPositiveButton(android.R.string.ok, null); + builder.show(); + } else if (result == BackupUtils.STATE_SUCCESS) { + // 导出成功 + AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); + builder.setTitle(NotesListActivity.this + .getString(R.string.success_sdcard_export)); + builder.setMessage(NotesListActivity.this.getString( + R.string.format_exported_file_location, backup + .getExportedTextFileName(), backup.getExportedTextFileDir())); + builder.setPositiveButton(android.R.string.ok, null); + builder.show(); + } else if (result == BackupUtils.STATE_SYSTEM_ERROR) { + // 系统错误导致导出失败 + AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); + builder.setTitle(NotesListActivity.this + .getString(R.string.failed_sdcard_export)); + builder.setMessage(NotesListActivity.this + .getString(R.string.error_sdcard_export)); + builder.setPositiveButton(android.R.string.ok, null); + builder.show(); + } + } + + }.execute(); + } + + /** + * 判断是否处于同步模式(已设置同步账户) + * @return true-同步模式,false-非同步模式 + */ + private boolean isSyncMode() { + return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; + } + + /** + * 启动设置页面 + */ + private void startPreferenceActivity() { + // 确定启动上下文(父Activity或当前Activity) + 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(); + // 通知动作模式回调更新选择状态 + mModeCallBack.onItemCheckedStateChanged(null, position, id, + !mNotesListAdapter.isSelectedItem(position)); + } + return; + } + + // 根据当前界面状态处理点击 + switch (mState) { + case NOTE_LIST: + // 根目录下:点击文件夹则打开文件夹,点击笔记则打开笔记 + if (item.getType() == Notes.TYPE_FOLDER + || item.getType() == Notes.TYPE_SYSTEM) { + openFolder(item); + } else if (item.getType() == Notes.TYPE_NOTE) { + openNode(item); + } else { + Log.e(TAG, "Wrong note type in NOTE_LIST"); + } + break; + case SUB_FOLDER: + case CALL_RECORD_FOLDER: + // 子文件夹或通话记录文件夹下:点击笔记则打开笔记 + if (item.getType() == Notes.TYPE_NOTE) { + openNode(item); + } else { + Log.e(TAG, "Wrong note type in SUB_FOLDER"); + } + break; + default: + break; + } + } + } + + } + + /** + * 异步查询目标文件夹列表(用于移动笔记等操作) + */ + 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, + FoldersListAdapter.PROJECTION, + selection, + new String[] { + String.valueOf(Notes.TYPE_FOLDER), + String.valueOf(Notes.ID_TRASH_FOLER), + String.valueOf(mCurrentFolderId) + }, + 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); + } else { + 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/ui/NotesListAdapter.java b/src/ui/NotesListAdapter.java new file mode 100644 index 0000000..6ab7b8e --- /dev/null +++ b/src/ui/NotesListAdapter.java @@ -0,0 +1,259 @@ +/* + * 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. + */ + +package net.micode.notes.ui; + +import android.content.Context; +import android.database.Cursor; +import android.util.Log; +import android.view.View; +import android.view.ViewGroup; +import android.widget.CursorAdapter; + +import net.micode.notes.data.Notes; + +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; + + +/** + * 便签列表适配器,用于将便签数据与列表视图绑定,支持多选操作 + * 继承自CursorAdapter,通过Cursor获取数据库中的便签数据 + */ +public class NotesListAdapter extends CursorAdapter { + private static final String TAG = "NotesListAdapter"; + private Context mContext; // 上下文对象 + private HashMap mSelectedIndex; // 存储选中项的位置和状态 + private int mNotesCount; // 便签总数(不包含文件夹) + private boolean mChoiceMode; // 是否处于选择模式 + + /** + * 桌面插件属性封装类 + * 用于存储选中项中包含的桌面插件信息 + */ + public static class AppWidgetAttribute { + public int widgetId; // 插件ID + public int widgetType; // 插件类型 + }; + + /** + * 构造方法 + * @param context 上下文对象 + */ + public NotesListAdapter(Context context) { + super(context, null); + mSelectedIndex = new HashMap(); + mContext = context; + mNotesCount = 0; + } + + /** + * 创建新的列表项视图 + * @param context 上下文 + * @param cursor 数据游标 + * @param parent 父容器 + * @return 新创建的NotesListItem视图 + */ + @Override + public View newView(Context context, Cursor cursor, ViewGroup parent) { + return new NotesListItem(context); + } + + /** + * 绑定数据到列表项视图 + * @param view 列表项视图 + * @param context 上下文 + * @param cursor 数据游标 + */ + @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())); + } + } + + /** + * 设置指定位置的选中状态 + * @param position 列表项位置 + * @param checked 是否选中 + */ + public void setCheckedItem(final int position, final boolean checked) { + mSelectedIndex.put(position, checked); + notifyDataSetChanged(); // 通知列表刷新 + } + + /** + * 判断是否处于选择模式 + * @return 是否为选择模式 + */ + public boolean isInChoiceMode() { + return mChoiceMode; + } + + /** + * 设置选择模式 + * @param mode 选择模式开关 + */ + public void setChoiceMode(boolean mode) { + mSelectedIndex.clear(); // 清除选中状态 + mChoiceMode = mode; + } + + /** + * 全选或取消全选所有便签(仅对普通便签有效) + * @param checked 是否选中 + */ + 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); + } + } + } + } + + /** + * 获取所有选中项的ID集合 + * @return 选中项ID的HashSet + */ + public HashSet getSelectedItemIds() { + HashSet itemSet = new HashSet(); + for (Integer position : mSelectedIndex.keySet()) { + if (mSelectedIndex.get(position) == true) { + Long id = getItemId(position); + // 过滤根文件夹ID(不应被选中) + if (id == Notes.ID_ROOT_FOLDER) { + Log.d(TAG, "Wrong item id, should not happen"); + } else { + itemSet.add(id); + } + } + } + return itemSet; + } + + /** + * 获取所有选中项中的桌面插件属性 + * @return 插件属性的HashSet + */ + public HashSet getSelectedWidget() { + HashSet itemSet = new HashSet(); + for (Integer position : mSelectedIndex.keySet()) { + if (mSelectedIndex.get(position) == true) { + Cursor c = (Cursor) getItem(position); + if (c != null) { + AppWidgetAttribute widget = new AppWidgetAttribute(); + NoteItemData item = new NoteItemData(mContext, c); + widget.widgetId = item.getWidgetId(); + widget.widgetType = item.getWidgetType(); + itemSet.add(widget); + // 注意:此处不关闭游标,游标由适配器管理 + } else { + Log.e(TAG, "Invalid cursor"); + return null; + } + } + } + return itemSet; + } + + /** + * 获取选中项的数量 + * @return 选中项数量 + */ + public int getSelectedCount() { + Collection values = mSelectedIndex.values(); + if (null == values) { + return 0; + } + Iterator iter = values.iterator(); + int count = 0; + while (iter.hasNext()) { + if (true == iter.next()) { + count++; + } + } + return count; + } + + /** + * 判断是否所有便签都被选中 + * @return 是否全选 + */ + public boolean isAllSelected() { + int checkedCount = getSelectedCount(); + return (checkedCount != 0 && checkedCount == mNotesCount); + } + + /** + * 判断指定位置的项是否被选中 + * @param position 列表项位置 + * @return 是否选中 + */ + public boolean isSelectedItem(final int position) { + if (null == mSelectedIndex.get(position)) { + return false; + } + return mSelectedIndex.get(position); + } + + /** + * 当数据发生变化时回调,重新计算便签数量 + */ + @Override + protected void onContentChanged() { + super.onContentChanged(); + calcNotesCount(); + } + + /** + * 更换游标时回调,重新计算便签数量 + * @param cursor 新游标 + */ + @Override + public void changeCursor(Cursor cursor) { + super.changeCursor(cursor); + calcNotesCount(); + } + + /** + * 计算普通便签的总数(排除文件夹) + */ + private void calcNotesCount() { + mNotesCount = 0; + for (int i = 0; i < getCount(); i++) { + Cursor c = (Cursor) getItem(i); + if (c != null) { + // 仅统计类型为普通便签的项 + if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) { + mNotesCount++; + } + } else { + Log.e(TAG, "Invalid cursor"); + return; + } + } + } +} \ No newline at end of file diff --git a/src/ui/NotesListItem.java b/src/ui/NotesListItem.java new file mode 100644 index 0000000..e3fd735 --- /dev/null +++ b/src/ui/NotesListItem.java @@ -0,0 +1,169 @@ +/* + * 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. + */ + +package net.micode.notes.ui; + +import android.content.Context; +import android.text.format.DateUtils; +import android.view.View; +import android.widget.CheckBox; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.TextView; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.tool.DataUtils; +import net.micode.notes.tool.ResourceParser.NoteItemBgResources; + + +/** + * 小米便签列表中的单个项视图 + * 负责展示便签、文件夹或通话记录的内容及状态,支持多选模式 + */ +public class NotesListItem extends LinearLayout { + private ImageView mAlert; // 提醒图标(显示闹钟或通话记录图标) + private TextView mTitle; // 标题/内容文本(显示便签内容、文件夹名称等) + private TextView mTime; // 时间文本(显示最后修改时间) + private TextView mCallName; // 通话记录联系人名称(仅通话记录便签显示) + private NoteItemData mItemData; // 当前项对应的数据模型 + private CheckBox mCheckBox; // 多选模式下的复选框 + + /** + * 构造方法:初始化布局和控件 + * @param context 上下文对象 + */ + public NotesListItem(Context context) { + super(context); + // 加载列表项布局文件 + inflate(context, R.layout.note_item, this); + // 绑定UI控件 + mAlert = (ImageView) findViewById(R.id.iv_alert_icon); + mTitle = (TextView) findViewById(R.id.tv_title); + mTime = (TextView) findViewById(R.id.tv_time); + mCallName = (TextView) findViewById(R.id.tv_name); + mCheckBox = (CheckBox) findViewById(android.R.id.checkbox); + } + + /** + * 绑定数据到当前列表项,根据数据类型和模式展示不同样式 + * @param context 上下文对象 + * @param data 便签数据模型 + * @param choiceMode 是否处于多选模式 + * @param checked 多选模式下是否被选中 + */ + 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); + } else { + mCheckBox.setVisibility(View.GONE); + } + + mItemData = data; + + // 处理通话记录文件夹(特殊系统文件夹) + if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { + mCallName.setVisibility(View.GONE); + mAlert.setVisibility(View.VISIBLE); + mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); + // 显示文件夹名称和包含的便签数量 + mTitle.setText(context.getString(R.string.call_record_folder_name) + + 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); + mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); // 显示便签内容片段 + // 显示提醒图标(如有) + if (data.hasAlert()) { + mAlert.setImageResource(R.drawable.clock); + mAlert.setVisibility(View.VISIBLE); + } else { + mAlert.setVisibility(View.GONE); + } + + // 处理普通文件夹和普通便签 + } else { + mCallName.setVisibility(View.GONE); + 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); + mAlert.setVisibility(View.VISIBLE); + } else { + mAlert.setVisibility(View.GONE); + } + } + } + + // 显示最后修改时间(相对时间格式,如"1小时前") + mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate())); + + // 设置项背景样式 + setBackground(data); + } + + /** + * 根据便签类型和位置设置背景样式 + * @param data 便签数据模型 + */ + private void setBackground(NoteItemData data) { + int bgColorId = data.getBgColorId(); // 获取背景色ID + + // 普通便签:根据位置(首项/末项/单项等)设置不同背景 + if (data.getType() == Notes.TYPE_NOTE) { + if (data.isSingle() || data.isOneFollowingFolder()) { + // 单项或文件夹后的唯一便签 + setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(bgColorId)); + } else if (data.isLast()) { + // 列表中的最后一项 + setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(bgColorId)); + } else if (data.isFirst() || data.isMultiFollowingFolder()) { + // 首项或文件夹后的多个便签中的第一项 + setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(bgColorId)); + } else { + // 中间项 + setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(bgColorId)); + } + } else { + // 文件夹:使用固定的文件夹背景 + setBackgroundResource(NoteItemBgResources.getFolderBgRes()); + } + } + + /** + * 获取当前项的数据模型 + * @return 便签数据模型 + */ + public NoteItemData getItemData() { + return mItemData; + } +} \ No newline at end of file diff --git a/src/ui/NotesPreferenceActivity.java b/src/ui/NotesPreferenceActivity.java new file mode 100644 index 0000000..a5761bb --- /dev/null +++ b/src/ui/NotesPreferenceActivity.java @@ -0,0 +1,463 @@ +/* + * 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. + */ + +package net.micode.notes.ui; + +import android.accounts.Account; +import android.accounts.AccountManager; +import android.app.ActionBar; +import android.app.AlertDialog; +import android.content.BroadcastReceiver; +import android.content.ContentValues; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.preference.Preference; +import android.preference.Preference.OnPreferenceClickListener; +import android.preference.PreferenceActivity; +import android.preference.PreferenceCategory; +import android.text.TextUtils; +import android.text.format.DateFormat; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.Button; +import android.widget.TextView; +import android.widget.Toast; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.gtask.remote.GTaskSyncService; + + +/** + * 小米便签的设置页面 + * 负责账号管理、同步控制及偏好设置,支持便签数据同步功能 + */ +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; + + @Override + protected void onCreate(Bundle icicle) { + super.onCreate(icicle); + + // 设置ActionBar支持返回导航 + getActionBar().setDisplayHomeAsUpEnabled(true); + + // 加载偏好设置布局 + addPreferencesFromResource(R.xml.preferences); + // 获取账号设置分类 + mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY); + // 初始化广播接收器并注册,监听同步服务广播 + mReceiver = new GTaskReceiver(); + 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); + } + + @Override + protected void onResume() { + super.onResume(); + + // 如果检测到新添加的账号,自动设置为同步账号 + if (mHasAddedAccount) { + Account[] accounts = getGoogleAccounts(); + if (mOriAccounts != null && accounts.length > mOriAccounts.length) { + for (Account accountNew : accounts) { + boolean found = false; + for (Account accountOld : mOriAccounts) { + if (TextUtils.equals(accountOld.name, accountNew.name)) { + found = true; + break; + } + } + if (!found) { + setSyncAccount(accountNew.name); + break; + } + } + } + } + + // 刷新UI显示 + refreshUI(); + } + + @Override + protected void onDestroy() { + // 注销广播接收器 + if (mReceiver != null) { + unregisterReceiver(mReceiver); + } + super.onDestroy(); + } + + /** + * 加载账号设置项到偏好页面 + */ + private void loadAccountPreference() { + mAccountCategory.removeAll(); + + Preference accountPref = new Preference(this); + final String defaultAccount = getSyncAccountName(this); + accountPref.setTitle(getString(R.string.preferences_account_title)); + accountPref.setSummary(getString(R.string.preferences_account_summary)); + // 设置账号项点击事件 + accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() { + public boolean onPreferenceClick(Preference preference) { + if (!GTaskSyncService.isSyncing()) { + if (TextUtils.isEmpty(defaultAccount)) { + // 首次设置账号,显示账号选择对话框 + showSelectAccountAlertDialog(); + } else { + // 已设置账号,显示账号变更确认对话框 + showChangeAccountConfirmAlertDialog(); + } + } else { + // 同步中不允许变更账号 + Toast.makeText(NotesPreferenceActivity.this, + R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT) + .show(); + } + return true; + } + }); + + 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); + + // 设置同步按钮状态 + if (GTaskSyncService.isSyncing()) { + syncButton.setText(getString(R.string.preferences_button_sync_cancel)); + syncButton.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) { + // 取消同步 + GTaskSyncService.cancelSync(NotesPreferenceActivity.this); + } + }); + } else { + syncButton.setText(getString(R.string.preferences_button_sync_immediately)); + syncButton.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) { + // 立即同步 + GTaskSyncService.startSync(NotesPreferenceActivity.this); + } + }); + } + // 未设置账号时禁用同步按钮 + syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this))); + + // 设置最后同步时间显示 + if (GTaskSyncService.isSyncing()) { + lastSyncTimeView.setText(GTaskSyncService.getProgressString()); + lastSyncTimeView.setVisibility(View.VISIBLE); + } else { + long lastSyncTime = getLastSyncTime(this); + if (lastSyncTime != 0) { + lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time, + DateFormat.format(getString(R.string.preferences_last_sync_time_format), + lastSyncTime))); + lastSyncTimeView.setVisibility(View.VISIBLE); + } else { + lastSyncTimeView.setVisibility(View.GONE); + } + } + } + + /** + * 刷新整个UI界面 + */ + private void refreshUI() { + loadAccountPreference(); + loadSyncButton(); + } + + /** + * 显示账号选择对话框 + */ + 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)); + TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle); + subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips)); + dialogBuilder.setCustomTitle(titleView); + dialogBuilder.setPositiveButton(null, null); + + // 获取谷歌账号列表 + Account[] accounts = getGoogleAccounts(); + String defAccount = getSyncAccountName(this); + + mOriAccounts = accounts; + mHasAddedAccount = false; + + if (accounts.length > 0) { + CharSequence[] items = new CharSequence[accounts.length]; + final CharSequence[] itemMapping = items; + int checkedItem = -1; + int index = 0; + // 构建账号选择列表 + for (Account account : accounts) { + if (TextUtils.equals(account.name, defAccount)) { + checkedItem = index; + } + items[index++] = account.name; + } + // 设置单选列表点击事件 + dialogBuilder.setSingleChoiceItems(items, checkedItem, + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + setSyncAccount(itemMapping[which].toString()); + dialog.dismiss(); + refreshUI(); + } + }); + } + + // 添加"添加账号"选项 + View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null); + dialogBuilder.setView(addAccountView); + + final AlertDialog dialog = dialogBuilder.show(); + 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" + }); + startActivityForResult(intent, -1); + dialog.dismiss(); + } + }); + } + + /** + * 显示账号变更确认对话框 + */ + 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, + getSyncAccountName(this))); + TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle); + 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), + getString(R.string.preferences_menu_cancel) + }; + dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + if (which == 0) { + // 变更账号:显示账号选择对话框 + showSelectAccountAlertDialog(); + } else if (which == 1) { + // 移除账号 + removeSyncAccount(); + refreshUI(); + } + } + }); + dialogBuilder.show(); + } + + /** + * 获取设备上的谷歌账号列表 + * @return 谷歌账号数组 + */ + private Account[] getGoogleAccounts() { + AccountManager accountManager = AccountManager.get(this); + return accountManager.getAccountsByType("com.google"); + } + + /** + * 设置同步账号并更新本地数据 + * @param account 账号名称 + */ + 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) { + editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account); + } else { + editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); + } + editor.commit(); + + // 清除最后同步时间 + setLastSyncTime(this, 0); + + // 清除本地GTASK相关信息(异步执行) + new Thread(new Runnable() { + public void run() { + ContentValues values = new ContentValues(); + values.put(NoteColumns.GTASK_ID, ""); + values.put(NoteColumns.SYNC_ID, 0); + getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null); + } + }).start(); + + Toast.makeText(NotesPreferenceActivity.this, + getString(R.string.preferences_toast_success_set_accout, account), + Toast.LENGTH_SHORT).show(); + } + } + + /** + * 移除当前同步账号并清理数据 + */ + private void removeSyncAccount() { + SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); + SharedPreferences.Editor editor = settings.edit(); + if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) { + editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME); + } + if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) { + editor.remove(PREFERENCE_LAST_SYNC_TIME); + } + editor.commit(); + + // 清除本地GTASK相关信息(异步执行) + new Thread(new Runnable() { + public void run() { + ContentValues values = new ContentValues(); + values.put(NoteColumns.GTASK_ID, ""); + values.put(NoteColumns.SYNC_ID, 0); + getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null); + } + }).start(); + } + + /** + * 获取保存的同步账号名称 + * @param context 上下文 + * @return 账号名称,为空表示未设置 + */ + public static String getSyncAccountName(Context context) { + SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, + Context.MODE_PRIVATE); + return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); + } + + /** + * 保存最后同步时间 + * @param context 上下文 + * @param time 时间戳 + */ + public static void setLastSyncTime(Context context, long time) { + SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, + Context.MODE_PRIVATE); + SharedPreferences.Editor editor = settings.edit(); + editor.putLong(PREFERENCE_LAST_SYNC_TIME, time); + editor.commit(); + } + + /** + * 获取最后同步时间 + * @param context 上下文 + * @return 时间戳,0表示从未同步过 + */ + public static long getLastSyncTime(Context context) { + SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, + Context.MODE_PRIVATE); + return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0); + } + + /** + * 监听同步服务广播的接收器 + * 用于同步过程中更新UI状态 + */ + private class GTaskReceiver extends BroadcastReceiver { + + @Override + public void onReceive(Context context, Intent intent) { + // 刷新UI显示同步状态 + refreshUI(); + if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) { + TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview); + syncStatus.setText(intent + .getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG)); + } + + } + } + + /** + * 处理菜单选项点击事件 + */ + 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); + return true; + default: + return false; + } + } +} \ No newline at end of file diff --git a/src/widget/NoteWidgetProvider.java b/src/widget/NoteWidgetProvider.java new file mode 100644 index 0000000..e953109 --- /dev/null +++ b/src/widget/NoteWidgetProvider.java @@ -0,0 +1,187 @@ +/* + * 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. + */ + +package net.micode.notes.widget; +import android.app.PendingIntent; +import android.appwidget.AppWidgetManager; +import android.appwidget.AppWidgetProvider; +import android.content.ContentValues; +import android.content.Context; +import android.content.Intent; +import android.database.Cursor; +import android.util.Log; +import android.widget.RemoteViews; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; +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, // 便签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"; + + /** + * 当小部件被删除时调用 + * 清除数据库中与该小部件关联的记录 + */ + @Override + public void onDeleted(Context context, int[] appWidgetIds) { + ContentValues values = new ContentValues(); + // 将小部件ID设为无效值 + values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); + for (int i = 0; i < appWidgetIds.length; i++) { + // 更新数据库中关联该小部件的便签记录 + context.getContentResolver().update(Notes.CONTENT_NOTE_URI, + values, + NoteColumns.WIDGET_ID + "=?", + new String[] { String.valueOf(appWidgetIds[i])}); + } + } + + /** + * 获取与指定小部件关联的便签信息 + * @param context 上下文 + * @param widgetId 小部件ID + * @return 包含便签信息的游标 + */ + private Cursor getNoteWidgetInfo(Context context, int widgetId) { + return context.getContentResolver().query(Notes.CONTENT_NOTE_URI, + PROJECTION, + // 查询条件:小部件ID匹配且不在回收站中 + NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>?", + new String[] { String.valueOf(widgetId), String.valueOf(Notes.ID_TRASH_FOLER) }, + null); + } + + /** + * 公开的更新方法,调用带隐私模式参数的私有更新方法 + */ + protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { + update(context, appWidgetManager, appWidgetIds, false); + } + + /** + * 核心更新方法,更新小部件的UI显示 + * @param context 上下文 + * @param appWidgetManager 小部件管理器 + * @param appWidgetIds 需要更新的小部件ID数组 + * @param privacyMode 是否隐私模式(隐藏内容) + */ + private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds, + boolean privacyMode) { + for (int i = 0; i < appWidgetIds.length; i++) { + // 只处理有效的小部件ID + if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) { + // 默认背景颜色ID + int bgId = ResourceParser.getDefaultBgId(context); + // 便签内容摘要 + String snippet = ""; + // 点击小部件时的跳转意图 + 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()) { + // 检查是否有多个便签关联到同一小部件(异常情况) + if (c.getCount() > 1) { + Log.e(TAG, "Multiple message with same widget id:" + appWidgetIds[i]); + c.close(); + return; + } + // 从游标中获取数据 + 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); // 新建便签 + } + + // 关闭游标释放资源 + if (c != null) { + c.close(); + } + + // 加载小部件布局 + RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId()); + // 设置背景图片 + rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId)); + intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId); + + // 创建点击事件的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 + * 由子类实现不同尺寸小部件的背景资源 + */ + protected abstract int getBgResourceId(int bgId); + + /** + * 抽象方法:获取布局ID + * 由子类实现不同尺寸小部件的布局文件 + */ + protected abstract int getLayoutId(); + + /** + * 抽象方法:获取小部件类型 + * 由子类定义具体的小部件类型(如2x、4x等) + */ + protected abstract int getWidgetType(); +} \ No newline at end of file diff --git a/src/widget/NoteWidgetProvider_2x.java b/src/widget/NoteWidgetProvider_2x.java new file mode 100644 index 0000000..f48b84b --- /dev/null +++ b/src/widget/NoteWidgetProvider_2x.java @@ -0,0 +1,76 @@ +/* + * 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. + */ + +package net.micode.notes.widget; + +import android.appwidget.AppWidgetManager; +import android.content.Context; + +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) { + // 调用父类的update方法执行通用更新逻辑(如查询数据、绑定事件) + super.update(context, appWidgetManager, appWidgetIds); + } + + /** + * 实现抽象方法,返回2x尺寸小部件的布局文件ID + * 布局文件定义了小部件的UI结构(如文本位置、背景容器等) + * @return 2x小部件布局ID(R.layout.widget_2x) + */ + @Override + protected int getLayoutId() { + return R.layout.widget_2x; + } + + /** + * 实现抽象方法,返回2x尺寸小部件的背景资源ID + * 根据便签的背景色ID(bgId)获取对应的2x尺寸背景图 + * @param bgId 便签背景色ID(如红色、黄色等) + * @return 2x小部件对应的背景资源ID + */ + @Override + protected int getBgResourceId(int bgId) { + // 通过资源解析工具获取2x尺寸的背景资源 + return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId); + } + + /** + * 实现抽象方法,返回2x尺寸小部件的类型标识 + * 用于系统区分不同尺寸的小部件,关联对应的数据和逻辑 + * @return 2x小部件类型标识(Notes.TYPE_WIDGET_2X) + */ + @Override + protected int getWidgetType() { + return Notes.TYPE_WIDGET_2X; + } +} \ No newline at end of file diff --git a/src/widget/NoteWidgetProvider_4x.java b/src/widget/NoteWidgetProvider_4x.java new file mode 100644 index 0000000..59bf459 --- /dev/null +++ b/src/widget/NoteWidgetProvider_4x.java @@ -0,0 +1,72 @@ +/* + * 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. + */ + +package net.micode.notes.widget; + +import android.appwidget.AppWidgetManager; +import android.content.Context; + +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 { + /** + * 当系统触发小部件更新时调用(如小部件添加到桌面、定时刷新) + * 调用父类的update方法,触发通用更新逻辑(查询便签数据、渲染视图等) + * @param context 应用上下文,用于访问资源和数据库 + * @param appWidgetManager 系统小部件管理器,负责更新小部件视图 + * @param appWidgetIds 需要更新的小部件ID数组 + */ + @Override + public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { + super.update(context, appWidgetManager, appWidgetIds); + } + + /** + * 提供4x尺寸小部件的布局文件ID + * 布局文件widget_4x.xml定义了该小部件的UI结构(如文本区域、背景容器等) + * @return 4x小部件的布局资源ID + */ + protected int getLayoutId() { + return R.layout.widget_4x; + } + + /** + * 根据背景ID(bgId)获取4x小部件对应的背景资源 + * 通过ResourceParser工具类解析,确保背景与便签设置的颜色一致 + * @param bgId 背景标识ID(如红色、蓝色等) + * @return 4x小部件的背景资源ID + */ + @Override + protected int getBgResourceId(int bgId) { + return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId); + } + + /** + * 返回4x小部件的类型标识,用于父类逻辑中区分小部件尺寸 + * 与Notes类中定义的TYPE_WIDGET_4X常量对应,确保数据关联正确 + * @return 4x小部件的类型标识 + */ + @Override + protected int getWidgetType() { + return Notes.TYPE_WIDGET_4X; + } +} \ No newline at end of file diff --git a/src/新建文件夹/AlarmAlertActivity.java b/src/新建文件夹/AlarmAlertActivity.java new file mode 100644 index 0000000..c0e7362 --- /dev/null +++ b/src/新建文件夹/AlarmAlertActivity.java @@ -0,0 +1,203 @@ +/* + * 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. + */ + +package net.micode.notes.ui; + +import android.app.Activity; +import android.app.AlertDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.DialogInterface.OnClickListener; +import android.content.DialogInterface.OnDismissListener; +import android.content.Intent; +import android.media.AudioManager; +import android.media.MediaPlayer; +import android.media.RingtoneManager; +import android.net.Uri; +import android.os.Bundle; +import android.os.PowerManager; +import android.provider.Settings; +import android.view.Window; +import android.view.WindowManager; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +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 + | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON + | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR); + } + + // 获取启动当前Activity的Intent(由AlarmReceiver传递) + Intent intent = getIntent(); + + try { + // 从Intent的Data中解析便签ID(Data格式为content://.../notes/{id},取路径的第2段) + mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1)); + // 通过便签ID获取内容摘要(用于提醒展示) + 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; + } catch (IllegalArgumentException e) { + e.printStackTrace(); + return; + } + + // 初始化媒体播放器 + mPlayer = new MediaPlayer(); + // 检查便签是否存在且可见(未被删除) + if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) { + // 显示提醒对话框 + showActionDialog(); + // 播放闹钟声音 + playAlarmSound(); + } else { + // 便签不存在则直接结束活动 + finish(); + } + } + + /** + * 判断屏幕是否处于亮屏状态 + * @return 屏幕亮着返回true,否则返回false + */ + 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.start(); + } catch (IllegalArgumentException | SecurityException | IllegalStateException | IOException e) { + 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); + // 若屏幕亮着,添加“进入”按钮(跳转到便签编辑页) + if (isScreenOn()) { + dialog.setNegativeButton(R.string.notealert_enter, this); + } + // 显示对话框,并设置消失监听(用于停止铃声) + dialog.show().setOnDismissListener(this); + } + + /** + * 处理对话框按钮点击事件 + * @param dialog 对话框实例 + * @param which 点击的按钮标识(BUTTON_POSITIVE/BUTTON_NEGATIVE) + */ + 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); // 传递便签ID + startActivity(intent); + break; + // 点击“确定”按钮:默认不做额外操作,对话框消失后会停止铃声并结束活动 + default: + break; + } + } + + /** + * 对话框消失时触发:停止铃声并结束活动 + * @param dialog 对话框实例 + */ + public void onDismiss(DialogInterface dialog) { + stopAlarmSound(); + finish(); + } + + /** + * 停止闹钟铃声并释放媒体播放器资源 + */ + private void stopAlarmSound() { + if (mPlayer != null) { + mPlayer.stop(); // 停止播放 + mPlayer.release(); // 释放资源 + mPlayer = null; + } + } +} \ No newline at end of file diff --git a/src/新建文件夹/AlarmInitReceiver.java b/src/新建文件夹/AlarmInitReceiver.java new file mode 100644 index 0000000..919d47b --- /dev/null +++ b/src/新建文件夹/AlarmInitReceiver.java @@ -0,0 +1,100 @@ +/* + * 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. + */ + +package net.micode.notes.ui; + +import android.app.AlarmManager; +import android.app.PendingIntent; +import android.content.BroadcastReceiver; +import android.content.ContentUris; +import android.content.Context; +import android.content.Intent; +import android.database.Cursor; + +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; + +/** + * 便签提醒初始化接收器 + * 用于在系统启动或特定事件触发时,重新注册所有未过期的便签提醒闹钟 + * 确保用户设置的便签提醒不会因系统重启等原因丢失 + */ +public class AlarmInitReceiver extends BroadcastReceiver { + + /** + * 数据库查询字段投影:只查询便签ID和提醒时间 + * 优化查询效率,避免获取不必要的字段 + */ + private static final String [] PROJECTION = new String [] { + NoteColumns.ID, // 便签ID + NoteColumns.ALERTED_DATE // 提醒时间戳 + }; + + // 字段索引常量,用于快速访问Cursor中的数据 + private static final int COLUMN_ID = 0; // 便签ID在投影中的索引 + private static final int COLUMN_ALERTED_DATE = 1; // 提醒时间在投影中的索引 + + /** + * 接收广播时触发的回调方法 + * 负责查询所有未过期的便签提醒,并重新注册到AlarmManager + * @param context 上下文对象 + * @param intent 接收到的广播意图 + */ + @Override + public void onReceive(Context context, Intent intent) { + // 获取当前系统时间,用于筛选未过期的提醒 + long currentDate = System.currentTimeMillis(); + + // 查询数据库中所有未过期的便签提醒 + // 条件:提醒时间 > 当前时间 且 便签类型为普通便签(TYPE_NOTE) + Cursor c = context.getContentResolver().query( + Notes.CONTENT_NOTE_URI, // 查询的内容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); + // 创建触发提醒时的意图(指向AlarmReceiver) + Intent sender = new Intent(context, AlarmReceiver.class); + // 为意图附加便签ID,便于后续定位具体便签 + sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, + c.getLong(COLUMN_ID))); + + // 创建延迟执行的PendingIntent(用于触发提醒) + PendingIntent pendingIntent = PendingIntent.getBroadcast( + context, 0, sender, 0); + + // 获取AlarmManager服务,用于设置系统闹钟 + AlarmManager alermManager = (AlarmManager) context + .getSystemService(Context.ALARM_SERVICE); + + // 注册闹钟:在指定时间(alertDate)唤醒设备并发送广播 + // RTC_WAKEUP模式确保在设备休眠时也能触发 + alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent); + } while (c.moveToNext()); // 继续处理下一个便签 + } + // 关闭Cursor,释放资源 + c.close(); + } + } +} \ No newline at end of file diff --git a/src/新建文件夹/AlarmReceiver.java b/src/新建文件夹/AlarmReceiver.java new file mode 100644 index 0000000..722b750 --- /dev/null +++ b/src/新建文件夹/AlarmReceiver.java @@ -0,0 +1,46 @@ +/* + * 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. + */ + +package net.micode.notes.ui; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; + +/** + * 便签提醒广播接收器,负责接收系统闹钟触发的广播,并启动提醒展示界面 + * 是小米便签提醒流程中连接闹钟触发与提醒展示的中间组件 + */ +public class AlarmReceiver extends BroadcastReceiver { + /** + * 接收广播时触发的回调方法 + * @param context 上下文环境,用于启动Activity + * @param intent 接收到的意图,包含触发提醒的便签信息(如便签ID) + */ + @Override + public void onReceive(Context context, Intent intent) { + // 将意图的目标组件设置为AlarmAlertActivity(便签提醒展示界面) + // 确保广播中携带的便签信息(如Data中的便签ID)被传递给目标界面 + intent.setClass(context, AlarmAlertActivity.class); + + // 添加FLAG_ACTIVITY_NEW_TASK标志:在BroadcastReceiver中启动Activity必须设置此标志 + // 因为BroadcastReceiver本身没有任务栈,需要为启动的Activity创建新任务栈 + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + + // 启动AlarmAlertActivity,展示便签提醒对话框并播放铃声 + context.startActivity(intent); + } +} \ No newline at end of file diff --git a/src/新建文件夹/BackupUtils.java b/src/新建文件夹/BackupUtils.java new file mode 100644 index 0000000..8f3eef8 --- /dev/null +++ b/src/新建文件夹/BackupUtils.java @@ -0,0 +1,436 @@ +/* + * 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. + */ + +package net.micode.notes.tool; + +import android.content.Context; +import android.database.Cursor; +import android.os.Environment; +import android.text.TextUtils; +import android.text.format.DateFormat; +import android.util.Log; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.DataConstants; +import net.micode.notes.data.Notes.NoteColumns; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.PrintStream; + + +/** + * 小米便签的备份工具类,用于将便签数据导出为文本文件存储在SD卡,支持文件夹、普通便签、通话记录便签的备份 + * 采用单例模式,确保全局唯一实例(只有当BackupUtils不存在时才创建) + */ +public class BackupUtils { + private static final String TAG = "BackupUtils"; // 日志标签 + // 单例实例 + private static BackupUtils sInstance; + + /** + * 获取单例实例 + * @param context 应用上下文,用于访问资源和数据库,Context让备份工具能够访问便签数据、读取格式模板、写入SD卡,是连接应用逻辑和Android系统的特殊类 + * @return 全局唯一的BackupUtils实例(只有当BackupUtils不存在时才创建) + */ + public static synchronized BackupUtils getInstance(Context context) { + if (sInstance == null) { + sInstance = new BackupUtils(context); + } + return sInstance; + } + + /** + * 备份/恢复状态常量,用于标识操作结果 + */ + // SD卡未挂载(无法读写) + public static final int STATE_SD_CARD_UNMOUONTED = 0; + // 备份文件不存在(恢复时使用) + public static final int STATE_BACKUP_FILE_NOT_EXIST = 1; + // 数据格式损坏(可能被其他程序修改) + public static final int STATE_DATA_DESTROIED = 2; + // 运行时异常导致操作失败 + public static final int STATE_SYSTEM_ERROR = 3; + // 备份/恢复成功 + public static final int STATE_SUCCESS = 4; + + // 文本导出的具体实现类 + private TextExport mTextExport; + + /** + * 私有构造方法,初始化文本导出工具 + * @param context 应用上下文 + */ + private BackupUtils(Context context) { + mTextExport = new TextExport(context); + } + + /** + * 检查外部存储(SD卡)是否可用(已挂载且可读写) + * @return 可用返回true,否则false + */ + private static boolean externalStorageAvailable() { + return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());// 返回存储状态 + } + + /** + * 对外提供的文本导出入口方法 + * @return 备份状态(如STATE_SUCCESS、STATE_SD_CARD_UNMOUONTED等) + */ + public int exportToText() { + return mTextExport.exportToText(); + } + + /** + * 获取导出的文本文件名 + * @return 文件名(如notes_20240520.txt) + */ + public String getExportedTextFileName() { + return mTextExport.mFileName; + } + + /** + * 获取导出的文本文件所在目录 + * @return 目录路径(如/sdcard/NotesBackup/) + */ + public String getExportedTextFileDir() { + return mTextExport.mFileDirectory; + } + + /** + * 静态内部类,封装文本导出的具体逻辑:查询数据库、格式化数据、写入文件 + */ + private static class TextExport { + // 查询便签时需要的字段投影(只查询需要的列,优化性能) + private static final String[] NOTE_PROJECTION = { + NoteColumns.ID, // 便签/文件夹ID + NoteColumns.MODIFIED_DATE,// 最后修改时间 + NoteColumns.SNIPPET, // 文件夹名或便签摘要 + NoteColumns.TYPE // 类型(文件夹/便签) + }; + + // 字段索引常量,用于从Cursor中快速获取对应值 + private static final int NOTE_COLUMN_ID = 0; + private static final int NOTE_COLUMN_MODIFIED_DATE = 1; + private static final int NOTE_COLUMN_SNIPPET = 2; + + // 查询便签详情数据时的字段投影 + private static final String[] DATA_PROJECTION = { + DataColumns.CONTENT, // 内容(文本/位置) + DataColumns.MIME_TYPE, // 类型(普通便签/通话便签) + DataColumns.DATA1, // 通话便签的通话时间,getFormat函数定义的 + DataColumns.DATA2, + DataColumns.DATA3, // 通话便签的电话号码,getFormat函数定义的 + DataColumns.DATA4, + }; + + /* + * private String getFormat(int id) { + return TEXT_FORMAT[id]; + }*/ + // 数据字段索引常量 + private static final int DATA_COLUMN_CONTENT = 0; + private static final int DATA_COLUMN_MIME_TYPE = 1; + private static final int DATA_COLUMN_CALL_DATE = 2; // 通话时间在DATA1中,getFormat函数定义的 + private static final int DATA_COLUMN_PHONE_NUMBER = 4; // 电话号码在DATA3中,getFormat函数定义的 + + // 文本格式化模板(从资源文件读取,如文件夹名、时间、内容的格式) + private final String [] TEXT_FORMAT; + // 格式化模板的索引常量 + private static final int FORMAT_FOLDER_NAME = 0; // 文件夹名格式 + private static final int FORMAT_NOTE_DATE = 1; // 便签时间格式 + private static final int FORMAT_NOTE_CONTENT = 2; // 便签内容格式 + + private Context mContext; // 上下文 + private String mFileName; // 导出的文件名 + private String mFileDirectory; // 导出的文件目录 + + /** + * 初始化文本导出工具 + * @param context 上下文,用于获取资源和查询数据库 + */ + public TextExport(Context context) { + // 从资源文件读取格式化模板(如strings.xml中的format_for_exported_note数组) + TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note); + mContext = context; + mFileName = ""; + mFileDirectory = ""; + } + + /** + * 获取指定索引的格式化模板 + * @param id 模板索引(如FORMAT_FOLDER_NAME) + * @return 模板字符串 + */ + private String getFormat(int id) { + return TEXT_FORMAT[id]; + } + + /** + * 导出指定文件夹下的所有便签到输出流 + * @param folderId 文件夹ID + * @param ps 输出流(指向备份文件) + */ + private void exportFolderToText(String folderId, PrintStream ps) { + // 查询该文件夹下的所有便签(通过parent_id关联) + Cursor notesCursor = mContext.getContentResolver().query( + Notes.CONTENT_NOTE_URI, // 便签数据库的URI + NOTE_PROJECTION, // 要查询的字段 + NoteColumns.PARENT_ID + "=?", // 查询条件:parent_id=folderId + new String[] {folderId}, // 条件参数 + null); // 排序方式(默认) + + if (notesCursor != null) { + if (notesCursor.moveToFirst()) { // 遍历所有便签 + do { + // 打印便签的最后修改时间(格式化显示) + ps.println(String.format( + getFormat(FORMAT_NOTE_DATE), + DateFormat.format( + mContext.getString(R.string.format_datetime_mdhm), // 时间格式(月日时分) + notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE) + ) + )); + // 导出该便签的详细内容 + String noteId = notesCursor.getString(NOTE_COLUMN_ID); + exportNoteToText(noteId, ps); + } while (notesCursor.moveToNext()); + } + notesCursor.close(); // 关闭游标,释放资源 + } + } + + /** + * 导出单个便签的详细内容到输出流 + * 区分普通便签和通话便签,分别格式化内容 + * @param noteId 便签ID + * @param ps 输出流(指向备份文件) + */ + private void exportNoteToText(String noteId, PrintStream ps) { + // 查询该便签的详细数据(如文本内容、通话记录信息) + Cursor dataCursor = mContext.getContentResolver().query( + Notes.CONTENT_DATA_URI, // 便签数据的URI + DATA_PROJECTION, // 要查询的字段 + DataColumns.NOTE_ID + "=?", // 查询条件:note_id=noteId + new String[] {noteId}, // 条件参数 + null); // 排序方式 + + if (dataCursor != null) { + if (dataCursor.moveToFirst()) { // 遍历便签的所有数据 + do { + String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE); + if (DataConstants.CALL_NOTE.equals(mimeType)) { // 通话记录便签 + // 提取电话号码、通话时间、位置信息 + String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER); + long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE); + String location = dataCursor.getString(DATA_COLUMN_CONTENT); + + // 打印电话号码(非空时) + if (!TextUtils.isEmpty(phoneNumber)) { + ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), phoneNumber)); + } + // 打印通话时间(格式化) + ps.println(String.format( + getFormat(FORMAT_NOTE_CONTENT), + DateFormat.format( + mContext.getString(R.string.format_datetime_mdhm), + callDate + ) + )); + // 打印位置信息(非空时) + if (!TextUtils.isEmpty(location)) { + ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), location)); + } + } else if (DataConstants.NOTE.equals(mimeType)) { // 普通文本便签 + String content = dataCursor.getString(DATA_COLUMN_CONTENT); + if (!TextUtils.isEmpty(content)) { // 打印文本内容 + ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), content)); + } + } + } while (dataCursor.moveToNext()); + } + dataCursor.close(); // 关闭游标,释放资源 + } + // 便签之间添加分隔符(换行) + try { + ps.write(new byte[] {Character.LINE_SEPARATOR, Character.LINE_SEPARATOR}); + } catch (IOException e) { + Log.e(TAG, "写入分隔符失败:" + e.toString()); + } + } + + /** + * 执行文本导出的主逻辑:检查SD卡→创建文件→查询数据→写入文件 + * @return 备份状态(如STATE_SUCCESS) + */ + public int exportToText() { + // 检查SD卡是否可用 + if (!externalStorageAvailable()) { + Log.d(TAG, "SD卡未挂载,无法导出"); + return STATE_SD_CARD_UNMOUONTED; + } + + // 获取指向备份文件的输出流 + PrintStream ps = getExportToTextPrintStream(); + if (ps == null) { + Log.e(TAG, "创建输出流失败"); + return STATE_SYSTEM_ERROR; + } + + // 1. 导出所有文件夹及其包含的便签(排除回收站,包含通话记录文件夹) + Cursor folderCursor = mContext.getContentResolver().query( + Notes.CONTENT_NOTE_URI, + NOTE_PROJECTION, + // 查询条件:文件夹类型且不在回收站,或通话记录文件夹 + "(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + " AND " + + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + ") OR " + + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER, + null, + null); + + if (folderCursor != null) { + if (folderCursor.moveToFirst()) { // 遍历所有文件夹 + do { + // 获取文件夹名(通话记录文件夹使用固定名称) + String folderName = ""; + if (folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) { + folderName = mContext.getString(R.string.call_record_folder_name); // 从资源获取“通话记录” + } else { + folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET); // 普通文件夹名 + } + // 打印文件夹名(非空时) + if (!TextUtils.isEmpty(folderName)) { + ps.println(String.format(getFormat(FORMAT_FOLDER_NAME), folderName)); + } + // 导出该文件夹下的所有便签 + String folderId = folderCursor.getString(NOTE_COLUMN_ID); + exportFolderToText(folderId, ps); + } while (folderCursor.moveToNext()); + } + folderCursor.close(); // 关闭游标 + } + + // 2. 导出根目录下的便签(无文件夹归属的便签,parent_id=0) + Cursor noteCursor = mContext.getContentResolver().query( + Notes.CONTENT_NOTE_URI, + NOTE_PROJECTION, + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID + "=0", + null, + null); + + if (noteCursor != null) { + if (noteCursor.moveToFirst()) { // 遍历根目录便签 + do { + // 打印修改时间 + ps.println(String.format( + getFormat(FORMAT_NOTE_DATE), + DateFormat.format( + mContext.getString(R.string.format_datetime_mdhm), + noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE) + ) + )); + // 导出便签内容 + String noteId = noteCursor.getString(NOTE_COLUMN_ID); + exportNoteToText(noteId, ps); + } while (noteCursor.moveToNext()); + } + noteCursor.close(); // 关闭游标 + } + + ps.close(); // 关闭输出流 + return STATE_SUCCESS; // 导出成功 + } + + /** + * 创建SD卡上的备份文件,并返回指向该文件的PrintStream + * @return 输出流(PrintStream),失败返回null + */ + private PrintStream getExportToTextPrintStream() { + // 在SD卡上生成备份文件(路径和名称从资源获取,包含当前日期) + File file = generateFileMountedOnSDcard( + mContext, + R.string.file_path, // 目录路径(如/sdcard/NotesBackup/) + R.string.file_name_txt_format // 文件名格式(如notes_%s.txt,%s为日期) + ); + if (file == null) { + Log.e(TAG, "创建备份文件失败"); + return null; + } + // 记录文件名和目录 + mFileName = file.getName(); + mFileDirectory = mContext.getString(R.string.file_path); + + // 创建输出流 + PrintStream ps = null; + try { + FileOutputStream fos = new FileOutputStream(file); + ps = new PrintStream(fos); + } catch (FileNotFoundException e) { + e.printStackTrace(); + return null; + } catch (NullPointerException e) { + e.printStackTrace(); + return null; + } + return ps; + } + } + + /** + * 在SD卡上创建备份文件(含目录) + * @param context 上下文 + * @param filePathResId 目录路径的资源ID(如R.string.file_path) + * @param fileNameFormatResId 文件名格式的资源ID(如R.string.file_name_txt_format) + * @return 创建的文件,失败返回null + */ + private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) { + StringBuilder sb = new StringBuilder(); + // 拼接路径:SD卡根目录 + 应用备份目录(如/sdcard/NotesBackup/) + sb.append(Environment.getExternalStorageDirectory()); + sb.append(context.getString(filePathResId)); + File filedir = new File(sb.toString()); + + // 拼接文件名:目录 + 格式化名称(含当前日期,如notes_20240520.txt) + sb.append(context.getString( + fileNameFormatResId, + DateFormat.format( + context.getString(R.string.format_date_ymd), // 日期格式(年月日) + System.currentTimeMillis() + ) + )); + File file = new File(sb.toString()); + + // 创建目录和文件 + try { + if (!filedir.exists()) { + filedir.mkdir(); // 目录不存在则创建 + } + if (!file.exists()) { + file.createNewFile(); // 文件不存在则创建 + } + return file; + } catch (SecurityException e) { + e.printStackTrace(); // 权限不足 + } catch (IOException e) { + e.printStackTrace(); // 创建文件失败 + } + return null; + } +} \ No newline at end of file diff --git a/src/新建文件夹/DataUtils.java b/src/新建文件夹/DataUtils.java new file mode 100644 index 0000000..1aa2572 --- /dev/null +++ b/src/新建文件夹/DataUtils.java @@ -0,0 +1,381 @@ +/* + * 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. + */ + +package net.micode.notes.tool; + +import android.content.ContentProviderOperation; +import android.content.ContentProviderResult; +import android.content.ContentResolver; +import android.content.ContentUris; +import android.content.ContentValues; +import android.content.OperationApplicationException; +import android.database.Cursor; +import android.os.RemoteException; +import android.util.Log; + +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.CallNote; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute; + +import java.util.ArrayList; +import java.util.HashSet; + + + + +/** + * 便签数据操作工具类,封装数据库查询、更新、删除等常用操作, + * 提供与ContentProvider交互的统一接口,支撑UI层的数据需求 + */ +public class DataUtils { + public static final String TAG = "DataUtils"; + + /** + * 批量删除便签或文件夹(跳过系统根目录) + * @param resolver 内容解析器,用于操作数据库 + * @param ids 待删除的便签/文件夹ID集合 + * @return 操作成功返回true,失败返回false + */ + public static boolean batchDeleteNotes(ContentResolver resolver, HashSet ids) { + if (ids == null) { + Log.d(TAG, "待删除的ID集合为null"); + return true; + } + if (ids.size() == 0) { + Log.d(TAG, "待删除的ID集合为空"); + return true; + } + + // 创建批量删除操作列表 + ArrayList operationList = new ArrayList(); + for (long id : ids) { + // 禁止删除系统根目录 + if(id == Notes.ID_ROOT_FOLDER) { + Log.e(TAG, "不能删除系统根目录文件夹"); + continue; + } + // 构建删除操作(根据ID删除便签) + ContentProviderOperation.Builder builder = ContentProviderOperation + .newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); + operationList.add(builder.build()); + } + + try { + // 执行批量删除 + ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); + if (results == null || results.length == 0 || results[0] == null) { + Log.d(TAG, "删除失败,ID集合:" + ids.toString()); + return false; + } + return true; + } catch (RemoteException e) { + Log.e(TAG, String.format("远程异常: %s: %s", e.toString(), e.getMessage())); + } catch (OperationApplicationException e) { + Log.e(TAG, String.format("操作应用异常: %s: %s", e.toString(), e.getMessage())); + } + return false; + } + + /** + * 将单个便签移动到目标文件夹 + * @param resolver 内容解析器 + * @param id 便签ID + * @param srcFolderId 原文件夹ID + * @param desFolderId 目标文件夹ID + */ + public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) { + ContentValues values = new ContentValues(); + values.put(NoteColumns.PARENT_ID, desFolderId); // 更新父目录ID为目标文件夹 + values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId); // 记录原始文件夹ID + values.put(NoteColumns.LOCAL_MODIFIED, 1); // 标记本地已修改 + // 执行更新操作 + resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null); + } + + /** + * 批量移动便签到目标文件夹 + * @param resolver 内容解析器 + * @param ids 待移动的便签ID集合 + * @param folderId 目标文件夹ID + * @return 操作成功返回true,失败返回false + */ + public static boolean batchMoveToFolder(ContentResolver resolver, HashSet ids, + long folderId) { + if (ids == null) { + Log.d(TAG, "待移动的ID集合为null"); + return true; + } + + // 创建批量更新操作列表 + ArrayList operationList = new ArrayList(); + for (long id : ids) { + // 构建更新操作(修改父目录ID) + ContentProviderOperation.Builder builder = ContentProviderOperation + .newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); + builder.withValue(NoteColumns.PARENT_ID, folderId); + builder.withValue(NoteColumns.LOCAL_MODIFIED, 1); // 标记本地修改 + operationList.add(builder.build()); + } + + try { + // 执行批量更新 + ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); + if (results == null || results.length == 0 || results[0] == null) { + Log.d(TAG, "移动失败,ID集合:" + ids.toString()); + return false; + } + return true; + } catch (RemoteException e) { + Log.e(TAG, String.format("远程异常: %s: %s", e.toString(), e.getMessage())); + } catch (OperationApplicationException e) { + Log.e(TAG, String.format("操作应用异常: %s: %s", e.toString(), e.getMessage())); + } + return false; + } + + /** + * 获取用户创建的文件夹数量(排除系统文件夹如垃圾站) + * @param resolver 内容解析器 + * @return 文件夹数量 + */ + public static int getUserFolderCount(ContentResolver resolver) { + // 查询非系统的文件夹且不在垃圾站中的文件夹数量 + Cursor cursor =resolver.query(Notes.CONTENT_NOTE_URI, + new String[] { "COUNT(*)" }, // 统计数量 + NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?", + new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)}, + null); + + int count = 0; + if(cursor != null) { + if(cursor.moveToFirst()) { + try { + count = cursor.getInt(0); + } catch (IndexOutOfBoundsException e) { + Log.e(TAG, "获取文件夹数量失败:" + e.toString()); + } finally { + cursor.close(); + } + } + } + return count; + } + + /** + * 检查便签是否存在且可见(不在垃圾站中) + * @param resolver 内容解析器 + * @param noteId 便签ID + * @param type 便签类型(如Notes.TYPE_NOTE) + * @return 存在且可见返回true,否则返回false + */ + public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) { + Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), + null, + NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER, + new String [] {String.valueOf(type)}, + null); + + boolean exist = false; + if (cursor != null) { + exist = cursor.getCount() > 0; // 游标有数据则存在 + cursor.close(); + } + return exist; + } + + /** + * 检查便签是否存在(包括垃圾站中的便签) + * @param resolver 内容解析器 + * @param noteId 便签ID + * @return 存在返回true,否则返回false + */ + public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) { + Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), + null, null, null, null); + + boolean exist = false; + if (cursor != null) { + exist = cursor.getCount() > 0; + cursor.close(); + } + return exist; + } + + /** + * 检查便签内容数据是否存在 + * @param resolver 内容解析器 + * @param dataId 内容数据ID + * @return 存在返回true,否则返回false + */ + public static boolean existInDataDatabase(ContentResolver resolver, long dataId) { + Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), + null, null, null, null); + + boolean exist = false; + if (cursor != null) { + exist = cursor.getCount() > 0; + cursor.close(); + } + return exist; + } + + /** + * 检查可见文件夹名称是否已存在(排除垃圾站) + * @param resolver 内容解析器 + * @param name 文件夹名称 + * @return 已存在返回true,否则返回false + */ + public static boolean checkVisibleFolderName(ContentResolver resolver, String name) { + Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null, + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + + " AND " + NoteColumns.SNIPPET + "=?", // SNIPPET字段存储文件夹名称 + new String[] { name }, null); + boolean exist = false; + if(cursor != null) { + exist = cursor.getCount() > 0; + cursor.close(); + } + return exist; + } + + /** + * 获取文件夹下所有便签关联的桌面小部件属性 + * @param resolver 内容解析器 + * @param folderId 文件夹ID + * @return 小部件属性集合(包含widgetId和widgetType) + */ + public static HashSet getFolderNoteWidget(ContentResolver resolver, long folderId) { + Cursor c = resolver.query(Notes.CONTENT_NOTE_URI, + new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE }, // 查询小部件ID和类型 + NoteColumns.PARENT_ID + "=?", // 筛选指定文件夹下的便签 + new String[] { String.valueOf(folderId) }, + null); + + HashSet set = null; + if (c != null) { + if (c.moveToFirst()) { + set = new HashSet(); + do { + try { + AppWidgetAttribute widget = new AppWidgetAttribute(); + widget.widgetId = c.getInt(0); + widget.widgetType = c.getInt(1); + set.add(widget); + } catch (IndexOutOfBoundsException e) { + Log.e(TAG, e.toString()); + } + } while (c.moveToNext()); + } + c.close(); + } + return set; + } + + /** + * 通过便签ID获取关联的电话号码(用于通话便签) + * @param resolver 内容解析器 + * @param noteId 通话便签ID + * @return 电话号码,获取失败返回空字符串 + */ + public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) { + Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, + new String [] { CallNote.PHONE_NUMBER }, // 查询电话号码字段 + CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?", // 筛选通话便签数据 + new String [] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE }, + null); + + if (cursor != null && cursor.moveToFirst()) { + try { + return cursor.getString(0); + } catch (IndexOutOfBoundsException e) { + Log.e(TAG, "获取电话号码失败 " + e.toString()); + } finally { + cursor.close(); + } + } + return ""; + } + + /** + * 通过电话号码和通话时间查找对应的通话便签ID(避免重复创建) + * @param resolver 内容解析器 + * @param phoneNumber 电话号码 + * @param callDate 通话时间戳 + * @return 便签ID,未找到返回0 + */ + public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) { + Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, + new String [] { CallNote.NOTE_ID }, // 查询关联的便签ID + CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL(" + + CallNote.PHONE_NUMBER + ",?)", // 按通话时间和电话号码筛选(支持号码格式匹配) + new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber }, + null); + + if (cursor != null) { + if (cursor.moveToFirst()) { + try { + return cursor.getLong(0); + } catch (IndexOutOfBoundsException e) { + Log.e(TAG, "获取通话便签ID失败 " + e.toString()); + } + } + cursor.close(); + } + return 0; + } + + /** + * 通过便签ID获取摘要文本(用于列表页展示) + * @param resolver 内容解析器 + * @param noteId 便签ID + * @return 摘要文本,便签不存在则抛出异常 + */ + public static String getSnippetById(ContentResolver resolver, long noteId) { + Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, + new String [] { NoteColumns.SNIPPET }, // 查询摘要字段 + NoteColumns.ID + "=?", + new String [] { String.valueOf(noteId)}, + null); + + if (cursor != null) { + String snippet = ""; + if (cursor.moveToFirst()) { + snippet = cursor.getString(0); + } + cursor.close(); + return snippet; + } + throw new IllegalArgumentException("未找到ID为 " + noteId + " 的便签"); + } + + /** + * 格式化摘要文本(去除首尾空格,取首行内容) + * @param snippet 原始摘要文本 + * @return 格式化后的摘要 + */ + public static String getFormattedSnippet(String snippet) { + if (snippet != null) { + snippet = snippet.trim(); // 去除首尾空格 + int index = snippet.indexOf('\n'); // 查找第一个换行符 + if (index != -1) { + snippet = snippet.substring(0, index); // 截取首行内容 + } + } + return snippet; + } +} \ No newline at end of file diff --git a/src/新建文件夹/DateTimePicker.java b/src/新建文件夹/DateTimePicker.java new file mode 100644 index 0000000..906261f --- /dev/null +++ b/src/新建文件夹/DateTimePicker.java @@ -0,0 +1,576 @@ +/* + * 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. + */ + +package net.micode.notes.ui; + +import java.text.DateFormatSymbols; +import java.util.Calendar; + +import net.micode.notes.R; + + +import android.content.Context; +import android.text.format.DateFormat; +import android.view.View; +import android.widget.FrameLayout; +import android.widget.NumberPicker; + +/** + * 日期时间选择器组件 + * 用于小米便签中设置提醒时间,支持日期、小时、分钟的选择,以及12/24小时制切换 + */ +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 HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW = 0; // 24小时制小时最小值 + private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23; // 24小时制小时最大值 + private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1; // 12小时制小时最小值 + private static final int HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW = 12; // 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; // 上下午选择器(12小时制用) + private Calendar mDate; // 日期时间计算工具 + + // 日期显示值数组(存储近一周的日期文本) + private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK]; + + // 时间状态变量 + 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(); + } + }; + + /** + * 小时选择器值变化监听器 + * 处理小时变更逻辑,包括跨天情况(如23点到0点)和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(); + + if (!mIs24HourView) { + // 12小时制处理:跨天情况(如11PM到12AM需加一天,12AM到11PM需减一天) + 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) { + cal.setTimeInMillis(mDate.getTimeInMillis()); + cal.add(Calendar.DAY_OF_YEAR, -1); + isDateChanged = true; + } + // 12点和11点切换时,切换上下午状态 + 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小时制处理:跨天情况(如23点到0点加一天,0点到23点减一天) + 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) { + cal.setTimeInMillis(mDate.getTimeInMillis()); + cal.add(Calendar.DAY_OF_YEAR, -1); + isDateChanged = true; + } + } + + // 更新小时并触发事件 + 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)); + setCurrentDay(cal.get(Calendar.DAY_OF_MONTH)); + } + } + }; + + /** + * 分钟选择器值变化监听器 + * 处理分钟变更逻辑,包括跨小时情况(如59分到0分需加1小时) + */ + 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; + + // 判断是否跨小时(59->0加1小时,0->59减1小时) + if (oldVal == maxValue && newVal == minValue) { + offset += 1; + } else if (oldVal == minValue && newVal == maxValue) { + offset -= 1; + } + + if (offset != 0) { + // 调整小时并更新相关控件 + mDate.add(Calendar.HOUR_OF_DAY, offset); + mHourSpinner.setValue(getCurrentHour()); + updateDateControl(); + + // 更新上下午状态(12小时制) + int newHour = getCurrentHourOfDay(); + if (newHour >= HOURS_IN_HALF_DAY) { + mIsAm = false; + } else { + mIsAm = true; + } + updateAmPmControl(); + } + + // 更新分钟并触发事件 + mDate.set(Calendar.MINUTE, newVal); + onDateTimeChanged(); + } + }; + + /** + * 上下午选择器值变化监听器 + * 切换上午/下午状态,并调整小时(加减12小时) + */ + private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() { + @Override + public void onValueChange(NumberPicker picker, int oldVal, int newVal) { + mIsAm = !mIsAm; + // 切换上下午时调整小时(上午转下午加12小时,反之减12小时) + if (mIsAm) { + mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY); + } else { + mDate.add(Calendar.HOUR_OF_DAY, HOURS_IN_HALF_DAY); + } + updateAmPmControl(); + onDateTimeChanged(); + } + }; + + /** + * 日期时间变更监听器接口 + * 当用户修改日期或时间时回调 + */ + public interface OnDateTimeChangedListener { + void onDateTimeChanged(DateTimePicker view, int year, int month, + int dayOfMonth, int hourOfDay, int minute); + } + + /** + * 构造方法:使用当前时间初始化,默认使用系统时间格式(12/24小时制) + * @param context 上下文 + */ + public DateTimePicker(Context context) { + this(context, System.currentTimeMillis()); + } + + /** + * 构造方法:使用指定时间初始化,默认使用系统时间格式(12/24小时制) + * @param context 上下文 + * @param date 初始化时间戳(毫秒) + */ + public DateTimePicker(Context context, long date) { + this(context, date, DateFormat.is24HourFormat(context)); + } + + /** + * 构造方法:使用指定时间和时间格式初始化 + * @param context 上下文 + * @param date 初始化时间戳(毫秒) + * @param is24HourView 是否使用24小时制 + */ + public DateTimePicker(Context context, long date, boolean is24HourView) { + super(context); + 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.setOnValueChangedListener(mOnMinuteChangedListener); + + // 初始化上下午选择器(使用系统本地化的AM/PM文本) + 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.setOnValueChangedListener(mOnAmPmChangedListener); + + // 更新控件到初始状态 + updateDateControl(); + updateHourControl(); + updateAmPmControl(); + + // 设置时间格式(12/24小时制) + set24HourView(is24HourView); + + // 设置初始时间 + setCurrentDate(date); + + // 设置启用状态 + setEnabled(isEnabled()); + + // 初始化完成 + mInitialising = false; + } + + /** + * 设置组件启用状态 + * @param enabled 是否启用 + */ + @Override + public void setEnabled(boolean enabled) { + if (mIsEnabled == enabled) { + return; + } + super.setEnabled(enabled); + mDateSpinner.setEnabled(enabled); + mMinuteSpinner.setEnabled(enabled); + mHourSpinner.setEnabled(enabled); + mAmPmSpinner.setEnabled(enabled); + mIsEnabled = enabled; + } + + /** + * 获取组件启用状态 + * @return 是否启用 + */ + @Override + public boolean isEnabled() { + return mIsEnabled; + } + + /** + * 获取当前选中的日期时间(毫秒时间戳) + * @return 时间戳 + */ + public long getCurrentDateInTimeMillis() { + return mDate.getTimeInMillis(); + } + + /** + * 设置当前日期时间(通过时间戳) + * @param date 时间戳(毫秒) + */ + 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)); + } + + /** + * 设置当前日期时间(通过年月日时分) + * @param year 年 + * @param month 月(0-11) + * @param dayOfMonth 日 + * @param hourOfDay 时(24小时制,0-23) + * @param minute 分 + */ + public void setCurrentDate(int year, int month, + int dayOfMonth, int hourOfDay, int minute) { + setCurrentYear(year); + setCurrentMonth(month); + setCurrentDay(dayOfMonth); + setCurrentHour(hourOfDay); + setCurrentMinute(minute); + } + + /** + * 获取当前年份 + * @return 年份 + */ + public int getCurrentYear() { + return mDate.get(Calendar.YEAR); + } + + /** + * 设置当前年份 + * @param year 年份 + */ + public void setCurrentYear(int year) { + if (!mInitialising && year == getCurrentYear()) { + return; + } + mDate.set(Calendar.YEAR, year); + updateDateControl(); + onDateTimeChanged(); + } + + /** + * 获取当前月份(0-11) + * @return 月份 + */ + public int getCurrentMonth() { + return mDate.get(Calendar.MONTH); + } + + /** + * 设置当前月份 + * @param month 月份(0-11) + */ + public void setCurrentMonth(int month) { + if (!mInitialising && month == getCurrentMonth()) { + return; + } + mDate.set(Calendar.MONTH, month); + updateDateControl(); + onDateTimeChanged(); + } + + /** + * 获取当前日 + * @return 日 + */ + public int getCurrentDay() { + return mDate.get(Calendar.DAY_OF_MONTH); + } + + /** + * 设置当前日 + * @param dayOfMonth 日 + */ + public void setCurrentDay(int dayOfMonth) { + if (!mInitialising && dayOfMonth == getCurrentDay()) { + return; + } + mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth); + updateDateControl(); + onDateTimeChanged(); + } + + /** + * 获取当前小时(24小时制,0-23) + * @return 小时 + */ + public int getCurrentHourOfDay() { + return mDate.get(Calendar.HOUR_OF_DAY); + } + + /** + * 根据当前时间格式(12/24小时制)获取小时显示值 + * @return 小时显示值 + */ + private int getCurrentHour() { + if (mIs24HourView){ + return getCurrentHourOfDay(); + } else { + int hour = getCurrentHourOfDay(); + // 12小时制转换:13->1,0->12 + if (hour > HOURS_IN_HALF_DAY) { + return hour - HOURS_IN_HALF_DAY; + } else { + return hour == 0 ? HOURS_IN_HALF_DAY : hour; + } + } + } + + /** + * 设置当前小时(24小时制) + * @param hourOfDay 小时(0-23) + */ + public void setCurrentHour(int hourOfDay) { + if (!mInitialising && hourOfDay == getCurrentHourOfDay()) { + return; + } + mDate.set(Calendar.HOUR_OF_DAY, hourOfDay); + + if (!mIs24HourView) { + // 12小时制处理:更新上下午状态和小时显示值 + 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(); + } + + /** + * 获取当前分钟 + * @return 分钟 + */ + public int getCurrentMinute() { + return mDate.get(Calendar.MINUTE); + } + + /** + * 设置当前分钟 + * @param minute 分钟(0-59) + */ + public void setCurrentMinute(int minute) { + if (!mInitialising && minute == getCurrentMinute()) { + return; + } + mMinuteSpinner.setValue(minute); + mDate.set(Calendar.MINUTE, minute); + onDateTimeChanged(); + } + + /** + * 判断是否为24小时制显示 + * @return 是否为24小时制 + */ + public boolean is24HourView () { + return mIs24HourView; + } + + /** + * 设置时间显示格式(24小时制/12小时制) + * @param is24HourView true为24小时制,false为12小时制 + */ + public void set24HourView(boolean is24HourView) { + if (mIs24HourView == is24HourView) { + return; + } + mIs24HourView = is24HourView; + // 24小时制隐藏上下午选择器,12小时制显示 + 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()); + // 计算起始日期(当前日期减去3天,用于显示近一周) + 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(); + } + + /** + * 更新上下午选择器状态(根据12小时制和当前上下午状态) + */ + private void updateAmPmControl() { + if (mIs24HourView) { + mAmPmSpinner.setVisibility(View.GONE); + } else { + int index = mIsAm ? Calendar.AM : Calendar.PM; + mAmPmSpinner.setValue(index); + mAmPmSpinner.setVisibility(View.VISIBLE); + } + } + + /** + * 更新小时选择器的范围(根据12/24小时制) + */ + 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); + } + } + + /** + * 设置日期时间变更监听器 + * @param callback 监听器实例 + */ + public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) { + mOnDateTimeChangedListener = callback; + } + + /** + * 触发日期时间变更事件(通知监听器) + */ + private void onDateTimeChanged() { + if (mOnDateTimeChangedListener != null) { + mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(), + getCurrentMonth(), getCurrentDay(), getCurrentHourOfDay(), getCurrentMinute()); + } + } +} \ No newline at end of file diff --git a/src/新建文件夹/DateTimePickerDialog.java b/src/新建文件夹/DateTimePickerDialog.java new file mode 100644 index 0000000..309d989 --- /dev/null +++ b/src/新建文件夹/DateTimePickerDialog.java @@ -0,0 +1,137 @@ +/* + * 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. + */ + +package net.micode.notes.ui; + +import java.util.Calendar; + +import net.micode.notes.R; +import net.micode.notes.ui.DateTimePicker; +import net.micode.notes.ui.DateTimePicker.OnDateTimeChangedListener; + +import android.app.AlertDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.DialogInterface.OnClickListener; +import android.text.format.DateFormat; +import android.text.format.DateUtils; + +/** + * 日期时间选择对话框,用于小米便签中设置提醒时间的交互界面 + * 继承自AlertDialog,内部集成DateTimePicker作为选择视图,提供日期和时间的可视化选择 + */ +public class DateTimePickerDialog extends AlertDialog implements OnClickListener { + + // 用于维护当前选中的日期时间 + private Calendar mDate = Calendar.getInstance(); + // 是否采用24小时制显示时间 + private boolean mIs24HourView; + // 日期时间选择完成后的回调监听器(由调用者实现,如NoteEditActivity) + private OnDateTimeSetListener mOnDateTimeSetListener; + // 自定义的日期时间选择器视图,负责用户选择交互 + private DateTimePicker mDateTimePicker; + + /** + * 日期时间选择完成的回调接口 + * 当用户点击"确定"后,通过此接口将选中的时间(毫秒级时间戳)传递给调用者 + */ + public interface OnDateTimeSetListener { + void OnDateTimeSet(AlertDialog dialog, long date); + } + + /** + * 构造方法:初始化日期时间选择对话框 + * @param context 上下文环境(如NoteEditActivity) + * @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()); + + // 设置对话框按钮:"确定"按钮触发onClick方法,"取消"按钮不执行操作 + setButton(context.getString(R.string.datetime_dialog_ok), this); + setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null); + + // 根据系统设置初始化24小时制显示模式 + set24HourView(DateFormat.is24HourFormat(this.getContext())); + // 初始化对话框标题为初始日期时间 + updateTitle(mDate.getTimeInMillis()); + } + + /** + * 设置时间显示模式(24小时制/12小时制) + * @param is24HourView true为24小时制,false为12小时制 + */ + public void set24HourView(boolean is24HourView) { + mIs24HourView = is24HourView; + } + + /** + * 设置日期时间选择完成后的回调监听器 + * @param callBack 实现了OnDateTimeSetListener的对象(通常为调用对话框的Activity) + */ + 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小时制模式调整显示格式 + flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_12HOUR; + // 格式化时间并设置为对话框标题 + setTitle(DateUtils.formatDateTime(this.getContext(), date, flag)); + } + + /** + * 处理"确定"按钮的点击事件 + * 当用户点击确定后,通过回调接口将选中的时间传递给调用者 + */ + public void onClick(DialogInterface arg0, int arg1) { + if (mOnDateTimeSetListener != null) { + // 回调传递选中的时间(毫秒级时间戳) + mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis()); + } + } + +} \ No newline at end of file diff --git a/src/新建文件夹/DropdownMenu.java b/src/新建文件夹/DropdownMenu.java new file mode 100644 index 0000000..041b5f6 --- /dev/null +++ b/src/新建文件夹/DropdownMenu.java @@ -0,0 +1,92 @@ +/* + * 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. + */ + +package net.micode.notes.ui; + +import android.content.Context; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.view.View.OnClickListener; +import android.widget.Button; +import android.widget.PopupMenu; +import android.widget.PopupMenu.OnMenuItemClickListener; + +import net.micode.notes.R; + +/** + * 下拉菜单工具类,用于在小米便签中实现按钮触发的弹出式菜单 + * 典型场景:笔记列表的批量操作菜单、编辑页的功能选项菜单等 + */ +public class DropdownMenu { + // 触发下拉菜单的按钮 + private Button mButton; + // 系统提供的弹出式菜单组件,负责显示下拉选项 + private PopupMenu mPopupMenu; + // 菜单容器,存储从资源文件加载的菜单项 + private Menu mMenu; + + /** + * 构造方法:初始化下拉菜单 + * @param context 上下文对象,用于访问资源和创建视图 + * @param button 触发下拉菜单的按钮 + * @param menuId 菜单资源ID(定义在res/menu目录下) + */ + 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(); + } + }); + } + + /** + * 设置下拉菜单项的点击事件监听器 + * @param listener 监听器对象,处理菜单项点击逻辑 + */ + public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) { + if (mPopupMenu != null) { + mPopupMenu.setOnMenuItemClickListener(listener); + } + } + + /** + * 根据ID查找菜单中的具体选项 + * @param id 菜单项的资源ID + * @return 对应的MenuItem对象,可用于修改状态(如勾选、隐藏) + */ + public MenuItem findItem(int id) { + return mMenu.findItem(id); + } + + /** + * 设置触发按钮的显示文本 + * @param title 要显示的文本(如"已选择3项") + */ + public void setTitle(CharSequence title) { + mButton.setText(title); + } +} \ No newline at end of file diff --git a/src/新建文件夹/FoldersListAdapter.java b/src/新建文件夹/FoldersListAdapter.java new file mode 100644 index 0000000..6fee552 --- /dev/null +++ b/src/新建文件夹/FoldersListAdapter.java @@ -0,0 +1,130 @@ +/* + * 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. + */ + +package net.micode.notes.ui; + +import android.content.Context; +import android.database.Cursor; +import android.view.View; +import android.view.ViewGroup; +import android.widget.CursorAdapter; +import android.widget.LinearLayout; +import android.widget.TextView; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; + +/** + * 文件夹列表适配器,用于小米便签中展示文件夹列表(如移动便签时选择目标文件夹) + * 继承自CursorAdapter,负责将数据库中的文件夹数据与列表视图绑定 + */ +public class FoldersListAdapter extends CursorAdapter { + /** + * 数据库查询投影:指定需要查询的文件夹字段 + * 包含文件夹ID(用于区分不同文件夹)和文件夹名称(存储在SNIPPET字段) + */ + public static final String [] PROJECTION = { + NoteColumns.ID, // 文件夹ID + NoteColumns.SNIPPET // 文件夹名称(小米便签中文件夹名称存储在此字段) + }; + + /** + * 投影字段对应的索引,用于从Cursor中快速获取数据 + */ + public static final int ID_COLUMN = 0; // PROJECTION中ID字段的索引 + public static final int NAME_COLUMN = 1; // PROJECTION中SNIPPET(名称)字段的索引 + + /** + * 构造方法:初始化文件夹列表适配器 + * @param context 上下文环境(如调用文件夹列表的Activity或对话框) + * @param c 包含文件夹数据的数据库游标(查询结果) + */ + public FoldersListAdapter(Context context, Cursor c) { + super(context, c); + // TODO Auto-generated constructor stub + } + + /** + * 创建新的列表项视图 + * @param context 上下文环境 + * @param cursor 包含当前项数据的游标(此处未直接使用,仅用于创建视图) + * @param parent 父视图容器(通常为ListView) + * @return 自定义的文件夹列表项视图(FolderListItem实例) + */ + @Override + public View newView(Context context, Cursor cursor, ViewGroup parent) { + return new FolderListItem(context); + } + + /** + * 将游标中的文件夹数据绑定到列表项视图 + * @param view 列表项视图(FolderListItem实例) + * @param context 上下文环境 + * @param cursor 包含当前文件夹数据的游标 + */ + @Override + public void bindView(View view, Context context, Cursor cursor) { + if (view instanceof FolderListItem) { + // 处理根文件夹的特殊名称:根文件夹ID为Notes.ID_ROOT_FOLDER,显示为“移动到父文件夹” + 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); + // 根文件夹特殊处理,其他文件夹直接取SNIPPET字段值 + return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context + .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); + } + + /** + * 自定义文件夹列表项视图,继承LinearLayout,用于展示单个文件夹的名称 + */ + private class FolderListItem extends LinearLayout { + private TextView mName; // 用于显示文件夹名称的文本控件 + + /** + * 构造方法:初始化列表项布局和控件 + * @param context 上下文环境 + */ + public FolderListItem(Context context) { + super(context); + // 加载文件夹列表项的布局文件(folder_list_item.xml) + 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/新建文件夹/GTaskStringUtils.java b/src/新建文件夹/GTaskStringUtils.java new file mode 100644 index 0000000..37a6856 --- /dev/null +++ b/src/新建文件夹/GTaskStringUtils.java @@ -0,0 +1,169 @@ +/* + * 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. + */ +package net.micode.notes.tool; + +/** + * GTask字符串常量工具类,定义小米便签与GTask(Google Tasks)同步过程中使用的所有标识符 + * 包括JSON键名、文件夹标识、元数据键等,用于统一同步过程中的数据交互格式 + */ +public class GTaskStringUtils { + + // ========================== GTask JSON动作相关键名 ========================== + /** JSON中动作ID的键名,用于标识同步操作的唯一ID(如创建/更新任务的动作ID) */ + public final static String GTASK_JSON_ACTION_ID = "action_id"; + + /** JSON中动作列表的键名,用于包装多个同步动作(如批量创建/更新任务) */ + public final static String GTASK_JSON_ACTION_LIST = "action_list"; + + /** JSON中动作类型的键名,用于标识当前动作是创建/更新/移动等类型 */ + public final static String GTASK_JSON_ACTION_TYPE = "action_type"; + + /** 动作类型:创建操作,用于标识在GTask中创建新任务或文件夹 */ + public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create"; + + /** 动作类型:获取全部数据,用于请求GTask中的所有任务和文件夹数据 */ + public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all"; + + /** 动作类型:移动操作,用于标识将任务/文件夹移动到新位置 */ + public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move"; + + /** 动作类型:更新操作,用于标识修改GTask中已有的任务或文件夹 */ + public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update"; + + + // ========================== GTask JSON实体属性相关键名 ========================== + /** JSON中创建者ID的键名,标识任务/文件夹的创建者(小米便签中暂用"null") */ + public final static String GTASK_JSON_CREATOR_ID = "creator_id"; + + /** JSON中子实体的键名,用于存储子任务信息 */ + public final static String GTASK_JSON_CHILD_ENTITY = "child_entity"; + + /** JSON中客户端版本的键名,标识当前同步客户端的版本 */ + public final static String GTASK_JSON_CLIENT_VERSION = "client_version"; + + /** JSON中任务完成状态的键名,标识任务是否已完成(true/false) */ + public final static String GTASK_JSON_COMPLETED = "completed"; + + /** JSON中当前列表ID的键名,标识当前操作的任务列表ID */ + public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id"; + + /** JSON中默认列表ID的键名,标识GTask中的默认任务列表ID */ + public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id"; + + /** JSON中删除状态的键名,标识任务/文件夹是否已删除(true/false) */ + public final static String GTASK_JSON_DELETED = "deleted"; + + /** JSON中目标列表的键名,用于移动操作时指定目标列表 */ + public final static String GTASK_JSON_DEST_LIST = "dest_list"; + + /** JSON中目标父节点的键名,用于移动操作时指定目标父节点 */ + public final static String GTASK_JSON_DEST_PARENT = "dest_parent"; + + /** JSON中目标父节点类型的键名,标识目标父节点是任务(TASK)还是文件夹(GROUP) */ + public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type"; + + /** JSON中实体增量的键名,用于存储任务/文件夹的修改内容(如名称、状态等) */ + public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta"; + + /** JSON中实体类型的键名,标识当前实体是任务(TASK)还是文件夹(GROUP) */ + public final static String GTASK_JSON_ENTITY_TYPE = "entity_type"; + + /** JSON中获取已删除实体的键名,用于请求GTask中已删除的任务/文件夹 */ + public final static String GTASK_JSON_GET_DELETED = "get_deleted"; + + /** JSON中实体ID的键名,标识任务/文件夹在GTask中的唯一ID */ + public final static String GTASK_JSON_ID = "id"; + + /** JSON中排序索引的键名,标识任务/文件夹在列表中的位置(用于排序) */ + public final static String GTASK_JSON_INDEX = "index"; + + /** JSON中最后修改时间的键名,标识任务/文件夹的最近修改时间(用于同步冲突判断) */ + public final static String GTASK_JSON_LAST_MODIFIED = "last_modified"; + + /** JSON中最新同步点的键名,标识上次同步的时间点(用于增量同步) */ + public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point"; + + /** JSON中列表ID的键名,标识当前任务所属的列表ID */ + public final static String GTASK_JSON_LIST_ID = "list_id"; + + /** JSON中列表集合的键名,用于存储多个任务列表数据 */ + public final static String GTASK_JSON_LISTS = "lists"; + + /** JSON中名称的键名,标识任务/文件夹的名称 */ + public final static String GTASK_JSON_NAME = "name"; + + /** JSON中新ID的键名,用于标识创建操作后GTask返回的新实体ID */ + public final static String GTASK_JSON_NEW_ID = "new_id"; + + /** JSON中备注的键名,标识任务的备注内容 */ + public final static String GTASK_JSON_NOTES = "notes"; + + /** JSON中父节点ID的键名,标识当前实体的父节点ID(用于层级结构) */ + public final static String GTASK_JSON_PARENT_ID = "parent_id"; + + /** JSON中前序兄弟节点ID的键名,标识当前实体的前一个兄弟节点(用于排序) */ + public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id"; + + /** JSON中结果集合的键名,用于存储GTask返回的同步结果 */ + public final static String GTASK_JSON_RESULTS = "results"; + + /** JSON中源列表的键名,用于移动操作时指定源列表 */ + public final static String GTASK_JSON_SOURCE_LIST = "source_list"; + + /** JSON中任务集合的键名,用于存储多个任务数据 */ + public final static String GTASK_JSON_TASKS = "tasks"; + + /** JSON中类型的键名,与ENTITY_TYPE配合使用 */ + public final static String GTASK_JSON_TYPE = "type"; + + /** 实体类型:文件夹(分组),标识当前实体是GTask中的文件夹 */ + public final static String GTASK_JSON_TYPE_GROUP = "GROUP"; + + /** 实体类型:任务,标识当前实体是GTask中的任务 */ + public final static String GTASK_JSON_TYPE_TASK = "TASK"; + + /** JSON中用户信息的键名,标识当前同步的用户 */ + public final static String GTASK_JSON_USER = "user"; + + + // ========================== 小米便签专属文件夹标识 ========================== + /** 小米便签文件夹前缀,用于在GTask中区分小米便签创建的文件夹(避免与其他应用冲突) */ + public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]"; + + /** 小米便签默认文件夹名称,拼接前缀后为"[MIUI_Notes]Default" */ + public final static String FOLDER_DEFAULT = "Default"; + + /** 小米便签通话记录文件夹名称,拼接前缀后为"[MIUI_Notes]Call_Note" */ + public final static String FOLDER_CALL_NOTE = "Call_Note"; + + /** 小米便签元数据文件夹名称,用于存储便签的额外信息(如本地ID、附件信息等) */ + public final static String FOLDER_META = "METADATA"; + + + // ========================== 元数据相关键名 ========================== + /** 元数据中GTask ID的键名,用于存储实体在GTask中的ID */ + public final static String META_HEAD_GTASK_ID = "meta_gid"; + + /** 元数据中便签信息的键名,用于存储便签的核心信息(如ID、类型等) */ + public final static String META_HEAD_NOTE = "meta_note"; + + /** 元数据中数据列表的键名,用于存储便签的内容数据(如文本、附件路径等) */ + public final static String META_HEAD_DATA = "meta_data"; + + /** 元数据便签的名称,标识该便签为元数据(禁止用户修改或删除) */ + public final static String META_NOTE_NAME = "[META INFO] DON'T UPDATE AND DELETE"; + +} \ No newline at end of file diff --git a/src/新建文件夹/NoteEditActivity.java b/src/新建文件夹/NoteEditActivity.java new file mode 100644 index 0000000..e42e69c --- /dev/null +++ b/src/新建文件夹/NoteEditActivity.java @@ -0,0 +1,1161 @@ +package net.micode.notes.ui; + +import android.app.Activity; +import android.app.AlarmManager; +import android.app.AlertDialog; +import android.app.PendingIntent; +import android.app.SearchManager; +import android.appwidget.AppWidgetManager; +import android.content.ContentUris; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.Paint; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.text.Spannable; +import android.text.SpannableString; +import android.text.TextUtils; +import android.text.format.DateUtils; +import android.text.style.BackgroundColorSpan; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuItem; +import android.view.MotionEvent; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.WindowManager; +import android.widget.CheckBox; +import android.widget.CompoundButton; +import android.widget.CompoundButton.OnCheckedChangeListener; +import android.widget.EditText; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.TextView; +import android.widget.Toast; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.TextNote; +import net.micode.notes.model.WorkingNote; +import net.micode.notes.model.WorkingNote.NoteSettingChangedListener; +import net.micode.notes.tool.DataUtils; +import net.micode.notes.tool.ResourceParser; +import net.micode.notes.tool.ResourceParser.TextAppearanceResources; +import net.micode.notes.ui.DateTimePickerDialog.OnDateTimeSetListener; +import net.micode.notes.ui.NoteEditText.OnTextViewChangeListener; +import net.micode.notes.widget.NoteWidgetProvider_2x; +import net.micode.notes.widget.NoteWidgetProvider_4x; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + + +/** + * 笔记编辑活动类,负责笔记的创建、编辑、显示等核心功能 + * 实现了点击事件监听、笔记设置变化监听和文本视图变化监听接口 + */ +public class NoteEditActivity extends Activity implements OnClickListener, + NoteSettingChangedListener, OnTextViewChangeListener { + + /** + * 头部视图持有者类,用于缓存头部视图中的控件,优化性能 + */ + private class HeadViewHolder { + public TextView tvModified; // 显示笔记修改时间的文本视图 + public ImageView ivAlertIcon; // 提醒图标 + public TextView tvAlertDate; // 显示提醒日期的文本视图 + public ImageView ibSetBgColor; // 设置背景颜色的按钮 + } + + /** + * 背景颜色选择按钮映射表 + * 键:按钮资源ID,值:对应的背景颜色资源ID(来自ResourceParser) + */ + private static final Map sBgSelectorBtnsMap = new HashMap(); + static { + sBgSelectorBtnsMap.put(R.id.iv_bg_yellow, ResourceParser.YELLOW); + sBgSelectorBtnsMap.put(R.id.iv_bg_red, ResourceParser.RED); + sBgSelectorBtnsMap.put(R.id.iv_bg_blue, ResourceParser.BLUE); + sBgSelectorBtnsMap.put(R.id.iv_bg_green, ResourceParser.GREEN); + sBgSelectorBtnsMap.put(R.id.iv_bg_white, ResourceParser.WHITE); + } + + /** + * 背景颜色选择状态映射表 + * 键:背景颜色资源ID(来自ResourceParser),值:对应的选中状态图标资源ID + */ + private static final Map sBgSelectorSelectionMap = new HashMap(); + static { + sBgSelectorSelectionMap.put(ResourceParser.YELLOW, R.id.iv_bg_yellow_select); + sBgSelectorSelectionMap.put(ResourceParser.RED, R.id.iv_bg_red_select); + sBgSelectorSelectionMap.put(ResourceParser.BLUE, R.id.iv_bg_blue_select); + sBgSelectorSelectionMap.put(ResourceParser.GREEN, R.id.iv_bg_green_select); + sBgSelectorSelectionMap.put(ResourceParser.WHITE, R.id.iv_bg_white_select); + } + + /** + * 字体大小选择按钮映射表 + * 键:按钮资源ID,值:对应的字体大小资源ID(来自ResourceParser) + */ + private static final Map sFontSizeBtnsMap = new HashMap(); + static { + sFontSizeBtnsMap.put(R.id.ll_font_large, ResourceParser.TEXT_LARGE); + sFontSizeBtnsMap.put(R.id.ll_font_small, ResourceParser.TEXT_SMALL); + sFontSizeBtnsMap.put(R.id.ll_font_normal, ResourceParser.TEXT_MEDIUM); + sFontSizeBtnsMap.put(R.id.ll_font_super, ResourceParser.TEXT_SUPER); + } + + /** + * 字体大小选择状态映射表 + * 键:字体大小资源ID(来自ResourceParser),值:对应的选中状态图标资源ID + */ + private static final Map sFontSelectorSelectionMap = new HashMap(); + static { + sFontSelectorSelectionMap.put(ResourceParser.TEXT_LARGE, R.id.iv_large_select); + sFontSelectorSelectionMap.put(ResourceParser.TEXT_SMALL, R.id.iv_small_select); + 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; // 当前字体大小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; // 正则表达式模式(用于查询文本高亮) + + /** + * 活动创建时调用的方法 + * 初始化布局和活动状态 + */ + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + this.setContentView(R.layout.note_edit); // 设置布局文件 + + // 如果没有保存的状态,且初始化活动状态失败,则结束活动 + if (savedInstanceState == null && !initActivityState(getIntent())) { + finish(); + return; + } + initResources(); // 初始化资源和视图 + } + + /** + * 当活动从保存的状态恢复时调用 + * 用于在内存不足导致活动被销毁后,恢复之前的状态 + */ + @Override + protected void onRestoreInstanceState(Bundle savedInstanceState) { + super.onRestoreInstanceState(savedInstanceState); + // 如果保存的状态中包含笔记ID,则恢复对应的笔记 + if (savedInstanceState != null && savedInstanceState.containsKey(Intent.EXTRA_UID)) { + Intent intent = new Intent(Intent.ACTION_VIEW); + intent.putExtra(Intent.EXTRA_UID, savedInstanceState.getLong(Intent.EXTRA_UID)); + // 如果恢复状态失败,则结束活动 + if (!initActivityState(intent)) { + finish(); + return; + } + Log.d(TAG, "Restoring from killed activity"); + } + } + + /** + * 初始化活动状态,根据传入的意图处理笔记的加载或创建 + * @param intent 传入的意图,包含操作类型和相关数据 + * @return 初始化成功返回true,否则返回false + */ + private boolean initActivityState(Intent intent) { + /** + * 如果用户指定了查看操作(ACTION_VIEW)但未提供笔记ID, + * 则跳转到笔记列表活动 + */ + mWorkingNote = null; + // 处理查看已有笔记的操作 + if (TextUtils.equals(Intent.ACTION_VIEW, intent.getAction())) { + long noteId = intent.getLongExtra(Intent.EXTRA_UID, 0); + mUserQuery = ""; + + /** + * 从搜索结果启动的情况 + */ + 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); + showToast(R.string.error_note_not_exist); + finish(); + return false; + } else { + // 加载笔记 + mWorkingNote = WorkingNote.load(this, noteId); + if (mWorkingNote == null) { + Log.e(TAG, "load note failed with note id" + noteId); + finish(); + 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())) { + // 新笔记 + long folderId = intent.getLongExtra(Notes.INTENT_EXTRA_FOLDER_ID, 0); + int widgetId = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_ID, + AppWidgetManager.INVALID_APPWIDGET_ID); + int widgetType = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, + Notes.TYPE_WIDGET_INVALIDE); + int bgResId = intent.getIntExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, + ResourceParser.getDefaultBgId(this)); + + // 解析通话记录笔记 + String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER); + long callDate = intent.getLongExtra(Notes.INTENT_EXTRA_CALL_DATE, 0); + if (callDate != 0 && phoneNumber != null) { + if (TextUtils.isEmpty(phoneNumber)) { + 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); + if (mWorkingNote == null) { + Log.e(TAG, "load call note failed with note id" + noteId); + finish(); + return false; + } + } else { + // 创建新的通话记录笔记 + mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId, + widgetType, bgResId); + mWorkingNote.convertToCallNote(phoneNumber, callDate); + } + } else { + // 创建普通空笔记 + mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId, widgetType, + bgResId); + } + + // 设置软键盘状态:可见且调整布局大小 + getWindow().setSoftInputMode( + WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE + | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); + } else { + Log.e(TAG, "Intent not specified action, should not support"); + finish(); + return false; + } + // 设置笔记设置变化监听器 + mWorkingNote.setOnSettingStatusChangedListener(this); + return true; + } + + /** + * 活动恢复时调用的方法 + * 初始化笔记显示界面 + */ + @Override + protected void onResume() { + super.onResume(); + 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: 添加设置提醒的菜单。目前禁用,因为DateTimePicker尚未准备好 + */ + showAlertHeader(); // 显示提醒信息 + } + + /** + * 显示提醒头部信息 + * 根据提醒时间是否过期显示不同内容 + */ + private void showAlertHeader() { + if (mWorkingNote.hasClockAlert()) { + long time = System.currentTimeMillis(); + if (time > mWorkingNote.getAlertDate()) { + mNoteHeaderHolder.tvAlertDate.setText(R.string.note_alert_expired); // 提醒已过期 + } else { + // 显示相对时间(如"30分钟后") + mNoteHeaderHolder.tvAlertDate.setText(DateUtils.getRelativeTimeSpanString( + mWorkingNote.getAlertDate(), time, DateUtils.MINUTE_IN_MILLIS)); + } + mNoteHeaderHolder.tvAlertDate.setVisibility(View.VISIBLE); + mNoteHeaderHolder.ivAlertIcon.setVisibility(View.VISIBLE); + } else { + // 没有提醒时隐藏相关视图 + mNoteHeaderHolder.tvAlertDate.setVisibility(View.GONE); + mNoteHeaderHolder.ivAlertIcon.setVisibility(View.GONE); + }; + } + + /** + * 当活动收到新的意图时调用 + * 重新初始化活动状态 + */ + @Override + protected void onNewIntent(Intent intent) { + super.onNewIntent(intent); + initActivityState(intent); + } + + /** + * 当活动状态需要保存时调用 + * 保存当前正在编辑的笔记ID + */ + @Override + protected void onSaveInstanceState(Bundle outState) { + super.onSaveInstanceState(outState); + /** + * 对于没有ID的新笔记,应先保存以生成ID。 + * 如果编辑的笔记不值得保存,则没有ID,相当于创建新笔记 + */ + if (!mWorkingNote.existInDatabase()) { + saveNote(); + } + outState.putLong(Intent.EXTRA_UID, mWorkingNote.getNoteId()); + Log.d(TAG, "Save working note id: " + mWorkingNote.getNoteId() + " onSaveInstanceState"); + } + + /** + * 分发触摸事件 + * 用于处理背景颜色选择器和字体大小选择器的点击外部关闭逻辑 + */ + @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); + return true; + } + return super.dispatchTouchEvent(ev); + } + + /** + * 判断触摸事件是否在指定视图范围内 + * @param view 目标视图 + * @param ev 触摸事件 + * @return 触摸点在视图范围内返回true,否则返回false + */ + private boolean inRangeOfView(View view, MotionEvent ev) { + int []location = new int[2]; + view.getLocationOnScreen(location); // 获取视图在屏幕上的位置 + int x = location[0]; + int y = location[1]; + // 判断触摸点是否在视图的边界内 + if (ev.getX() < x + || ev.getX() > (x + view.getWidth()) + || ev.getY() < y + || ev.getY() > (y + view.getHeight())) { + return false; + } + return true; + } + /** + * 初始化界面资源和视图组件 + * 包括标题栏、编辑器、背景颜色选择器、字体大小选择器等 + */ + private void initResources() { + // 获取标题栏面板视图 + mHeadViewPanel = findViewById(R.id.note_title); + // 初始化标题栏视图持有者 + mNoteHeaderHolder = new HeadViewHolder(); + mNoteHeaderHolder.tvModified = (TextView) findViewById(R.id.tv_modified_date); // 最后修改时间文本 + mNoteHeaderHolder.ivAlertIcon = (ImageView) findViewById(R.id.iv_alert_icon); // 提醒图标 + mNoteHeaderHolder.tvAlertDate = (TextView) findViewById(R.id.tv_alert_date); // 提醒日期文本 + mNoteHeaderHolder.ibSetBgColor = (ImageView) findViewById(R.id.btn_set_bg_color); // 设置背景颜色按钮 + mNoteHeaderHolder.ibSetBgColor.setOnClickListener(this); // 绑定点击事件 + + // 获取笔记编辑器和其容器 + 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); + }; + + // 获取SharedPreferences用于存储字体大小设置 + mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); + // 从SharedPreferences读取保存的字体大小ID,默认使用默认字体大小 + mFontSizeId = mSharedPrefs.getInt(PREFERENCE_FONT_SIZE, ResourceParser.BG_DEFAULT_FONT_SIZE); + /** + * 修复SharedPreferences中存储的资源ID可能超出资源长度的问题 + * 若超出则使用默认字体大小 + */ + 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; + } + + // 传入小部件ID并发送广播 + 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); + // 更新笔记的背景颜色ID + mWorkingNote.setBgColorId(sBgSelectorBtnsMap.get(id)); + // 隐藏背景颜色选择器 + mNoteBgColorSelector.setVisibility(View.GONE); + } + // 处理字体大小选择器中的按钮点击 + else if (sFontSizeBtnsMap.containsKey(id)) { + // 隐藏之前选中的字体大小指示器 + findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.GONE); + // 更新字体大小ID并保存到SharedPreferences + 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(); + } + + /** + * 清除设置面板的显示状态 + * 隐藏背景颜色选择器和字体大小选择器 + * @return 若有面板被隐藏则返回true,否则返回false + */ + 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(); + } + + /** + * 分享笔记内容到其他应用 + * 通过ACTION_SEND意图分享纯文本内容 + * @param context 上下文 + * @param info 要分享的文本内容 + */ + 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() { + // 保存当前编辑的笔记 + saveNote(); + + // 安全起见,关闭当前活动并启动新的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(); + // 检查笔记ID是否有效 + 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); + } + + /** + * 判断是否处于同步模式 + * @return 若设置了同步账户则返回true,否则返回false + */ + private boolean isSyncMode() { + return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; + } + + /** + * 提醒时间改变时调用 + * 处理闹钟的设置或取消 + * @param date 提醒时间戳 + * @param set 是否设置提醒(true为设置,false为取消) + */ + public void onClockAlertChanged(long date, boolean set) { + /** + * 用户可能为未保存的笔记设置提醒,因此在设置前需先保存笔记 + */ + if (!mWorkingNote.existInDatabase()) { + saveNote(); + } + // 笔记ID有效时处理闹钟 + 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 { + /** + * 若用户未输入内容(笔记未保存),无有效ID,提示用户输入内容 + */ + Log.e(TAG, "Clock alert setting error"); + showToast(R.string.error_note_empty_for_clock); + } + } + + /** + * 小部件改变时调用 + * 触发小部件更新 + */ + public void onWidgetChanged() { + updateWidget(); + } + + /** + * 处理编辑框删除事件(清单模式下) + * @param index 要删除的编辑框索引 + * @param text 被删除的文本内容 + */ + 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); + } + + /** + * 处理编辑框回车事件(清单模式下) + * 在当前位置插入新的编辑框 + * @param index 当前编辑框索引 + * @param text 编辑框中的文本内容 + */ + public void onEditTextEnter(int index, String text) { + /** + * 理论上不会发生,用于调试检查 + */ + 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); + } + } + + /** + * 切换到清单模式 + * 将普通文本按换行分割为多个清单项 + * @param text 要转换的文本内容 + */ + 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); + } + + /** + * 高亮显示查询结果 + * 对文本中与查询词匹配的部分设置背景色 + * @param fullText 完整文本 + * @param userQuery 用户查询词 + * @return 处理后的带高亮效果的文本 + */ + 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; + } + /** + * 创建并返回列表模式下的列表项视图 + * @param item 列表项的文本内容 + * @param index 列表项的索引位置 + * @return 构建好的列表项视图 + */ + 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; + } + + /** + * 文本内容变化时回调(控制复选框显示/隐藏) + * @param index 列表项索引 + * @param hasText 文本是否有内容 + */ + 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); + } + } + + /** + * 检查列表模式切换时的处理 + * @param oldMode 旧模式 + * @param newMode 新模式 + */ + 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); + } + } + + /** + * 获取当前编辑的文本内容(根据模式处理) + * @return 是否包含已勾选的列表项 + */ + 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; + } + + /** + * 保存笔记内容 + * @return 是否保存成功 + */ + private boolean saveNote() { + // 先获取当前编辑的内容 + getWorkingText(); + // 保存笔记 + boolean saved = mWorkingNote.saveNote(); + if (saved) { + /** + * 从列表页进入编辑页有两种模式: + * 1. 打开已有笔记:返回时需要定位到原位置 + * 2. 创建新笔记:返回时需要定位到列表顶部 + * 通过设置RESULT_OK标识当前是创建/编辑状态 + */ + setResult(RESULT_OK); + } + return saved; + } + + /** + * 将笔记发送到桌面(创建快捷方式) + */ + private void sendToDesktop() { + /** + * 发送到桌面之前确保笔记已保存到数据库 + * 对于新笔记,先执行保存操作 + */ + if (!mWorkingNote.existInDatabase()) { + saveNote(); + } + + // 笔记ID有效时创建快捷方式 + 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 { + /** + * 处理异常情况:用户未输入内容(笔记未保存) + * 此时无有效笔记ID,提示用户输入内容 + */ + Log.e(TAG, "Send to desktop error"); + showToast(R.string.error_note_empty_for_send_to_desktop); + } + } + + /** + * 生成快捷方式图标标题(处理特殊前缀并限制长度) + * @param content 笔记内容 + * @return 处理后的标题 + */ + 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; + } + + /** + * 显示短时长提示信息 + * @param resId 字符串资源ID + */ + private void showToast(int resId) { + showToast(resId, Toast.LENGTH_SHORT); + } + + /** + * 显示指定时长的提示信息 + * @param resId 字符串资源ID + * @param duration 时长(Toast.LENGTH_SHORT/Toast.LENGTH_LONG) + */ + private void showToast(int resId, int duration) { + Toast.makeText(this, resId, duration).show(); + } +} \ No newline at end of file diff --git a/src/新建文件夹/NoteEditText.java b/src/新建文件夹/NoteEditText.java new file mode 100644 index 0000000..bfcb48d --- /dev/null +++ b/src/新建文件夹/NoteEditText.java @@ -0,0 +1,288 @@ +/* + * 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. + */ + +package net.micode.notes.ui; + +import android.content.Context; +import android.graphics.Rect; +import android.text.Layout; +import android.text.Selection; +import android.text.Spanned; +import android.text.TextUtils; +import android.text.style.URLSpan; +import android.util.AttributeSet; +import android.util.Log; +import android.view.ContextMenu; +import android.view.KeyEvent; +import android.view.MenuItem; +import android.view.MenuItem.OnMenuItemClickListener; +import android.view.MotionEvent; +import android.widget.EditText; + +import net.micode.notes.R; + +import java.util.HashMap; +import java.util.Map; + +/** + * 小米便签的自定义文本输入控件,继承自EditText,扩展了便签编辑的核心交互功能 + * 支持多输入框管理、链接识别与交互、精确光标定位等 + */ +public class NoteEditText extends EditText { + private static final String TAG = "NoteEditText"; + // 当前输入框在多输入框列表中的索引(用于区分不同输入框) + private int mIndex; + // 记录删除键按下前的光标起始位置(用于判断是否删除当前输入框) + private int mSelectionStartBeforeDelete; + + // 支持的链接协议常量 + private static final String SCHEME_TEL = "tel:" ; // 电话协议(如"tel:10086") + private static final String SCHEME_HTTP = "http:" ; // 网页协议(如"http://www.micode.net") + private static final String SCHEME_EMAIL = "mailto:" ; // 邮件协议(如"mailto:test@micode.net") + + // 链接协议与对应菜单资源的映射(用于上下文菜单显示对应操作文字) + 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); // 邮件链接对应"发送邮件"菜单 + } + + /** + * 文本视图变化监听器,由{@link NoteEditActivity}实现,用于处理输入框的增删和文本状态变化 + */ + public interface OnTextViewChangeListener { + /** + * 当按下删除键且文本为空时,删除当前输入框 + * @param index 当前输入框的索引 + * @param text 当前输入框的文本内容 + */ + void onEditTextDelete(int index, String text); + + /** + * 当按下回车键时,在当前输入框后新增一个输入框 + * @param index 新增输入框的索引(当前索引+1) + * @param text 回车键后需要移动到新输入框的文本 + */ + void onEditTextEnter(int index, String text); + + /** + * 当文本内容变化时,通知是否显示输入框相关操作选项 + * @param index 当前输入框的索引 + * @param hasText 文本是否非空(用于控制操作选项的显示/隐藏) + */ + void onTextChange(int index, boolean hasText); + } + + // 文本变化监听器实例(由NoteEditActivity设置) + private OnTextViewChangeListener mOnTextViewChangeListener; + + /** + * 构造方法:初始化文本输入控件(仅上下文参数) + * @param context 上下文环境(如NoteEditActivity) + */ + public NoteEditText(Context context) { + super(context, null); + mIndex = 0; // 默认索引为0 + } + + /** + * 设置当前输入框在多输入框列表中的索引 + * @param index 输入框索引 + */ + public void setIndex(int index) { + mIndex = index; + } + + /** + * 设置文本变化监听器,关联到NoteEditActivity + * @param listener 实现了OnTextViewChangeListener的监听器 + */ + public void setOnTextViewChangeListener(OnTextViewChangeListener listener) { + mOnTextViewChangeListener = listener; + } + + /** + * 构造方法:初始化文本输入控件(上下文+属性集) + * @param context 上下文环境 + * @param attrs 布局中定义的属性集合 + */ + public NoteEditText(Context context, AttributeSet attrs) { + super(context, attrs, android.R.attr.editTextStyle); + } + + /** + * 构造方法:初始化文本输入控件(上下文+属性集+样式) + * @param context 上下文环境 + * @param attrs 属性集合 + * @param defStyle 默认样式 + */ + public NoteEditText(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + // TODO Auto-generated constructor stub + } + + /** + * 处理触摸事件,精确设置光标位置(根据触摸坐标计算光标应在的文本位置) + * @param event 触摸事件(包含触摸坐标等信息) + * @return 事件是否被处理 + */ + @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(); + y -= getTotalPaddingTop(); + x += getScrollX(); + y += getScrollY(); + + // 根据坐标获取对应的文本行和偏移量,设置光标位置 + Layout layout = getLayout(); + int line = layout.getLineForVertical(y); // 触摸点所在的文本行 + int off = layout.getOffsetForHorizontal(line, x); // 行内的水平偏移(光标位置) + Selection.setSelection(getText(), off); // 设置光标 + break; + } + return super.onTouchEvent(event); + } + + /** + * 处理键盘按下事件,记录删除键按下前的光标位置 + * @param keyCode 按键代码(如KEYCODE_DEL、KEYCODE_ENTER) + * @param event 键盘事件 + * @return 事件是否被处理 + */ + @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: + break; + } + return super.onKeyDown(keyCode, event); + } + + /** + * 处理键盘抬起事件,触发输入框增删逻辑 + * @param keyCode 按键代码 + * @param event 键盘事件 + * @return 事件是否被处理 + */ + @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()); + return true; + } + } else { + Log.d(TAG, "OnTextViewChangeListener was not seted"); + } + break; + case KeyEvent.KEYCODE_ENTER: + if (mOnTextViewChangeListener != null) { + // 处理回车键:将光标后的文本移至新输入框 + int selectionStart = getSelectionStart(); + String text = getText().subSequence(selectionStart, length()).toString(); // 光标后文本 + setText(getText().subSequence(0, selectionStart)); // 保留光标前文本 + mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text); // 通知新增输入框 + } else { + Log.d(TAG, "OnTextViewChangeListener was not seted"); + } + break; + default: + break; + } + return super.onKeyUp(keyCode, event); + } + + /** + * 处理焦点变化事件,通知监听器文本是否为空(用于控制操作选项显示) + * @param focused 是否获得焦点 + * @param direction 焦点移动方向 + * @param previouslyFocusedRect 上一个焦点区域 + */ + @Override + protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { + if (mOnTextViewChangeListener != null) { + // 失去焦点且文本为空时,通知无文本;否则通知有文本 + if (!focused && TextUtils.isEmpty(getText())) { + mOnTextViewChangeListener.onTextChange(mIndex, false); + } else { + mOnTextViewChangeListener.onTextChange(mIndex, true); + } + } + super.onFocusChanged(focused, direction, previouslyFocusedRect); + } + + /** + * 创建上下文菜单,识别选中的链接并显示对应操作选项(如拨打、打开网页) + * @param menu 上下文菜单实例 + */ + @Override + protected void onCreateContextMenu(ContextMenu menu) { + // 仅处理富文本中的链接 + if (getText() instanceof Spanned) { + int selStart = getSelectionStart(); + int selEnd = getSelectionEnd(); + int min = Math.min(selStart, selEnd); + int max = Math.max(selStart, selEnd); + + // 获取选中区域内的链接 + final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class); + if (urls.length == 1) { // 仅处理单个链接的情况 + int defaultResId = 0; + // 识别链接协议,匹配对应的菜单资源 + for(String schema: sSchemaActionResMap.keySet()) { + if(urls[0].getURL().indexOf(schema) >= 0) { + defaultResId = sSchemaActionResMap.get(schema); + break; + } + } + + // 未匹配到已知协议时,使用默认菜单文本 + if (defaultResId == 0) { + defaultResId = R.string.note_link_other; + } + + // 向菜单添加链接操作项,点击后触发链接的默认行为(如拨号、打开浏览器) + menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener( + new OnMenuItemClickListener() { + public boolean onMenuItemClick(MenuItem item) { + urls[0].onClick(NoteEditText.this); // 触发URLSpan的点击事件 + return true; + } + }); + } + } + super.onCreateContextMenu(menu); + } +} \ No newline at end of file diff --git a/src/新建文件夹/NoteItemData.java b/src/新建文件夹/NoteItemData.java new file mode 100644 index 0000000..8259487 --- /dev/null +++ b/src/新建文件夹/NoteItemData.java @@ -0,0 +1,319 @@ +/* + * 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. + */ + +package net.micode.notes.ui; + +import android.content.Context; +import android.database.Cursor; +import android.text.TextUtils; + +import net.micode.notes.data.Contact; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.tool.DataUtils; + + +/** + * 小米便签列表项的数据模型类,封装单个便签的核心信息及列表位置属性,用于支撑列表UI展示 + */ +public class NoteItemData { + // 数据库查询的列名数组,对应便签表的核心字段 + 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, // 桌面插件类型 + }; + + // 上述PROJECTION数组中各列的索引常量,用于从Cursor中提取数据 + 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; // 类型(Notes.TYPE_NOTE:便签;TYPE_FOLDER:文件夹等) + private int mWidgetId; // 关联的桌面插件ID(无则为无效值) + private int mWidgetType; // 桌面插件类型(无则为无效值) + private String mName; // 通话记录便签的联系人姓名(非通话记录则为空) + private String mPhoneNumber; // 通话记录便签的电话号码(非通话记录则为空) + + // 列表位置属性(用于UI背景样式适配) + 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); + mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN); + mHasAttachment = (cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0) ? true : false; + mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN); + 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)) { + mName = Contact.getContact(context, mPhoneNumber); // 获取联系人姓名 + if (mName == null) { + mName = mPhoneNumber; // 无联系人时显示电话号码 + } + } + } + + if (mName == null) { + mName = ""; + } + // 计算当前项在列表中的位置属性 + checkPostion(cursor); + } + + /** + * 判断当前项在游标中的位置,初始化位置属性(用于UI背景样式适配) + * @param cursor 数据库查询结果游标 + */ + private void checkPostion(Cursor cursor) { + mIsLastItem = cursor.isLast() ? true : false; // 是否为最后一项 + mIsFirstItem = cursor.isFirst() ? true : false; // 是否为第一项 + mIsOnlyOneItem = (cursor.getCount() == 1); // 是否为唯一一项 + + // 初始化文件夹后便签的位置属性 + mIsMultiNotesFollowingFolder = false; + mIsOneNoteFollowingFolder = false; + + // 若当前是便签项且不是第一项,检查前一项是否为文件夹 + if (mType == Notes.TYPE_NOTE && !mIsFirstItem) { + int position = cursor.getPosition(); + if (cursor.moveToPrevious()) { // 移动到前一项 + // 前一项是文件夹或系统文件夹 + if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER + || cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) { + // 若游标总数大于当前位置+1,说明文件夹后有多个便签 + if (cursor.getCount() > (position + 1)) { + mIsMultiNotesFollowingFolder = true; + } else { + // 否则文件夹后只有当前一个便签 + mIsOneNoteFollowingFolder = true; + } + } + // 移回原位置,避免游标错乱 + if (!cursor.moveToNext()) { + throw new IllegalStateException("cursor move to previous but can't move back"); + } + } + } + } + + /** + * 是否为文件夹后的唯一便签项 + */ + public boolean isOneFollowingFolder() { + return mIsOneNoteFollowingFolder; + } + + /** + * 是否为文件夹后的多个便签项之一 + */ + public boolean isMultiFollowingFolder() { + return mIsMultiNotesFollowingFolder; + } + + /** + * 是否为列表最后一项 + */ + public boolean isLast() { + return mIsLastItem; + } + + /** + * 获取通话记录便签的联系人姓名(非通话记录返回空) + */ + public String getCallName() { + return mName; + } + + /** + * 是否为列表第一项 + */ + public boolean isFirst() { + return mIsFirstItem; + } + + /** + * 是否为列表中唯一一项 + */ + public boolean isSingle() { + return mIsOnlyOneItem; + } + + /** + * 获取便签ID + */ + public long getId() { + return mId; + } + + /** + * 获取提醒时间(毫秒时间戳) + */ + public long getAlertDate() { + return mAlertDate; + } + + /** + * 获取创建时间(毫秒时间戳) + */ + public long getCreatedDate() { + return mCreatedDate; + } + + /** + * 是否有附件 + */ + public boolean hasAttachment() { + return mHasAttachment; + } + + /** + * 获取最后修改时间(毫秒时间戳) + */ + public long getModifiedDate() { + return mModifiedDate; + } + + /** + * 获取背景色ID + */ + public int getBgColorId() { + return mBgColorId; + } + + /** + * 获取所属文件夹ID + */ + public long getParentId() { + return mParentId; + } + + /** + * 获取文件夹包含的便签数量(仅文件夹类型有效) + */ + public int getNotesCount() { + return mNotesCount; + } + + /** + * 获取所属文件夹ID(与getParentId一致,兼容不同调用场景) + */ + public long getFolderId () { + return mParentId; + } + + /** + * 获取类型(便签/文件夹/系统文件夹) + */ + public int getType() { + return mType; + } + + /** + * 获取桌面插件类型 + */ + public int getWidgetType() { + return mWidgetType; + } + + /** + * 获取桌面插件ID + */ + public int getWidgetId() { + return mWidgetId; + } + + /** + * 获取内容摘要(文件夹名或便签内容片段) + */ + public String getSnippet() { + return mSnippet; + } + + /** + * 是否设置了提醒(提醒时间>0) + */ + public boolean hasAlert() { + return (mAlertDate > 0); + } + + /** + * 是否为通话记录便签(属于通话记录文件夹且有电话号码) + */ + public boolean isCallRecord() { + return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber)); + } + + /** + * 从游标中获取便签类型 + * @param cursor 数据库查询结果游标 + * @return 便签类型(Notes.TYPE_NOTE等) + */ + public static int getNoteType(Cursor cursor) { + return cursor.getInt(TYPE_COLUMN); + } +} \ No newline at end of file diff --git a/src/新建文件夹/NoteWidgetProvider.java b/src/新建文件夹/NoteWidgetProvider.java new file mode 100644 index 0000000..e953109 --- /dev/null +++ b/src/新建文件夹/NoteWidgetProvider.java @@ -0,0 +1,187 @@ +/* + * 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. + */ + +package net.micode.notes.widget; +import android.app.PendingIntent; +import android.appwidget.AppWidgetManager; +import android.appwidget.AppWidgetProvider; +import android.content.ContentValues; +import android.content.Context; +import android.content.Intent; +import android.database.Cursor; +import android.util.Log; +import android.widget.RemoteViews; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; +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, // 便签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"; + + /** + * 当小部件被删除时调用 + * 清除数据库中与该小部件关联的记录 + */ + @Override + public void onDeleted(Context context, int[] appWidgetIds) { + ContentValues values = new ContentValues(); + // 将小部件ID设为无效值 + values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); + for (int i = 0; i < appWidgetIds.length; i++) { + // 更新数据库中关联该小部件的便签记录 + context.getContentResolver().update(Notes.CONTENT_NOTE_URI, + values, + NoteColumns.WIDGET_ID + "=?", + new String[] { String.valueOf(appWidgetIds[i])}); + } + } + + /** + * 获取与指定小部件关联的便签信息 + * @param context 上下文 + * @param widgetId 小部件ID + * @return 包含便签信息的游标 + */ + private Cursor getNoteWidgetInfo(Context context, int widgetId) { + return context.getContentResolver().query(Notes.CONTENT_NOTE_URI, + PROJECTION, + // 查询条件:小部件ID匹配且不在回收站中 + NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>?", + new String[] { String.valueOf(widgetId), String.valueOf(Notes.ID_TRASH_FOLER) }, + null); + } + + /** + * 公开的更新方法,调用带隐私模式参数的私有更新方法 + */ + protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { + update(context, appWidgetManager, appWidgetIds, false); + } + + /** + * 核心更新方法,更新小部件的UI显示 + * @param context 上下文 + * @param appWidgetManager 小部件管理器 + * @param appWidgetIds 需要更新的小部件ID数组 + * @param privacyMode 是否隐私模式(隐藏内容) + */ + private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds, + boolean privacyMode) { + for (int i = 0; i < appWidgetIds.length; i++) { + // 只处理有效的小部件ID + if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) { + // 默认背景颜色ID + int bgId = ResourceParser.getDefaultBgId(context); + // 便签内容摘要 + String snippet = ""; + // 点击小部件时的跳转意图 + 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()) { + // 检查是否有多个便签关联到同一小部件(异常情况) + if (c.getCount() > 1) { + Log.e(TAG, "Multiple message with same widget id:" + appWidgetIds[i]); + c.close(); + return; + } + // 从游标中获取数据 + 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); // 新建便签 + } + + // 关闭游标释放资源 + if (c != null) { + c.close(); + } + + // 加载小部件布局 + RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId()); + // 设置背景图片 + rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId)); + intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId); + + // 创建点击事件的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 + * 由子类实现不同尺寸小部件的背景资源 + */ + protected abstract int getBgResourceId(int bgId); + + /** + * 抽象方法:获取布局ID + * 由子类实现不同尺寸小部件的布局文件 + */ + protected abstract int getLayoutId(); + + /** + * 抽象方法:获取小部件类型 + * 由子类定义具体的小部件类型(如2x、4x等) + */ + protected abstract int getWidgetType(); +} \ No newline at end of file diff --git a/src/新建文件夹/NoteWidgetProvider_2x.java b/src/新建文件夹/NoteWidgetProvider_2x.java new file mode 100644 index 0000000..f48b84b --- /dev/null +++ b/src/新建文件夹/NoteWidgetProvider_2x.java @@ -0,0 +1,76 @@ +/* + * 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. + */ + +package net.micode.notes.widget; + +import android.appwidget.AppWidgetManager; +import android.content.Context; + +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) { + // 调用父类的update方法执行通用更新逻辑(如查询数据、绑定事件) + super.update(context, appWidgetManager, appWidgetIds); + } + + /** + * 实现抽象方法,返回2x尺寸小部件的布局文件ID + * 布局文件定义了小部件的UI结构(如文本位置、背景容器等) + * @return 2x小部件布局ID(R.layout.widget_2x) + */ + @Override + protected int getLayoutId() { + return R.layout.widget_2x; + } + + /** + * 实现抽象方法,返回2x尺寸小部件的背景资源ID + * 根据便签的背景色ID(bgId)获取对应的2x尺寸背景图 + * @param bgId 便签背景色ID(如红色、黄色等) + * @return 2x小部件对应的背景资源ID + */ + @Override + protected int getBgResourceId(int bgId) { + // 通过资源解析工具获取2x尺寸的背景资源 + return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId); + } + + /** + * 实现抽象方法,返回2x尺寸小部件的类型标识 + * 用于系统区分不同尺寸的小部件,关联对应的数据和逻辑 + * @return 2x小部件类型标识(Notes.TYPE_WIDGET_2X) + */ + @Override + protected int getWidgetType() { + return Notes.TYPE_WIDGET_2X; + } +} \ No newline at end of file diff --git a/src/新建文件夹/NoteWidgetProvider_4x.java b/src/新建文件夹/NoteWidgetProvider_4x.java new file mode 100644 index 0000000..59bf459 --- /dev/null +++ b/src/新建文件夹/NoteWidgetProvider_4x.java @@ -0,0 +1,72 @@ +/* + * 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. + */ + +package net.micode.notes.widget; + +import android.appwidget.AppWidgetManager; +import android.content.Context; + +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 { + /** + * 当系统触发小部件更新时调用(如小部件添加到桌面、定时刷新) + * 调用父类的update方法,触发通用更新逻辑(查询便签数据、渲染视图等) + * @param context 应用上下文,用于访问资源和数据库 + * @param appWidgetManager 系统小部件管理器,负责更新小部件视图 + * @param appWidgetIds 需要更新的小部件ID数组 + */ + @Override + public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { + super.update(context, appWidgetManager, appWidgetIds); + } + + /** + * 提供4x尺寸小部件的布局文件ID + * 布局文件widget_4x.xml定义了该小部件的UI结构(如文本区域、背景容器等) + * @return 4x小部件的布局资源ID + */ + protected int getLayoutId() { + return R.layout.widget_4x; + } + + /** + * 根据背景ID(bgId)获取4x小部件对应的背景资源 + * 通过ResourceParser工具类解析,确保背景与便签设置的颜色一致 + * @param bgId 背景标识ID(如红色、蓝色等) + * @return 4x小部件的背景资源ID + */ + @Override + protected int getBgResourceId(int bgId) { + return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId); + } + + /** + * 返回4x小部件的类型标识,用于父类逻辑中区分小部件尺寸 + * 与Notes类中定义的TYPE_WIDGET_4X常量对应,确保数据关联正确 + * @return 4x小部件的类型标识 + */ + @Override + protected int getWidgetType() { + return Notes.TYPE_WIDGET_4X; + } +} \ No newline at end of file diff --git a/src/新建文件夹/NotesListActivity.java b/src/新建文件夹/NotesListActivity.java new file mode 100644 index 0000000..b80c6ad --- /dev/null +++ b/src/新建文件夹/NotesListActivity.java @@ -0,0 +1,1232 @@ +/* + * 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. + */ + +package net.micode.notes.ui; + +import android.app.Activity; +import android.app.AlertDialog; +import android.app.Dialog; +import android.appwidget.AppWidgetManager; +import android.content.AsyncQueryHandler; +import android.content.ContentResolver; +import android.content.ContentValues; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.database.Cursor; +import android.os.AsyncTask; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.text.Editable; +import android.text.TextUtils; +import android.text.TextWatcher; +import android.util.Log; +import android.view.ActionMode; +import android.view.ContextMenu; +import android.view.ContextMenu.ContextMenuInfo; +import android.view.Display; +import android.view.HapticFeedbackConstants; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuItem; +import android.view.MenuItem.OnMenuItemClickListener; +import android.view.MotionEvent; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.View.OnCreateContextMenuListener; +import android.view.View.OnTouchListener; +import android.view.inputmethod.InputMethodManager; +import android.widget.AdapterView; +import android.widget.AdapterView.OnItemClickListener; +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; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.gtask.remote.GTaskSyncService; +import net.micode.notes.model.WorkingNote; +import net.micode.notes.tool.BackupUtils; +import net.micode.notes.tool.DataUtils; +import net.micode.notes.tool.ResourceParser; +import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute; +import net.micode.notes.widget.NoteWidgetProvider_2x; +import net.micode.notes.widget.NoteWidgetProvider_4x; + +import java.io.BufferedReader; +import java.io.IOException; +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 MENU_FOLDER_DELETE = 0; + // 上下文菜单选项:查看文件夹 + private static final int MENU_FOLDER_VIEW = 1; + // 上下文菜单选项:重命名文件夹 + private static final int MENU_FOLDER_CHANGE_NAME = 2; + + // SharedPreferences键:记录是否已添加应用介绍笔记 + private static final String PREFERENCE_ADD_INTRODUCTION = "net.micode.notes.introduction"; + + /** + * 列表状态枚举: + * - NOTE_LIST:显示普通笔记列表(根目录) + * - SUB_FOLDER:显示子文件夹内容 + * - CALL_RECORD_FOLDER:显示通话记录文件夹内容 + */ + private enum ListEditState { + NOTE_LIST, SUB_FOLDER, CALL_RECORD_FOLDER + }; + + // 当前列表状态 + private ListEditState mState; + // 异步查询处理器,用于处理ContentProvider的查询操作(避免主线程阻塞) + private BackgroundQueryHandler mBackgroundQueryHandler; + // 笔记列表适配器,负责将数据绑定到ListView + private NotesListAdapter mNotesListAdapter; + // 笔记列表视图 + private ListView mNotesListView; + // 新建笔记按钮 + private Button mAddNewNote; + // 触摸事件分发标记:是否将事件分发给ListView + private boolean mDispatch; + // 触摸起始Y坐标(用于处理新建按钮的透明区域点击) + private int mOriginY; + // 分发给ListView的Y坐标(修正偏移后的坐标) + private int mDispatchY; + // 标题栏文本视图 + private TextView mTitleBar; + // 当前所在文件夹ID(默认根目录) + private long mCurrentFolderId; + // 内容解析器,用于操作ContentProvider + private ContentResolver mContentResolver; + // 多选模式回调,处理列表多选状态的逻辑 + private ModeCallback mModeCallBack; + // 日志标记 + private static final String TAG = "NotesListActivity"; + // 列表滚动速率 + public static final int NOTES_LISTVIEW_SCROLL_RATE = 30; + // 当前聚焦的笔记数据项(用于上下文操作) + private NoteItemData mFocusNoteDataItem; + + // 普通文件夹查询条件:按父文件夹ID筛选 + private static final String NORMAL_SELECTION = NoteColumns.PARENT_ID + "=?"; + // 根目录查询条件: + // 1. 非系统类型且父ID为根目录的项 + // 2. 通话记录文件夹且包含笔记的项 + 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; + @Override + /** + * Activity创建时调用的生命周期方法,用于初始化界面和数据 + * @param savedInstanceState 保存的实例状态,用于恢复数据(如屏幕旋转时) + */ + /*Bundle 是一个专门用于存储和传递键值对数据的核心类,设计初衷是为了解决组件间的数据交互问题,尤其适合在生命周期变化时暂存和传递数据*/ + protected void onCreate(Bundle savedInstanceState) { + // 调用父类Activity的onCreate方法,完成基础初始化 + super.onCreate(savedInstanceState); + // 设置当前Activity的布局文件为note_list.xml + // (布局文件定义了便签列表的UI结构,如ListView、添加按钮等) + setContentView(R.layout.note_list); + // 初始化界面资源和成员变量(如列表视图、适配器、事件监听器等) + initResources(); + + /** + * 当用户首次使用应用时,插入一条介绍性便签 + * (引导用户了解应用功能,仅在首次启动时执行) + */ + 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); + } else { + super.onActivityResult(requestCode, resultCode, data); + } + } + + /** + * 首次启动应用时,从raw资源读取引导文本并创建引导便签 + * 仅在用户第一次打开应用时执行,通过SharedPreferences标记避免重复创建 + */ + private void setAppInfoFromRawRes() { + SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); + + // 检查是否已添加过引导便签(通过PREFERENCE_ADD_INTRODUCTION标记判断) + // 若为false,说明是首次使用,需要创建引导便签 + if (!sp.getBoolean(PREFERENCE_ADD_INTRODUCTION, false)) { + // 用于拼接读取到的引导文本内容 + /*StringBuilder 是 Java 中用于动态拼接字符串的类,属于 java.lang 包*/ + StringBuilder sb = new StringBuilder(); + // 输入流,用于读取raw资源文件,InputStream 是 Java 中处理字节输入流的抽象类,属于 java.io 包 + InputStream in = null; + + try { + // 打开raw目录下的introduction文件(引导文本内容) + in = getResources().openRawResource(R.raw.introduction); + + // 若文件打开成功 + if (in != null) { + // 构建字符输入流(指定默认编码) + InputStreamReader isr = new InputStreamReader(in); + // 缓冲字符流,提高读取效率 + BufferedReader br = new BufferedReader(isr); + // 缓冲区,每次读取1024个字符 + char [] buf = new char[1024]; + // 记录每次读取的字符长度 + int len = 0; + + // 循环读取文件内容,直到末尾(len=-1时结束) + while ((len = br.read(buf)) > 0) { + // 将读取到的字符追加到字符串构建器 + sb.append(buf, 0, len); + } + } else { + // 文件打开失败时记录错误日志并返回 + Log.e(TAG, "Read introduction file error"); + return; + } + } catch (IOException e) { + // 读取过程中发生IO异常时,打印堆栈信息并返回 + e.printStackTrace(); + return; + } finally { + // 确保输入流最终被关闭,释放资源 + if(in != null) { + try { + in.close(); + } catch (IOException e) { + // 关闭流时发生异常,打印堆栈信息 + e.printStackTrace(); + } + } + } + + // 创建一个空便签对象 + // 参数说明: + // - 上下文:当前Activity + // - 父文件夹ID:根目录(Notes.ID_ROOT_FOLDER) + // - 桌面部件ID:无效(因为不是桌面部件生成的便签) + // - 部件类型:无效 + // - 背景色:红色(ResourceParser.RED) + 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"); + return; + } + } + } + + @Override + + protected void onStart() { + // 调用父类的onStart()方法,确保Activity生命周期的正常执行 + super.onStart(); + // 启动异步查询笔记列表数据的操作 + startAsyncNotesListQuery(); + } + /** + * 初始化视图资源和监听器 + */ + private void initResources() { + mContentResolver = this.getContentResolver(); + mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver()); + 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); + // 设置列表项点击监听器 + mNotesListView.setOnItemClickListener(new OnListItemClickListener()); + // 设置列表项长按监听器 + 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; + + mTitleBar = (TextView) findViewById(R.id.tv_title_bar); + mState = ListEditState.NOTE_LIST; // 默认状态为普通笔记列表 + mModeCallBack = new ModeCallback(); // 初始化多选模式回调 + } + + /** + * 多选模式回调类,实现列表项的批量操作(删除、移动等) + */ + private class ModeCallback implements ListView.MultiChoiceModeListener, OnMenuItemClickListener { + private DropdownMenu mDropDownMenu; // 下拉菜单(全选/取消全选) + private ActionMode mActionMode; // 动作模式实例 + private MenuItem mMoveMenu; // 移动菜单选项 + + /** + * 创建动作模式时调用,初始化菜单 + */ + 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) { + mMoveMenu.setVisible(false); + } else { + mMoveMenu.setVisible(true); + mMoveMenu.setOnMenuItemClickListener(this); + } + + mActionMode = mode; + mNotesListAdapter.setChoiceMode(true); // 适配器启用多选模式 + mNotesListView.setLongClickable(false); // 多选模式下禁用长按 + 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(){ + public boolean onMenuItemClick(MenuItem item) { + mNotesListAdapter.selectAll(!mNotesListAdapter.isAllSelected()); + updateMenu(); // 更新菜单状态 + return true; + } + }); + return true; + } + + /** + * 更新菜单状态(显示选中数量、切换全选/取消全选文本) + */ + private void updateMenu() { + int selectedCount = mNotesListAdapter.getSelectedCount(); + // 更新下拉菜单标题(显示选中数量) + 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()) { + item.setChecked(true); + item.setTitle(R.string.menu_deselect_all); + } else { + item.setChecked(false); + item.setTitle(R.string.menu_select_all); + } + } + } + + /** + * 准备动作模式时调用(未实现具体逻辑) + */ + public boolean onPrepareActionMode(ActionMode mode, Menu menu) { + return false; + } + + /** + * 动作项点击时调用(未实现具体逻辑) + */ + public boolean onActionItemClicked(ActionMode mode, MenuItem item) { + return false; + } + + /** + * 销毁动作模式时调用,恢复列表状态 + */ + public void onDestroyActionMode(ActionMode mode) { + mNotesListAdapter.setChoiceMode(false); // 关闭多选模式 + mNotesListView.setLongClickable(true); // 恢复长按功能 + mAddNewNote.setVisibility(View.VISIBLE); // 显示新建按钮 + } + + /** + * 结束动作模式 + */ + public void finishActionMode() { + 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), + Toast.LENGTH_SHORT).show(); + return true; + } + + 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); + builder.setMessage(getString(R.string.alert_message_delete_notes, + mNotesListAdapter.getSelectedCount())); + builder.setPositiveButton(android.R.string.ok, + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, + int which) { + batchDelete(); // 执行批量删除 + } + }); + builder.setNegativeButton(android.R.string.cancel, null); + builder.show(); + break; + case R.id.move: + startQueryDestinationFolders(); // 查询目标文件夹列表(用于移动笔记) + break; + default: + return false; + } + return true; + } + } + + /** + * 新建笔记按钮的触摸事件监听器,处理透明区域点击穿透到列表的逻辑 + */ + 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; // 按钮在屏幕中的起始Y坐标 + int eventY = start + (int) event.getY(); // 转换为屏幕坐标 + + // 子文件夹状态下,减去标题栏高度修正坐标 + if (mState == ListEditState.SUB_FOLDER) { + eventY -= mTitleBar.getHeight(); + start -= mTitleBar.getHeight(); + } + + /** + * 特殊处理:新建按钮的透明区域点击需要穿透到下方列表 + * 透明区域由公式 y = -0.12x + 94 界定(基于按钮局部坐标) + * 若点击位置在透明区域内,则将事件分发给ListView + */ + if (event.getY() < (event.getX() * (-0.12) + 94)) { + // 获取列表最后一个可见项 + View view = mNotesListView.getChildAt(mNotesListView.getChildCount() - 1 + - mNotesListView.getFooterViewsCount()); + // 检查点击位置是否在列表项范围内 + if (view != null && view.getBottom() > start + && (view.getTop() < (start + 94))) { + mOriginY = (int) event.getY(); + mDispatchY = eventY; + // 修正事件坐标为列表坐标系 + event.setLocation(event.getX(), mDispatchY); + mDispatch = true; // 标记需要分发事件 + return mNotesListView.dispatchTouchEvent(event); // 分发事件到列表 + } + } + break; + } + case MotionEvent.ACTION_MOVE: { + // 移动时持续分发事件 + if (mDispatch) { + mDispatchY += (int) event.getY() - mOriginY; + event.setLocation(event.getX(), mDispatchY); + return mNotesListView.dispatchTouchEvent(event); + } + break; + } + default: { + // 事件结束时分发最后一次事件并重置标记 + if (mDispatch) { + event.setLocation(event.getX(), mDispatchY); + mDispatch = false; + return mNotesListView.dispatchTouchEvent(event); + } + break; + } + } + return false; + } + + }; + + /** + * 启动异步查询加载笔记列表数据 + */ + private void startAsyncNotesListQuery() { + // 根据当前文件夹ID选择查询条件(根目录或普通文件夹) + String selection = (mCurrentFolderId == Notes.ID_ROOT_FOLDER) ? ROOT_FOLDER_SELECTION + : NORMAL_SELECTION; + // 发起异步查询 + mBackgroundQueryHandler.startQuery(FOLDER_NOTE_LIST_QUERY_TOKEN, null, + Notes.CONTENT_NOTE_URI, NoteItemData.PROJECTION, selection, new String[] { + String.valueOf(mCurrentFolderId) + }, NoteColumns.TYPE + " DESC," + NoteColumns.MODIFIED_DATE + " DESC"); + } + + /** + * 异步查询处理器,继承自AsyncQueryHandler,处理ContentProvider查询 + */ + private final class BackgroundQueryHandler extends AsyncQueryHandler { + public BackgroundQueryHandler(ContentResolver contentResolver) { + super(contentResolver); + } + + /** + * 查询完成时回调 + */ + @Override + protected void onQueryComplete(int token, Object cookie, Cursor cursor) { + switch (token) { + case FOLDER_NOTE_LIST_QUERY_TOKEN: + // 笔记列表查询完成,更新适配器数据 + mNotesListAdapter.changeCursor(cursor); + break; + case FOLDER_LIST_QUERY_TOKEN: + // 文件夹列表查询完成,显示文件夹选择菜单 + if (cursor != null && cursor.getCount() > 0) { + showFolderListMenu(cursor); + } else { + Log.e(TAG, "Query folder failed"); + } + break; + default: + return; + } + } + } + + /** + * 显示文件夹列表菜单(用于移动笔记时选择目标文件夹) + */ + private void showFolderListMenu(Cursor cursor) { + AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); + builder.setTitle(R.string.menu_title_select_folder); + final FoldersListAdapter adapter = new FoldersListAdapter(this, cursor); + // 设置适配器并处理选择事件 + builder.setAdapter(adapter, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + // 批量移动笔记到选中文件夹 + DataUtils.batchMoveToFolder(mContentResolver, + mNotesListAdapter.getSelectedItemIds(), adapter.getItemId(which)); + // 显示移动成功提示 + Toast.makeText( + NotesListActivity.this, + getString(R.string.format_move_notes_to_folder, + mNotesListAdapter.getSelectedCount(), + adapter.getFolderName(NotesListActivity.this, which)), + Toast.LENGTH_SHORT).show(); + mModeCallBack.finishActionMode(); // 结束多选模式 + } + }); + builder.show(); + } + + /** + * 新建笔记,跳转到编辑界面 + */ + private void createNewNote() { + Intent intent = new Intent(this, NoteEditActivity.class); + intent.setAction(Intent.ACTION_INSERT_OR_EDIT); + intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mCurrentFolderId); // 传递当前文件夹ID + this.startActivityForResult(intent, REQUEST_CODE_NEW_NODE); + } + + /** + * 批量删除笔记 + */ + private void batchDelete() { + new AsyncTask>() { + protected HashSet doInBackground(Void... unused) { + // 获取选中项关联的 widget 信息 + HashSet widgets = mNotesListAdapter.getSelectedWidget(); + if (!isSyncMode()) { + // 非同步模式:直接删除笔记 + if (DataUtils.batchDeleteNotes(mContentResolver, mNotesListAdapter + .getSelectedItemIds())) { + } else { + Log.e(TAG, "Delete notes error, should not happens"); + } + } else { + // 同步模式:将笔记移动到回收站 + if (!DataUtils.batchMoveToFolder(mContentResolver, mNotesListAdapter + .getSelectedItemIds(), Notes.ID_TRASH_FOLER)) { + Log.e(TAG, "Move notes to trash folder error, should not happens"); + } + } + return widgets; + } + + @Override + protected void onPostExecute(HashSet widgets) { + // 批量删除操作执行完成后回调 + if (widgets != null) { + // 遍历相关小部件并更新 + for (AppWidgetAttribute widget : widgets) { + // 校验小部件ID和类型有效性 + if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID + && widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) { + updateWidget(widget.widgetId, widget.widgetType); + } + } + } + // 结束动作模式(如批量选择模式) + 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); + return; + } + + // 构建要删除的文件夹ID集合 + HashSet ids = new HashSet(); + ids.add(folderId); + // 获取该文件夹关联的小部件信息 + HashSet widgets = DataUtils.getFolderNoteWidget(mContentResolver, + folderId); + + if (!isSyncMode()) { + // 非同步模式下直接删除文件夹 + DataUtils.batchDeleteNotes(mContentResolver, ids); + } else { + // 同步模式下将文件夹移到回收站 + 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) { + updateWidget(widget.widgetId, widget.widgetType); + } + } + } + } + + /** + * 打开笔记进行查看/编辑 + * @param data 笔记数据对象 + */ + private void openNode(NoteItemData data) { + Intent intent = new Intent(this, NoteEditActivity.class); + intent.setAction(Intent.ACTION_VIEW); + intent.putExtra(Intent.EXTRA_UID, data.getId()); + this.startActivityForResult(intent, REQUEST_CODE_OPEN_NODE); + } + + /** + * 打开文件夹,显示文件夹内的笔记 + * @param data 文件夹数据对象 + */ + private void openFolder(NoteItemData data) { + mCurrentFolderId = data.getId(); + // 异步查询文件夹内的笔记列表 + 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 { + mTitleBar.setText(data.getSnippet()); + } + mTitleBar.setVisibility(View.VISIBLE); + } + + /** + * 点击事件处理 + */ + public void onClick(View v) { + switch (v.getId()) { + case R.id.btn_new_note: + // 点击新建笔记按钮 + createNewNote(); + break; + default: + break; + } + } + + /** + * 显示软键盘 + */ + private void showSoftInput() { + InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); + if (inputMethodManager != null) { + inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); + } + } + + /** + * 隐藏软键盘 + * @param view 触发隐藏的视图 + */ + private void hideSoftInput(View view) { + InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); + inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0); + } + + /** + * 显示创建或修改文件夹的对话框 + * @param create true-创建文件夹,false-修改文件夹 + */ + 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(); // 显示软键盘 + + // 根据操作类型(创建/修改)初始化对话框 + if (!create) { + // 修改文件夹:设置当前文件夹名称 + if (mFocusNoteDataItem != null) { + etName.setText(mFocusNoteDataItem.getSnippet()); + builder.setTitle(getString(R.string.menu_folder_change_name)); + } else { + Log.e(TAG, "The long click data item is null"); + return; + } + } else { + // 创建文件夹:清空输入框 + etName.setText(""); + builder.setTitle(this.getString(R.string.menu_create_folder)); + } + + 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); // 取消时隐藏软键盘 + } + }); + + final Dialog dialog = builder.setView(view).show(); + final Button positive = (Button)dialog.findViewById(android.R.id.button1); + positive.setOnClickListener(new OnClickListener() { + public void onClick(View v) { + 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(); + values.put(NoteColumns.SNIPPET, name); + values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); + values.put(NoteColumns.LOCAL_MODIFIED, 1); // 标记为本地已修改 + mContentResolver.update(Notes.CONTENT_NOTE_URI, values, NoteColumns.ID + + "=?", new String[] { + String.valueOf(mFocusNoteDataItem.getId()) + }); + } + } else if (!TextUtils.isEmpty(name)) { + // 创建新文件夹 + ContentValues values = new ContentValues(); + values.put(NoteColumns.SNIPPET, name); + values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); + mContentResolver.insert(Notes.CONTENT_NOTE_URI, values); + } + dialog.dismiss(); + } + }); + + // 初始状态:输入框为空时禁用确定按钮 + if (TextUtils.isEmpty(etName.getText())) { + positive.setEnabled(false); + } + + // 监听输入框文本变化,控制确定按钮状态 + etName.addTextChangedListener(new TextWatcher() { + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + // 文本变化前回调(未实现) + } + + public void onTextChanged(CharSequence s, int start, int before, int count) { + // 文本变化时:为空则禁用按钮,否则启用 + if (TextUtils.isEmpty(etName.getText())) { + positive.setEnabled(false); + } else { + positive.setEnabled(true); + } + } + + public void afterTextChanged(Editable s) { + // 文本变化后回调(未实现) + } + }); + } + + /** + * 处理返回键事件 + */ + @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); // 显示新建笔记按钮 + mTitleBar.setVisibility(View.GONE); + startAsyncNotesListQuery(); // 重新查询数据 + break; + case NOTE_LIST: + // 根目录下直接返回 + 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) { + intent.setClass(this, NoteWidgetProvider_4x.class); + } else { + Log.e(TAG, "Unspported widget type"); + return; + } + + intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { + appWidgetId + }); + + sendBroadcast(intent); // 发送广播更新小部件 + setResult(RESULT_OK, intent); + } + + /** + * 文件夹长按菜单创建监听器 + */ + private final OnCreateContextMenuListener mFolderOnCreateContextMenuListener = new OnCreateContextMenuListener() { + public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { + if (mFocusNoteDataItem != null) { + menu.setHeaderTitle(mFocusNoteDataItem.getSnippet()); // 菜单标题设为文件夹名称 + // 添加菜单选项 + menu.add(0, MENU_FOLDER_VIEW, 0, R.string.menu_folder_view); // 查看 + menu.add(0, MENU_FOLDER_DELETE, 0, R.string.menu_folder_delete); // 删除 + menu.add(0, MENU_FOLDER_CHANGE_NAME, 0, R.string.menu_folder_change_name); // 重命名 + } + } + }; + + /** + * 上下文菜单关闭时回调 + */ + @Override + public void onContextMenuClosed(Menu menu) { + if (mNotesListView != null) { + // 清除列表的上下文菜单监听器,避免重复触发 + mNotesListView.setOnCreateContextMenuListener(null); + } + super.onContextMenuClosed(menu); + } + + /** + * 上下文菜单项选择事件处理 + */ + @Override + public boolean onContextItemSelected(MenuItem item) { + if (mFocusNoteDataItem == null) { + Log.e(TAG, "The long click data item is null"); + return false; + } + switch (item.getItemId()) { + case MENU_FOLDER_VIEW: + // 查看文件夹 + 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); + builder.setMessage(getString(R.string.alert_message_delete_folder)); + builder.setPositiveButton(android.R.string.ok, + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + deleteFolder(mFocusNoteDataItem.getId()); // 确认删除文件夹 + } + }); + builder.setNegativeButton(android.R.string.cancel, null); + builder.show(); + break; + case MENU_FOLDER_CHANGE_NAME: + // 修改文件夹名称 + showCreateOrModifyFolderDialog(false); + break; + default: + break; + } + + return true; + } + + /** + * 准备选项菜单(根据当前状态动态调整菜单) + */ + @Override + public boolean onPrepareOptionsMenu(Menu menu) { + menu.clear(); // 清空现有菜单 + // 根据当前界面状态加载对应的菜单资源 + if (mState == ListEditState.NOTE_LIST) { + getMenuInflater().inflate(R.menu.note_list, menu); + // 根据同步状态更新同步菜单的文本 + menu.findItem(R.id.menu_sync).setTitle( + GTaskSyncService.isSyncing() ? R.string.menu_sync_cancel : R.string.menu_sync); + } else if (mState == ListEditState.SUB_FOLDER) { + getMenuInflater().inflate(R.menu.sub_folder, menu); + } else if (mState == ListEditState.CALL_RECORD_FOLDER) { + getMenuInflater().inflate(R.menu.call_record_folder, menu); + } else { + Log.e(TAG, "Wrong state:" + mState); + } + return true; + } + + /** + * 选项菜单项选择事件处理 + */ + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case R.id.menu_new_folder: { + // 新建文件夹 + showCreateOrModifyFolderDialog(true); + break; + } + case R.id.menu_export_text: { + // 导出笔记为文本 + exportNoteToText(); + break; + } + case R.id.menu_sync: { + // 同步相关操作 + if (isSyncMode()) { + // 已开启同步模式:根据菜单文本判断是开始还是取消同步 + if (TextUtils.equals(item.getTitle(), getString(R.string.menu_sync))) { // 开始同步 + GTaskSyncService.startSync(this); + } else { + // 取消同步 + GTaskSyncService.cancelSync(this); + } + } else { + // 未开启同步模式:跳转到设置页面 + startPreferenceActivity(); + } + break; + } + case R.id.menu_setting: { + // 跳转到设置页面 + startPreferenceActivity(); + break; + } + case R.id.menu_new_note: { + // 新建笔记 + createNewNote(); + break; + } + case R.id.menu_search: + // 触发搜索功能 + onSearchRequested(); + break; + default: + break; + } + return true; + } + + /** + * 处理搜索请求 + */ + @Override + public boolean onSearchRequested() { + // 启动搜索功能,参数分别为:搜索内容、是否显示搜索框、额外数据、是否全局搜索 + startSearch(null, false, null /* appData */, false); + return true; + } + + /** + * 将笔记导出为文本文件 + */ + private void exportNoteToText() { + // 获取备份工具实例 + final BackupUtils backup = BackupUtils.getInstance(NotesListActivity.this); + // 异步执行导出操作 + new AsyncTask() { + + @Override + protected Integer doInBackground(Void... unused) { + // 后台执行导出逻辑 + return backup.exportToText(); + } + + @Override + protected void onPostExecute(Integer result) { + // 导出完成后根据结果显示对应对话框 + if (result == BackupUtils.STATE_SD_CARD_UNMOUONTED) { + // SD卡未挂载 + AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); + builder.setTitle(NotesListActivity.this + .getString(R.string.failed_sdcard_export)); + builder.setMessage(NotesListActivity.this + .getString(R.string.error_sdcard_unmounted)); + builder.setPositiveButton(android.R.string.ok, null); + builder.show(); + } else if (result == BackupUtils.STATE_SUCCESS) { + // 导出成功 + AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); + builder.setTitle(NotesListActivity.this + .getString(R.string.success_sdcard_export)); + builder.setMessage(NotesListActivity.this.getString( + R.string.format_exported_file_location, backup + .getExportedTextFileName(), backup.getExportedTextFileDir())); + builder.setPositiveButton(android.R.string.ok, null); + builder.show(); + } else if (result == BackupUtils.STATE_SYSTEM_ERROR) { + // 系统错误导致导出失败 + AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); + builder.setTitle(NotesListActivity.this + .getString(R.string.failed_sdcard_export)); + builder.setMessage(NotesListActivity.this + .getString(R.string.error_sdcard_export)); + builder.setPositiveButton(android.R.string.ok, null); + builder.show(); + } + } + + }.execute(); + } + + /** + * 判断是否处于同步模式(已设置同步账户) + * @return true-同步模式,false-非同步模式 + */ + private boolean isSyncMode() { + return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; + } + + /** + * 启动设置页面 + */ + private void startPreferenceActivity() { + // 确定启动上下文(父Activity或当前Activity) + 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(); + // 通知动作模式回调更新选择状态 + mModeCallBack.onItemCheckedStateChanged(null, position, id, + !mNotesListAdapter.isSelectedItem(position)); + } + return; + } + + // 根据当前界面状态处理点击 + switch (mState) { + case NOTE_LIST: + // 根目录下:点击文件夹则打开文件夹,点击笔记则打开笔记 + if (item.getType() == Notes.TYPE_FOLDER + || item.getType() == Notes.TYPE_SYSTEM) { + openFolder(item); + } else if (item.getType() == Notes.TYPE_NOTE) { + openNode(item); + } else { + Log.e(TAG, "Wrong note type in NOTE_LIST"); + } + break; + case SUB_FOLDER: + case CALL_RECORD_FOLDER: + // 子文件夹或通话记录文件夹下:点击笔记则打开笔记 + if (item.getType() == Notes.TYPE_NOTE) { + openNode(item); + } else { + Log.e(TAG, "Wrong note type in SUB_FOLDER"); + } + break; + default: + break; + } + } + } + + } + + /** + * 异步查询目标文件夹列表(用于移动笔记等操作) + */ + 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, + FoldersListAdapter.PROJECTION, + selection, + new String[] { + String.valueOf(Notes.TYPE_FOLDER), + String.valueOf(Notes.ID_TRASH_FOLER), + String.valueOf(mCurrentFolderId) + }, + 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); + } else { + 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/新建文件夹/NotesListAdapter.java b/src/新建文件夹/NotesListAdapter.java new file mode 100644 index 0000000..6ab7b8e --- /dev/null +++ b/src/新建文件夹/NotesListAdapter.java @@ -0,0 +1,259 @@ +/* + * 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. + */ + +package net.micode.notes.ui; + +import android.content.Context; +import android.database.Cursor; +import android.util.Log; +import android.view.View; +import android.view.ViewGroup; +import android.widget.CursorAdapter; + +import net.micode.notes.data.Notes; + +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; + + +/** + * 便签列表适配器,用于将便签数据与列表视图绑定,支持多选操作 + * 继承自CursorAdapter,通过Cursor获取数据库中的便签数据 + */ +public class NotesListAdapter extends CursorAdapter { + private static final String TAG = "NotesListAdapter"; + private Context mContext; // 上下文对象 + private HashMap mSelectedIndex; // 存储选中项的位置和状态 + private int mNotesCount; // 便签总数(不包含文件夹) + private boolean mChoiceMode; // 是否处于选择模式 + + /** + * 桌面插件属性封装类 + * 用于存储选中项中包含的桌面插件信息 + */ + public static class AppWidgetAttribute { + public int widgetId; // 插件ID + public int widgetType; // 插件类型 + }; + + /** + * 构造方法 + * @param context 上下文对象 + */ + public NotesListAdapter(Context context) { + super(context, null); + mSelectedIndex = new HashMap(); + mContext = context; + mNotesCount = 0; + } + + /** + * 创建新的列表项视图 + * @param context 上下文 + * @param cursor 数据游标 + * @param parent 父容器 + * @return 新创建的NotesListItem视图 + */ + @Override + public View newView(Context context, Cursor cursor, ViewGroup parent) { + return new NotesListItem(context); + } + + /** + * 绑定数据到列表项视图 + * @param view 列表项视图 + * @param context 上下文 + * @param cursor 数据游标 + */ + @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())); + } + } + + /** + * 设置指定位置的选中状态 + * @param position 列表项位置 + * @param checked 是否选中 + */ + public void setCheckedItem(final int position, final boolean checked) { + mSelectedIndex.put(position, checked); + notifyDataSetChanged(); // 通知列表刷新 + } + + /** + * 判断是否处于选择模式 + * @return 是否为选择模式 + */ + public boolean isInChoiceMode() { + return mChoiceMode; + } + + /** + * 设置选择模式 + * @param mode 选择模式开关 + */ + public void setChoiceMode(boolean mode) { + mSelectedIndex.clear(); // 清除选中状态 + mChoiceMode = mode; + } + + /** + * 全选或取消全选所有便签(仅对普通便签有效) + * @param checked 是否选中 + */ + 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); + } + } + } + } + + /** + * 获取所有选中项的ID集合 + * @return 选中项ID的HashSet + */ + public HashSet getSelectedItemIds() { + HashSet itemSet = new HashSet(); + for (Integer position : mSelectedIndex.keySet()) { + if (mSelectedIndex.get(position) == true) { + Long id = getItemId(position); + // 过滤根文件夹ID(不应被选中) + if (id == Notes.ID_ROOT_FOLDER) { + Log.d(TAG, "Wrong item id, should not happen"); + } else { + itemSet.add(id); + } + } + } + return itemSet; + } + + /** + * 获取所有选中项中的桌面插件属性 + * @return 插件属性的HashSet + */ + public HashSet getSelectedWidget() { + HashSet itemSet = new HashSet(); + for (Integer position : mSelectedIndex.keySet()) { + if (mSelectedIndex.get(position) == true) { + Cursor c = (Cursor) getItem(position); + if (c != null) { + AppWidgetAttribute widget = new AppWidgetAttribute(); + NoteItemData item = new NoteItemData(mContext, c); + widget.widgetId = item.getWidgetId(); + widget.widgetType = item.getWidgetType(); + itemSet.add(widget); + // 注意:此处不关闭游标,游标由适配器管理 + } else { + Log.e(TAG, "Invalid cursor"); + return null; + } + } + } + return itemSet; + } + + /** + * 获取选中项的数量 + * @return 选中项数量 + */ + public int getSelectedCount() { + Collection values = mSelectedIndex.values(); + if (null == values) { + return 0; + } + Iterator iter = values.iterator(); + int count = 0; + while (iter.hasNext()) { + if (true == iter.next()) { + count++; + } + } + return count; + } + + /** + * 判断是否所有便签都被选中 + * @return 是否全选 + */ + public boolean isAllSelected() { + int checkedCount = getSelectedCount(); + return (checkedCount != 0 && checkedCount == mNotesCount); + } + + /** + * 判断指定位置的项是否被选中 + * @param position 列表项位置 + * @return 是否选中 + */ + public boolean isSelectedItem(final int position) { + if (null == mSelectedIndex.get(position)) { + return false; + } + return mSelectedIndex.get(position); + } + + /** + * 当数据发生变化时回调,重新计算便签数量 + */ + @Override + protected void onContentChanged() { + super.onContentChanged(); + calcNotesCount(); + } + + /** + * 更换游标时回调,重新计算便签数量 + * @param cursor 新游标 + */ + @Override + public void changeCursor(Cursor cursor) { + super.changeCursor(cursor); + calcNotesCount(); + } + + /** + * 计算普通便签的总数(排除文件夹) + */ + private void calcNotesCount() { + mNotesCount = 0; + for (int i = 0; i < getCount(); i++) { + Cursor c = (Cursor) getItem(i); + if (c != null) { + // 仅统计类型为普通便签的项 + if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) { + mNotesCount++; + } + } else { + Log.e(TAG, "Invalid cursor"); + return; + } + } + } +} \ No newline at end of file diff --git a/src/新建文件夹/NotesListItem.java b/src/新建文件夹/NotesListItem.java new file mode 100644 index 0000000..e3fd735 --- /dev/null +++ b/src/新建文件夹/NotesListItem.java @@ -0,0 +1,169 @@ +/* + * 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. + */ + +package net.micode.notes.ui; + +import android.content.Context; +import android.text.format.DateUtils; +import android.view.View; +import android.widget.CheckBox; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.TextView; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.tool.DataUtils; +import net.micode.notes.tool.ResourceParser.NoteItemBgResources; + + +/** + * 小米便签列表中的单个项视图 + * 负责展示便签、文件夹或通话记录的内容及状态,支持多选模式 + */ +public class NotesListItem extends LinearLayout { + private ImageView mAlert; // 提醒图标(显示闹钟或通话记录图标) + private TextView mTitle; // 标题/内容文本(显示便签内容、文件夹名称等) + private TextView mTime; // 时间文本(显示最后修改时间) + private TextView mCallName; // 通话记录联系人名称(仅通话记录便签显示) + private NoteItemData mItemData; // 当前项对应的数据模型 + private CheckBox mCheckBox; // 多选模式下的复选框 + + /** + * 构造方法:初始化布局和控件 + * @param context 上下文对象 + */ + public NotesListItem(Context context) { + super(context); + // 加载列表项布局文件 + inflate(context, R.layout.note_item, this); + // 绑定UI控件 + mAlert = (ImageView) findViewById(R.id.iv_alert_icon); + mTitle = (TextView) findViewById(R.id.tv_title); + mTime = (TextView) findViewById(R.id.tv_time); + mCallName = (TextView) findViewById(R.id.tv_name); + mCheckBox = (CheckBox) findViewById(android.R.id.checkbox); + } + + /** + * 绑定数据到当前列表项,根据数据类型和模式展示不同样式 + * @param context 上下文对象 + * @param data 便签数据模型 + * @param choiceMode 是否处于多选模式 + * @param checked 多选模式下是否被选中 + */ + 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); + } else { + mCheckBox.setVisibility(View.GONE); + } + + mItemData = data; + + // 处理通话记录文件夹(特殊系统文件夹) + if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { + mCallName.setVisibility(View.GONE); + mAlert.setVisibility(View.VISIBLE); + mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); + // 显示文件夹名称和包含的便签数量 + mTitle.setText(context.getString(R.string.call_record_folder_name) + + 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); + mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); // 显示便签内容片段 + // 显示提醒图标(如有) + if (data.hasAlert()) { + mAlert.setImageResource(R.drawable.clock); + mAlert.setVisibility(View.VISIBLE); + } else { + mAlert.setVisibility(View.GONE); + } + + // 处理普通文件夹和普通便签 + } else { + mCallName.setVisibility(View.GONE); + 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); + mAlert.setVisibility(View.VISIBLE); + } else { + mAlert.setVisibility(View.GONE); + } + } + } + + // 显示最后修改时间(相对时间格式,如"1小时前") + mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate())); + + // 设置项背景样式 + setBackground(data); + } + + /** + * 根据便签类型和位置设置背景样式 + * @param data 便签数据模型 + */ + private void setBackground(NoteItemData data) { + int bgColorId = data.getBgColorId(); // 获取背景色ID + + // 普通便签:根据位置(首项/末项/单项等)设置不同背景 + if (data.getType() == Notes.TYPE_NOTE) { + if (data.isSingle() || data.isOneFollowingFolder()) { + // 单项或文件夹后的唯一便签 + setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(bgColorId)); + } else if (data.isLast()) { + // 列表中的最后一项 + setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(bgColorId)); + } else if (data.isFirst() || data.isMultiFollowingFolder()) { + // 首项或文件夹后的多个便签中的第一项 + setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(bgColorId)); + } else { + // 中间项 + setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(bgColorId)); + } + } else { + // 文件夹:使用固定的文件夹背景 + setBackgroundResource(NoteItemBgResources.getFolderBgRes()); + } + } + + /** + * 获取当前项的数据模型 + * @return 便签数据模型 + */ + public NoteItemData getItemData() { + return mItemData; + } +} \ No newline at end of file diff --git a/src/新建文件夹/NotesPreferenceActivity.java b/src/新建文件夹/NotesPreferenceActivity.java new file mode 100644 index 0000000..a5761bb --- /dev/null +++ b/src/新建文件夹/NotesPreferenceActivity.java @@ -0,0 +1,463 @@ +/* + * 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. + */ + +package net.micode.notes.ui; + +import android.accounts.Account; +import android.accounts.AccountManager; +import android.app.ActionBar; +import android.app.AlertDialog; +import android.content.BroadcastReceiver; +import android.content.ContentValues; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.preference.Preference; +import android.preference.Preference.OnPreferenceClickListener; +import android.preference.PreferenceActivity; +import android.preference.PreferenceCategory; +import android.text.TextUtils; +import android.text.format.DateFormat; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.Button; +import android.widget.TextView; +import android.widget.Toast; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.gtask.remote.GTaskSyncService; + + +/** + * 小米便签的设置页面 + * 负责账号管理、同步控制及偏好设置,支持便签数据同步功能 + */ +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; + + @Override + protected void onCreate(Bundle icicle) { + super.onCreate(icicle); + + // 设置ActionBar支持返回导航 + getActionBar().setDisplayHomeAsUpEnabled(true); + + // 加载偏好设置布局 + addPreferencesFromResource(R.xml.preferences); + // 获取账号设置分类 + mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY); + // 初始化广播接收器并注册,监听同步服务广播 + mReceiver = new GTaskReceiver(); + 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); + } + + @Override + protected void onResume() { + super.onResume(); + + // 如果检测到新添加的账号,自动设置为同步账号 + if (mHasAddedAccount) { + Account[] accounts = getGoogleAccounts(); + if (mOriAccounts != null && accounts.length > mOriAccounts.length) { + for (Account accountNew : accounts) { + boolean found = false; + for (Account accountOld : mOriAccounts) { + if (TextUtils.equals(accountOld.name, accountNew.name)) { + found = true; + break; + } + } + if (!found) { + setSyncAccount(accountNew.name); + break; + } + } + } + } + + // 刷新UI显示 + refreshUI(); + } + + @Override + protected void onDestroy() { + // 注销广播接收器 + if (mReceiver != null) { + unregisterReceiver(mReceiver); + } + super.onDestroy(); + } + + /** + * 加载账号设置项到偏好页面 + */ + private void loadAccountPreference() { + mAccountCategory.removeAll(); + + Preference accountPref = new Preference(this); + final String defaultAccount = getSyncAccountName(this); + accountPref.setTitle(getString(R.string.preferences_account_title)); + accountPref.setSummary(getString(R.string.preferences_account_summary)); + // 设置账号项点击事件 + accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() { + public boolean onPreferenceClick(Preference preference) { + if (!GTaskSyncService.isSyncing()) { + if (TextUtils.isEmpty(defaultAccount)) { + // 首次设置账号,显示账号选择对话框 + showSelectAccountAlertDialog(); + } else { + // 已设置账号,显示账号变更确认对话框 + showChangeAccountConfirmAlertDialog(); + } + } else { + // 同步中不允许变更账号 + Toast.makeText(NotesPreferenceActivity.this, + R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT) + .show(); + } + return true; + } + }); + + 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); + + // 设置同步按钮状态 + if (GTaskSyncService.isSyncing()) { + syncButton.setText(getString(R.string.preferences_button_sync_cancel)); + syncButton.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) { + // 取消同步 + GTaskSyncService.cancelSync(NotesPreferenceActivity.this); + } + }); + } else { + syncButton.setText(getString(R.string.preferences_button_sync_immediately)); + syncButton.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) { + // 立即同步 + GTaskSyncService.startSync(NotesPreferenceActivity.this); + } + }); + } + // 未设置账号时禁用同步按钮 + syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this))); + + // 设置最后同步时间显示 + if (GTaskSyncService.isSyncing()) { + lastSyncTimeView.setText(GTaskSyncService.getProgressString()); + lastSyncTimeView.setVisibility(View.VISIBLE); + } else { + long lastSyncTime = getLastSyncTime(this); + if (lastSyncTime != 0) { + lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time, + DateFormat.format(getString(R.string.preferences_last_sync_time_format), + lastSyncTime))); + lastSyncTimeView.setVisibility(View.VISIBLE); + } else { + lastSyncTimeView.setVisibility(View.GONE); + } + } + } + + /** + * 刷新整个UI界面 + */ + private void refreshUI() { + loadAccountPreference(); + loadSyncButton(); + } + + /** + * 显示账号选择对话框 + */ + 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)); + TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle); + subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips)); + dialogBuilder.setCustomTitle(titleView); + dialogBuilder.setPositiveButton(null, null); + + // 获取谷歌账号列表 + Account[] accounts = getGoogleAccounts(); + String defAccount = getSyncAccountName(this); + + mOriAccounts = accounts; + mHasAddedAccount = false; + + if (accounts.length > 0) { + CharSequence[] items = new CharSequence[accounts.length]; + final CharSequence[] itemMapping = items; + int checkedItem = -1; + int index = 0; + // 构建账号选择列表 + for (Account account : accounts) { + if (TextUtils.equals(account.name, defAccount)) { + checkedItem = index; + } + items[index++] = account.name; + } + // 设置单选列表点击事件 + dialogBuilder.setSingleChoiceItems(items, checkedItem, + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + setSyncAccount(itemMapping[which].toString()); + dialog.dismiss(); + refreshUI(); + } + }); + } + + // 添加"添加账号"选项 + View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null); + dialogBuilder.setView(addAccountView); + + final AlertDialog dialog = dialogBuilder.show(); + 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" + }); + startActivityForResult(intent, -1); + dialog.dismiss(); + } + }); + } + + /** + * 显示账号变更确认对话框 + */ + 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, + getSyncAccountName(this))); + TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle); + 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), + getString(R.string.preferences_menu_cancel) + }; + dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + if (which == 0) { + // 变更账号:显示账号选择对话框 + showSelectAccountAlertDialog(); + } else if (which == 1) { + // 移除账号 + removeSyncAccount(); + refreshUI(); + } + } + }); + dialogBuilder.show(); + } + + /** + * 获取设备上的谷歌账号列表 + * @return 谷歌账号数组 + */ + private Account[] getGoogleAccounts() { + AccountManager accountManager = AccountManager.get(this); + return accountManager.getAccountsByType("com.google"); + } + + /** + * 设置同步账号并更新本地数据 + * @param account 账号名称 + */ + 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) { + editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account); + } else { + editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); + } + editor.commit(); + + // 清除最后同步时间 + setLastSyncTime(this, 0); + + // 清除本地GTASK相关信息(异步执行) + new Thread(new Runnable() { + public void run() { + ContentValues values = new ContentValues(); + values.put(NoteColumns.GTASK_ID, ""); + values.put(NoteColumns.SYNC_ID, 0); + getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null); + } + }).start(); + + Toast.makeText(NotesPreferenceActivity.this, + getString(R.string.preferences_toast_success_set_accout, account), + Toast.LENGTH_SHORT).show(); + } + } + + /** + * 移除当前同步账号并清理数据 + */ + private void removeSyncAccount() { + SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); + SharedPreferences.Editor editor = settings.edit(); + if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) { + editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME); + } + if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) { + editor.remove(PREFERENCE_LAST_SYNC_TIME); + } + editor.commit(); + + // 清除本地GTASK相关信息(异步执行) + new Thread(new Runnable() { + public void run() { + ContentValues values = new ContentValues(); + values.put(NoteColumns.GTASK_ID, ""); + values.put(NoteColumns.SYNC_ID, 0); + getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null); + } + }).start(); + } + + /** + * 获取保存的同步账号名称 + * @param context 上下文 + * @return 账号名称,为空表示未设置 + */ + public static String getSyncAccountName(Context context) { + SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, + Context.MODE_PRIVATE); + return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); + } + + /** + * 保存最后同步时间 + * @param context 上下文 + * @param time 时间戳 + */ + public static void setLastSyncTime(Context context, long time) { + SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, + Context.MODE_PRIVATE); + SharedPreferences.Editor editor = settings.edit(); + editor.putLong(PREFERENCE_LAST_SYNC_TIME, time); + editor.commit(); + } + + /** + * 获取最后同步时间 + * @param context 上下文 + * @return 时间戳,0表示从未同步过 + */ + public static long getLastSyncTime(Context context) { + SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, + Context.MODE_PRIVATE); + return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0); + } + + /** + * 监听同步服务广播的接收器 + * 用于同步过程中更新UI状态 + */ + private class GTaskReceiver extends BroadcastReceiver { + + @Override + public void onReceive(Context context, Intent intent) { + // 刷新UI显示同步状态 + refreshUI(); + if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) { + TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview); + syncStatus.setText(intent + .getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG)); + } + + } + } + + /** + * 处理菜单选项点击事件 + */ + 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); + return true; + default: + return false; + } + } +} \ No newline at end of file diff --git a/src/新建文件夹/ResourceParser.java b/src/新建文件夹/ResourceParser.java new file mode 100644 index 0000000..af06daf --- /dev/null +++ b/src/新建文件夹/ResourceParser.java @@ -0,0 +1,272 @@ +/* + * 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. + */ + +package net.micode.notes.tool; + +import android.content.Context; +import android.preference.PreferenceManager; + +import net.micode.notes.R; +import net.micode.notes.ui.NotesPreferenceActivity; + +/** + * 资源解析器:统一管理便签应用中的各类资源(背景、文字样式等) + * 提供资源获取接口,实现样式资源与业务逻辑的解耦 + */ +public class ResourceParser { + + // 背景颜色常量定义(用于标识不同颜色主题) + public static final int YELLOW = 0; // 黄色背景 + public static final int BLUE = 1; // 蓝色背景 + public static final int WHITE = 2; // 白色背景 + public static final int GREEN = 3; // 绿色背景 + public static final int RED = 4; // 红色背景 + + public static final int BG_DEFAULT_COLOR = YELLOW; // 默认背景颜色(黄色) + + // 字体大小常量定义 + public static final int TEXT_SMALL = 0; // 小字体 + public static final int TEXT_MEDIUM = 1; // 中字体(默认) + public static final int TEXT_LARGE = 2; // 大字体 + public static final int TEXT_SUPER = 3; // 超大字体 + + public static final int BG_DEFAULT_FONT_SIZE = TEXT_MEDIUM; // 默认字体大小 + + /** + * 便签编辑页背景资源管理 + * 提供编辑页主体背景和标题栏背景的资源获取 + */ + public static class NoteBgResources { + // 编辑页主体背景资源数组(与颜色常量顺序对应) + private final static int [] BG_EDIT_RESOURCES = new int [] { + R.drawable.edit_yellow, // 黄色背景 + R.drawable.edit_blue, // 蓝色背景 + R.drawable.edit_white, // 白色背景 + R.drawable.edit_green, // 绿色背景 + R.drawable.edit_red // 红色背景 + }; + + // 编辑页标题栏背景资源数组(与颜色常量顺序对应) + private final static int [] BG_EDIT_TITLE_RESOURCES = new int [] { + R.drawable.edit_title_yellow, // 黄色标题栏 + R.drawable.edit_title_blue, // 蓝色标题栏 + R.drawable.edit_title_white, // 白色标题栏 + R.drawable.edit_title_green, // 绿色标题栏 + R.drawable.edit_title_red // 红色标题栏 + }; + + /** + * 获取便签编辑页主体背景资源 + * @param id 颜色标识(如YELLOW、BLUE等) + * @return 背景图片资源ID + */ + public static int getNoteBgResource(int id) { + return BG_EDIT_RESOURCES[id]; + } + + /** + * 获取便签编辑页标题栏背景资源 + * @param id 颜色标识(如YELLOW、BLUE等) + * @return 标题栏背景图片资源ID + */ + public static int getNoteTitleBgResource(int id) { + return BG_EDIT_TITLE_RESOURCES[id]; + } + } + + /** + * 获取默认背景颜色ID + * 根据用户设置判断:若开启随机背景,则返回随机颜色;否则返回默认黄色 + * @param context 上下文 + * @return 背景颜色标识 + */ + public static int getDefaultBgId(Context context) { + if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean( + NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) { + // 随机选择背景颜色(0到背景资源数量-1之间) + return (int) (Math.random() * NoteBgResources.BG_EDIT_RESOURCES.length); + } else { + // 返回默认背景色 + return BG_DEFAULT_COLOR; + } + } + + /** + * 便签列表项背景资源管理 + * 针对列表中不同位置的项(首项、中间项、末项、唯一项)提供对应的背景资源 + */ + public static class NoteItemBgResources { + // 列表首项背景资源数组 + private final static int [] BG_FIRST_RESOURCES = new int [] { + R.drawable.list_yellow_up, // 黄色首项 + R.drawable.list_blue_up, // 蓝色首项 + R.drawable.list_white_up, // 白色首项 + R.drawable.list_green_up, // 绿色首项 + R.drawable.list_red_up // 红色首项 + }; + + // 列表中间项背景资源数组 + private final static int [] BG_NORMAL_RESOURCES = new int [] { + R.drawable.list_yellow_middle, // 黄色中间项 + R.drawable.list_blue_middle, // 蓝色中间项 + R.drawable.list_white_middle, // 白色中间项 + R.drawable.list_green_middle, // 绿色中间项 + R.drawable.list_red_middle // 红色中间项 + }; + + // 列表末项背景资源数组 + private final static int [] BG_LAST_RESOURCES = new int [] { + R.drawable.list_yellow_down, // 黄色末项 + R.drawable.list_blue_down, // 蓝色末项 + R.drawable.list_white_down, // 白色末项 + R.drawable.list_green_down, // 绿色末项 + R.drawable.list_red_down, // 红色末项 + }; + + // 列表唯一项(仅一项时)背景资源数组 + private final static int [] BG_SINGLE_RESOURCES = new int [] { + R.drawable.list_yellow_single, // 黄色唯一项 + R.drawable.list_blue_single, // 蓝色唯一项 + R.drawable.list_white_single, // 白色唯一项 + R.drawable.list_green_single, // 绿色唯一项 + R.drawable.list_red_single // 红色唯一项 + }; + + /** + * 获取列表首项背景资源 + * @param id 颜色标识 + * @return 首项背景资源ID + */ + public static int getNoteBgFirstRes(int id) { + return BG_FIRST_RESOURCES[id]; + } + + /** + * 获取列表末项背景资源 + * @param id 颜色标识 + * @return 末项背景资源ID + */ + public static int getNoteBgLastRes(int id) { + return BG_LAST_RESOURCES[id]; + } + + /** + * 获取列表唯一项背景资源 + * @param id 颜色标识 + * @return 唯一项背景资源ID + */ + public static int getNoteBgSingleRes(int id) { + return BG_SINGLE_RESOURCES[id]; + } + + /** + * 获取列表中间项背景资源 + * @param id 颜色标识 + * @return 中间项背景资源ID + */ + public static int getNoteBgNormalRes(int id) { + return BG_NORMAL_RESOURCES[id]; + } + + /** + * 获取文件夹项背景资源 + * @return 文件夹背景资源ID + */ + public static int getFolderBgRes() { + return R.drawable.list_folder; + } + } + + /** + * 桌面小部件(Widget)背景资源管理 + * 提供不同尺寸Widget的背景资源 + */ + public static class WidgetBgResources { + // 2x尺寸Widget背景资源数组 + private final static int [] BG_2X_RESOURCES = new int [] { + R.drawable.widget_2x_yellow, // 2x黄色Widget + R.drawable.widget_2x_blue, // 2x蓝色Widget + R.drawable.widget_2x_white, // 2x白色Widget + R.drawable.widget_2x_green, // 2x绿色Widget + R.drawable.widget_2x_red, // 2x红色Widget + }; + + /** + * 获取2x尺寸Widget背景资源 + * @param id 颜色标识 + * @return 2x Widget背景资源ID + */ + public static int getWidget2xBgResource(int id) { + return BG_2X_RESOURCES[id]; + } + + // 4x尺寸Widget背景资源数组 + private final static int [] BG_4X_RESOURCES = new int [] { + R.drawable.widget_4x_yellow, // 4x黄色Widget + R.drawable.widget_4x_blue, // 4x蓝色Widget + R.drawable.widget_4x_white, // 4x白色Widget + R.drawable.widget_4x_green, // 4x绿色Widget + R.drawable.widget_4x_red // 4x红色Widget + }; + + /** + * 获取4x尺寸Widget背景资源 + * @param id 颜色标识 + * @return 4x Widget背景资源ID + */ + public static int getWidget4xBgResource(int id) { + return BG_4X_RESOURCES[id]; + } + } + + /** + * 文字样式资源管理 + * 提供不同字体大小的样式资源 + */ + public static class TextAppearanceResources { + // 文字样式资源数组(与字体大小常量顺序对应) + private final static int [] TEXTAPPEARANCE_RESOURCES = new int [] { + R.style.TextAppearanceNormal, // 小字体样式 + R.style.TextAppearanceMedium, // 中字体样式 + R.style.TextAppearanceLarge, // 大字体样式 + R.style.TextAppearanceSuper // 超大字体样式 + }; + + /** + * 获取文字样式资源 + * @param id 字体大小标识(如TEXT_SMALL、TEXT_MEDIUM等) + * @return 文字样式资源ID(若id无效则返回默认样式) + */ + public static int getTexAppearanceResource(int id) { + /** + * 兼容处理:防止存储的资源ID超出范围 + * 若id无效,返回默认字体大小样式 + */ + if (id >= TEXTAPPEARANCE_RESOURCES.length) { + return BG_DEFAULT_FONT_SIZE; + } + return TEXTAPPEARANCE_RESOURCES[id]; + } + + /** + * 获取文字样式资源数量 + * @return 样式资源数组长度 + */ + public static int getResourcesSize() { + return TEXTAPPEARANCE_RESOURCES.length; + } + } +} \ No newline at end of file