注释tool包,ui包,widget包 #45

Merged
pkx2w7qjn merged 1 commits from zhaochang_branch into develop 3 weeks ago

@ -35,14 +35,31 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
/**
*
*
*/
public class BackupUtils {
// 日志标签,用于调试时在 Logcat 中标识本类的日志输出
private static final String TAG = "BackupUtils";
// Singleton stuff
// 单例模式:持有 BackupUtils 的唯一实例
private static BackupUtils sInstance;
/**
* BackupUtils 线
*
* <p>
* Application Context
* 使 Activity Context ApplicationContext 使
*
* @param context BackupUtils
* @return BackupUtils
*/
public static synchronized BackupUtils getInstance(Context context) {
if (sInstance == null) {
// 首次调用时创建实例
sInstance = new BackupUtils(context);
}
return sInstance;
@ -69,14 +86,17 @@ public class BackupUtils {
mTextExport = new TextExport(context);
}
//判断外部存储(如 SD 卡)是否已挂载且可读写
private static boolean externalStorageAvailable() {
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
}
//执行导出
public int exportToText() {
return mTextExport.exportToText();
}
//获取导出文件的文件名和目录路径
public String getExportedTextFileName() {
return mTextExport.mFileName;
}
@ -85,12 +105,27 @@ public class BackupUtils {
return mTextExport.mFileDirectory;
}
/**
*
*
* <p> ContentProvider NotesData
* .txt
* 使Projection
*
*/
private static class TextExport {
// === 笔记主表Notes Table查询配置 ===
/**
* 使
*
*/
private static final String[] NOTE_PROJECTION = {
NoteColumns.ID,
NoteColumns.MODIFIED_DATE,
NoteColumns.SNIPPET,
NoteColumns.TYPE
NoteColumns.ID, // 笔记唯一ID
NoteColumns.MODIFIED_DATE, // 最后修改时间
NoteColumns.SNIPPET, // 笔记摘要/标题
NoteColumns.TYPE // 笔记类型(用于分组或过滤)
};
private static final int NOTE_COLUMN_ID = 0;
@ -99,9 +134,16 @@ public class BackupUtils {
private static final int NOTE_COLUMN_SNIPPET = 2;
// === 数据明细表Data Table查询配置 ===
/**
* 使
* Android Contacts Provider EAV
* MIME_TYPE
*/
private static final String[] DATA_PROJECTION = {
DataColumns.CONTENT,
DataColumns.MIME_TYPE,
DataColumns.CONTENT, // 主内容(如文本)
DataColumns.MIME_TYPE, // 数据类型(决定 DATA1~DATA4 的语义)
DataColumns.DATA1,
DataColumns.DATA2,
DataColumns.DATA3,
@ -112,19 +154,33 @@ public class BackupUtils {
private static final int DATA_COLUMN_MIME_TYPE = 1;
private static final int DATA_COLUMN_CALL_DATE = 2;
private static final int DATA_COLUMN_CALL_DATE = 2; //通话日期字段的列索引
private static final int DATA_COLUMN_PHONE_NUMBER = 4; //电话号码字段的列索引
private static final int DATA_COLUMN_PHONE_NUMBER = 4;
// === 文本格式模板配置 ===
/**
*
* res/values/arrays.xml R.array.format_for_exported_note
*/
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;
private Context mContext; //保存上下文,用于访问系统服务
private String mFileName; //存储最近一次成功导出的文件名
private String mFileDirectory; //存储导出文件所在的目录路径
/**
* TextExport
*
* <p>R.array.format_for_exported_note
*
*
* @param context 访
*/
public TextExport(Context context) {
TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note);
mContext = context;
@ -132,6 +188,9 @@ public class BackupUtils {
mFileDirectory = "";
}
/**
* ID
*/
private String getFormat(int id) {
return TEXT_FORMAT[id];
}
@ -146,7 +205,9 @@ public class BackupUtils {
folderId
}, null);
// 检查查询结果是否有效(非 null
if (notesCursor != null) {
// 尝试将游标移动到第一条记录;若结果集为空,则 moveToFirst() 返回 false跳过循环
if (notesCursor.moveToFirst()) {
do {
// Print note's last modified date
@ -156,8 +217,9 @@ public class BackupUtils {
// Query data belong to this note
String noteId = notesCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId, ps);
} while (notesCursor.moveToNext());
} while (notesCursor.moveToNext()); // 移动到下一条笔记,直到遍历完所有记录
}
// 关闭 Cursor 以释放数据库资源,防止内存泄漏
notesCursor.close();
}
}
@ -166,16 +228,20 @@ public class BackupUtils {
* Export note identified by id to a print stream
*/
private void exportNoteToText(String noteId, PrintStream ps) {
// 查询属于该笔记的所有明细数据Data 表),每条数据可能代表文本、电话记录等
Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI,
DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] {
noteId
}, null);
if (dataCursor != null) {
// 遍历该笔记关联的所有数据行(一个笔记可能包含多条 Data 记录)
if (dataCursor.moveToFirst()) {
do {
// 根据 MIME 类型区分数据类型
String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE);
if (DataConstants.CALL_NOTE.equals(mimeType)) {
// 处理“通话笔记”类型:包含电话号码、通话时间、附加位置信息
// Print phone number
String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER);
long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE);
@ -195,6 +261,7 @@ public class BackupUtils {
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),
@ -206,6 +273,13 @@ public class BackupUtils {
dataCursor.close();
}
// print a line separator between note
// 注意:当前实现存在两个问题:
// 1. Character.LINE_SEPARATOR 是 Unicode 行分隔符 '\u2028',多数文本编辑器不识别为换行;
// 2. Character.LETTER_NUMBER 实际值为字符 '1'ASCII 49会意外输出数字 "1"。
// 正确做法应使用标准换行符,例如:
// ps.println(); // 推荐:输出平台兼容换行
// 或 ps.write('\n'); // 简单 LF 换行(适用于纯文本导出)
// 建议后续重构此逻辑以避免导出文件包含乱码或多余字符。
try {
ps.write(new byte[] {
Character.LINE_SEPARATOR, Character.LETTER_NUMBER
@ -219,17 +293,22 @@ public class BackupUtils {
* Note will be exported as text which is user readable
*/
public int exportToText() {
// 检查外部存储是否可用(如 SD 卡是否挂载)
if (!externalStorageAvailable()) {
Log.d(TAG, "Media was not mounted");
return STATE_SD_CARD_UNMOUONTED;
}
// 获取用于写入导出文本的 PrintStream
PrintStream ps = getExportToTextPrintStream();
if (ps == null) {
Log.e(TAG, "get print stream error");
return STATE_SYSTEM_ERROR;
}
// First export folder and its notes
// 查询所有“非回收站”的文件夹 + 通话记录专用文件夹(即使它可能不满足普通文件夹条件)
// 条件说明:
// - 类型为 TYPE_FOLDER 且父 ID 不是回收站(排除回收站本身)
// - 或者是固定的通话记录文件夹ID = ID_CALL_RECORD_FOLDER
Cursor folderCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION,
@ -241,6 +320,7 @@ public class BackupUtils {
if (folderCursor.moveToFirst()) {
do {
// Print folder's name
// 获取文件夹名称:通话记录文件夹使用固定字符串,其他取自 SNIPPET 字段
String folderName = "";
if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) {
folderName = mContext.getString(R.string.call_record_folder_name);
@ -248,9 +328,11 @@ public class BackupUtils {
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());
}
@ -258,6 +340,7 @@ public class BackupUtils {
}
// Export notes in root's folder
// 查询“根目录”下的普通笔记(即 PARENT_ID = 0 且类型为普通笔记)
Cursor noteCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION,
@ -267,6 +350,7 @@ public class BackupUtils {
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))));
@ -286,22 +370,28 @@ public class BackupUtils {
* Get a print stream pointed to the file {@generateExportedTextFile}
*/
private PrintStream getExportToTextPrintStream() {
// 生成导出文件的完整路径(位于外部存储指定目录下)
File file = generateFileMountedOnSDcard(mContext, R.string.file_path,
R.string.file_name_txt_format);
if (file == null) {
Log.e(TAG, "create file to exported failed");
return null;
}
// 缓存文件名和目录路径
mFileName = file.getName();
mFileDirectory = mContext.getString(R.string.file_path);
PrintStream ps = null;
try {
// 创建指向该文件的输出流(覆盖写入模式)
FileOutputStream fos = new FileOutputStream(file);
// 包装为 PrintStream便于使用 println() 等文本写入方法
ps = new PrintStream(fos);
} catch (FileNotFoundException e) {
// 文件无法创建(如路径无效、权限不足、存储未挂载等)
e.printStackTrace();
return null;
} catch (NullPointerException e) {
// 通常由 generateFileMountedOnSDcard 返回 null 或上下文异常导致
e.printStackTrace();
return null;
}
@ -313,10 +403,13 @@ public class BackupUtils {
* Generate the text file to store imported data
*/
private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) {
// 构建文件完整路径:外部存储根目录 + 资源中定义的子路径
StringBuilder sb = new StringBuilder();
sb.append(Environment.getExternalStorageDirectory());
sb.append(context.getString(filePathResId));
File filedir = new File(sb.toString());
// 在路径后追加格式化后的文件名
sb.append(context.getString(
fileNameFormatResId,
DateFormat.format(context.getString(R.string.format_date_ymd),
@ -324,21 +417,24 @@ public class BackupUtils {
File file = new File(sb.toString());
try {
// 确保目标目录存在,不存在则尝试创建
if (!filedir.exists()) {
filedir.mkdir();
filedir.mkdir(); // 注意mkdir() 只能创建单层目录,若需多级应使用 mkdirs()
}
// 创建空文件(如果尚不存在)
if (!file.exists()) {
file.createNewFile();
}
return file;
} catch (SecurityException e) {
// 通常因缺少 WRITE_EXTERNAL_STORAGE 权限Android 6.0+ 需动态申请)
e.printStackTrace();
} catch (IOException e) {
// 可能原因:磁盘空间不足、路径为只读、文件被占用等
e.printStackTrace();
}
// 任一异常发生或创建失败时,返回 null 表示文件准备失败
return null;
}
}

@ -34,10 +34,21 @@ import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute;
import java.util.ArrayList;
import java.util.HashSet;
/**
*
*
*/
public class DataUtils {
public static final String TAG = "DataUtils";
private static final String TAG = "DataUtils"; // 日志标签
/**
*
* @param resolver 访ContentProvider
* @param ids ID
* @return truefalse
*/
public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) {
// 参数检查如果ID集合为空直接返回成功
if (ids == null) {
Log.d(TAG, "the ids is null");
return true;
@ -47,18 +58,24 @@ public class DataUtils {
return true;
}
// 创建批量操作列表
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
for (long id : ids) {
// 安全检查:不允许删除系统根文件夹
if(id == Notes.ID_ROOT_FOLDER) {
Log.e(TAG, "Don't delete system folder root");
continue;
}
// 为每个笔记创建删除操作
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, "delete notes failed, ids:" + ids.toString());
return false;
@ -72,32 +89,52 @@ public class DataUtils {
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);
values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId);
values.put(NoteColumns.LOCAL_MODIFIED, 1);
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 truefalse
*/
public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids,
long folderId) {
long folderId) {
// 参数检查
if (ids == null) {
Log.d(TAG, "the ids is null");
return true;
}
// 创建批量操作列表
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
for (long id : ids) {
// 为每个笔记创建更新操作
ContentProviderOperation.Builder builder = ContentProviderOperation
.newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
builder.withValue(NoteColumns.PARENT_ID, folderId);
builder.withValue(NoteColumns.LOCAL_MODIFIED, 1);
builder.withValue(NoteColumns.PARENT_ID, folderId); // 设置目标文件夹ID
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, "delete notes failed, ids:" + ids.toString());
return false;
@ -112,9 +149,12 @@ public class DataUtils {
}
/**
* Get the all folder count except system folders {@link Notes#TYPE_SYSTEM}}
*
* @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 + "<>?",
@ -125,17 +165,24 @@ public class DataUtils {
if(cursor != null) {
if(cursor.moveToFirst()) {
try {
count = cursor.getInt(0);
count = cursor.getInt(0); // 获取数量
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "get folder count failed:" + e.toString());
} finally {
cursor.close();
cursor.close(); // 确保游标被关闭
}
}
}
return count;
}
/**
* ID
* @param resolver
* @param noteId ID
* @param type
* @return truefalse
*/
public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null,
@ -146,13 +193,19 @@ public class DataUtils {
boolean exist = false;
if (cursor != null) {
if (cursor.getCount() > 0) {
exist = true;
exist = true; // 有记录存在
}
cursor.close();
}
return exist;
}
/**
* ID
* @param resolver
* @param noteId ID
* @return truefalse
*/
public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null, null, null, null);
@ -167,6 +220,12 @@ public class DataUtils {
return exist;
}
/**
* ID
* @param resolver
* @param dataId ID
* @return truefalse
*/
public static boolean existInDataDatabase(ContentResolver resolver, long dataId) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId),
null, null, null, null);
@ -181,11 +240,17 @@ public class DataUtils {
return exist;
}
/**
*
* @param resolver
* @param name
* @return truefalse
*/
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 + "=?",
" AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER +
" AND " + NoteColumns.SNIPPET + "=?",
new String[] { name }, null);
boolean exist = false;
if(cursor != null) {
@ -197,7 +262,14 @@ public class DataUtils {
return exist;
}
/**
*
* @param resolver
* @param folderId ID
* @return null
*/
public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) {
// 查询文件夹中所有笔记的小部件信息
Cursor c = resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE },
NoteColumns.PARENT_ID + "=?",
@ -210,9 +282,10 @@ public class DataUtils {
set = new HashSet<AppWidgetAttribute>();
do {
try {
// 创建小部件属性对象并添加到集合
AppWidgetAttribute widget = new AppWidgetAttribute();
widget.widgetId = c.getInt(0);
widget.widgetType = c.getInt(1);
widget.widgetId = c.getInt(0); // 小部件ID
widget.widgetType = c.getInt(1); // 小部件类型
set.add(widget);
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, e.toString());
@ -224,7 +297,14 @@ public class DataUtils {
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 + "=?",
@ -233,37 +313,52 @@ public class DataUtils {
if (cursor != null && cursor.moveToFirst()) {
try {
return cursor.getString(0);
return cursor.getString(0); // 返回电话号码
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "Get call number fails " + e.toString());
} finally {
cursor.close();
cursor.close(); // 确保游标被关闭
}
}
return "";
return ""; // 没有找到返回空字符串
}
/**
* ID
* @param resolver
* @param phoneNumber
* @param callDate
* @return ID0
*/
public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) {
// 使用自定义的PHONE_NUMBERS_EQUAL函数比较电话号码
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.NOTE_ID },
CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL("
+ CallNote.PHONE_NUMBER + ",?)",
+ 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);
return cursor.getLong(0); // 返回笔记ID
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "Get call note id fails " + e.toString());
}
}
cursor.close();
}
return 0;
return 0; // 没有找到返回0
}
/**
* ID
* @param resolver
* @param noteId ID
* @return
* @throws IllegalArgumentException
*/
public static String getSnippetById(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
new String [] { NoteColumns.SNIPPET },
@ -274,7 +369,7 @@ public class DataUtils {
if (cursor != null) {
String snippet = "";
if (cursor.moveToFirst()) {
snippet = cursor.getString(0);
snippet = cursor.getString(0); // 获取内容摘要
}
cursor.close();
return snippet;
@ -282,14 +377,19 @@ public class DataUtils {
throw new IllegalArgumentException("Note is not found with id: " + noteId);
}
/**
*
* @param snippet
* @return
*/
public static String getFormattedSnippet(String snippet) {
if (snippet != null) {
snippet = snippet.trim();
int index = snippet.indexOf('\n');
snippet = snippet.trim(); // 去除首尾空格
int index = snippet.indexOf('\n'); // 查找第一个换行符
if (index != -1) {
snippet = snippet.substring(0, index);
snippet = snippet.substring(0, index); // 只保留第一行
}
}
return snippet;
}
}
}

@ -16,98 +16,112 @@
package net.micode.notes.tool;
/**
* GTask
* Google Task APIJSON
* 便Google Task
*/
public class GTaskStringUtils {
// ==================== 动作相关常量 ====================
/** 动作ID字段名 */
public final static String GTASK_JSON_ACTION_ID = "action_id";
/** 动作列表字段名 */
public final static String GTASK_JSON_ACTION_LIST = "action_list";
/** 动作类型字段名 */
public final static String GTASK_JSON_ACTION_TYPE = "action_type";
/** 创建动作类型 */
public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create";
/** 获取所有动作类型 */
public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all";
/** 移动动作类型 */
public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move";
/** 更新动作类型 */
public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update";
// ==================== 实体属性相关常量 ====================
/** 创建者ID字段名 */
public final static String GTASK_JSON_CREATOR_ID = "creator_id";
/** 子实体字段名 */
public final static String GTASK_JSON_CHILD_ENTITY = "child_entity";
/** 客户端版本字段名 */
public final static String GTASK_JSON_CLIENT_VERSION = "client_version";
/** 完成状态字段名 */
public final static String GTASK_JSON_COMPLETED = "completed";
/** 当前列表ID字段名 */
public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id";
/** 默认列表ID字段名 */
public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id";
/** 删除状态字段名 */
public final static String GTASK_JSON_DELETED = "deleted";
/** 目标列表字段名 */
public final static String GTASK_JSON_DEST_LIST = "dest_list";
/** 目标父级字段名 */
public final static String GTASK_JSON_DEST_PARENT = "dest_parent";
/** 目标父级类型字段名 */
public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type";
/** 实体增量字段名 */
public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta";
/** 实体类型字段名 */
public final static String GTASK_JSON_ENTITY_TYPE = "entity_type";
/** 获取已删除项字段名 */
public final static String GTASK_JSON_GET_DELETED = "get_deleted";
/** ID字段名 */
public final static String GTASK_JSON_ID = "id";
/** 索引字段名 */
public final static String GTASK_JSON_INDEX = "index";
/** 最后修改时间字段名 */
public final static String GTASK_JSON_LAST_MODIFIED = "last_modified";
/** 最新同步点字段名 */
public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point";
/** 列表ID字段名 */
public final static String GTASK_JSON_LIST_ID = "list_id";
// ==================== 数据结构相关常量 ====================
/** 列表集合字段名 */
public final static String GTASK_JSON_LISTS = "lists";
/** 名称字段名 */
public final static String GTASK_JSON_NAME = "name";
/** 新ID字段名 */
public final static String GTASK_JSON_NEW_ID = "new_id";
/** 便签字段名 */
public final static String GTASK_JSON_NOTES = "notes";
/** 父级ID字段名 */
public final static String GTASK_JSON_PARENT_ID = "parent_id";
/** 前一个兄弟节点ID字段名 */
public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id";
/** 结果字段名 */
public final static String GTASK_JSON_RESULTS = "results";
/** 源列表字段名 */
public final static String GTASK_JSON_SOURCE_LIST = "source_list";
/** 任务字段名 */
public final static String GTASK_JSON_TASKS = "tasks";
/** 类型字段名 */
public final static String GTASK_JSON_TYPE = "type";
/** 组类型(文件夹) */
public final static String GTASK_JSON_TYPE_GROUP = "GROUP";
/** 任务类型(便签) */
public final static String GTASK_JSON_TYPE_TASK = "TASK";
/** 用户字段名 */
public final static String GTASK_JSON_USER = "user";
// ==================== MIUI便签特定常量 ====================
/** MIUI文件夹前缀用于标识MIUI便签创建的文件夹 */
public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]";
/** 默认文件夹名称 */
public final static String FOLDER_DEFAULT = "Default";
/** 通话记录便签文件夹名称 */
public final static String FOLDER_CALL_NOTE = "Call_Note";
/** 元数据文件夹名称 */
public final static String FOLDER_META = "METADATA";
// ==================== 元数据相关常量 ====================
/** 元数据头Google Task ID */
public final static String META_HEAD_GTASK_ID = "meta_gid";
/** 元数据头:便签信息 */
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";
}
}

@ -22,151 +22,253 @@ import android.preference.PreferenceManager;
import net.micode.notes.R;
import net.micode.notes.ui.NotesPreferenceActivity;
/**
*
* 便
* ID
*/
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
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
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 // 红色标题背景
};
/**
* ID便
* @param id ID (YELLOW, BLUE, WHITE, GREEN, RED)
* @return ID
*/
public static int getNoteBgResource(int id) {
return BG_EDIT_RESOURCES[id];
}
/**
* ID便
* @param id ID (YELLOW, BLUE, WHITE, GREEN, RED)
* @return ID
*/
public static int getNoteTitleBgResource(int id) {
return BG_EDIT_TITLE_RESOURCES[id];
}
}
/**
* ID
* 使
* @param context
* @return ID
*/
public static int getDefaultBgId(Context context) {
// 检查用户是否启用了随机背景颜色功能
if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) {
// 启用随机颜色返回0-4之间的随机数
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
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
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,
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
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 ID
* @return ID
*/
public static int getNoteBgFirstRes(int id) {
return BG_FIRST_RESOURCES[id];
}
/**
*
* @param id ID
* @return ID
*/
public static int getNoteBgLastRes(int id) {
return BG_LAST_RESOURCES[id];
}
/**
* 使
* @param id ID
* @return ID
*/
public static int getNoteBgSingleRes(int id) {
return BG_SINGLE_RESOURCES[id];
}
/**
*
* @param id 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;
}
}
/**
*
*
*/
public static class WidgetBgResources {
/** 2x尺寸小部件的背景资源数组 */
private final static int [] BG_2X_RESOURCES = new int [] {
R.drawable.widget_2x_yellow,
R.drawable.widget_2x_blue,
R.drawable.widget_2x_white,
R.drawable.widget_2x_green,
R.drawable.widget_2x_red,
R.drawable.widget_2x_yellow, // 黄色2x小部件
R.drawable.widget_2x_blue, // 蓝色2x小部件
R.drawable.widget_2x_white, // 白色2x小部件
R.drawable.widget_2x_green, // 绿色2x小部件
R.drawable.widget_2x_red, // 红色2x小部件
};
/**
* 2x
* @param id ID
* @return ID
*/
public static int getWidget2xBgResource(int id) {
return BG_2X_RESOURCES[id];
}
/** 4x尺寸小部件的背景资源数组 */
private final static int [] BG_4X_RESOURCES = new int [] {
R.drawable.widget_4x_yellow,
R.drawable.widget_4x_blue,
R.drawable.widget_4x_white,
R.drawable.widget_4x_green,
R.drawable.widget_4x_red
R.drawable.widget_4x_yellow, // 黄色4x小部件
R.drawable.widget_4x_blue, // 蓝色4x小部件
R.drawable.widget_4x_white, // 白色4x小部件
R.drawable.widget_4x_green, // 绿色4x小部件
R.drawable.widget_4x_red // 红色4x小部件
};
/**
* 4x
* @param id ID
* @return 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
R.style.TextAppearanceNormal, // 正常字体样式
R.style.TextAppearanceMedium, // 中等字体样式
R.style.TextAppearanceLarge, // 大字体样式
R.style.TextAppearanceSuper // 超大字体样式
};
/**
* ID
*
* @param id ID (TEXT_SMALL, TEXT_MEDIUM, TEXT_LARGE, TEXT_SUPER)
* @return ID
*/
public static int getTexAppearanceResource(int id) {
/**
* HACKME: Fix bug of store the resource id in shared preference.
* The id may larger than the length of resources, in this case,
* return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE}
* HACKME: SharedPreferenceIDbug
* ID
*
*/
if (id >= TEXTAPPEARANCE_RESOURCES.length) {
return BG_DEFAULT_FONT_SIZE;
@ -174,8 +276,12 @@ public class ResourceParser {
return TEXTAPPEARANCE_RESOURCES[id];
}
/**
*
* @return
*/
public static int getResourcesSize() {
return TEXTAPPEARANCE_RESOURCES.length;
}
}
}
}

@ -39,21 +39,26 @@ import net.micode.notes.tool.DataUtils;
import java.io.IOException;
/**
* - 便
*
*/
public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener {
private long mNoteId;
private String mSnippet;
private static final int SNIPPET_PREW_MAX_LEN = 60;
MediaPlayer mPlayer;
private long mNoteId; // 便签ID
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);
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
@ -64,8 +69,10 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD
Intent intent = getIntent();
try {
// 从Intent中获取便签ID和内容片段
mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1));
mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId);
// 截取片段内容,如果过长则添加省略号
mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0,
SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info)
: mSnippet;
@ -75,84 +82,106 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD
}
mPlayer = new MediaPlayer();
// 检查便签是否仍然存在于数据库中且为普通类型
if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) {
showActionDialog();
playAlarmSound();
showActionDialog(); // 显示操作对话框
playAlarmSound(); // 播放闹钟声音
} else {
finish();
finish(); // 如果便签不存在,直接结束活动
}
}
/**
*
*/
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();
mPlayer.setLooping(true); // 设置循环播放
mPlayer.start(); // 开始播放
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
*
*/
private void showActionDialog() {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle(R.string.app_name);
dialog.setMessage(mSnippet);
dialog.setPositiveButton(R.string.notealert_ok, this);
dialog.setTitle(R.string.app_name); // 设置应用名称作为标题
dialog.setMessage(mSnippet); // 设置便签片段作为内容
dialog.setPositiveButton(R.string.notealert_ok, this); // 确定按钮
// 如果屏幕已开启,显示进入按钮(用于跳转到便签编辑界面)
if (isScreenOn()) {
dialog.setNegativeButton(R.string.notealert_enter, this);
}
dialog.show().setOnDismissListener(this);
dialog.show().setOnDismissListener(this); // 设置对话框关闭监听器
}
/**
*
*/
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_NEGATIVE:
case DialogInterface.BUTTON_NEGATIVE: // 点击"进入"按钮
Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(Intent.EXTRA_UID, mNoteId);
startActivity(intent);
intent.putExtra(Intent.EXTRA_UID, mNoteId); // 传递便签ID
startActivity(intent); // 跳转到便签编辑界面
break;
default:
break;
break; // 确定按钮或其他按钮,不执行特殊操作
}
}
/**
*
*/
public void onDismiss(DialogInterface dialog) {
stopAlarmSound();
finish();
stopAlarmSound(); // 停止闹钟声音
finish(); // 结束活动
}
/**
*
*/
private void stopAlarmSound() {
if (mPlayer != null) {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
mPlayer.stop(); // 停止播放
mPlayer.release(); // 释放资源
mPlayer = null; // 置空引用
}
}
}
}

@ -27,39 +27,64 @@ 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,
NoteColumns.ALERTED_DATE
NoteColumns.ID, // 便签ID
NoteColumns.ALERTED_DATE // 提醒日期时间戳
};
private static final int COLUMN_ID = 0;
private static final int COLUMN_ALERTED_DATE = 1;
// 列索引常量,提高代码可读性
private static final int COLUMN_ID = 0; // ID列索引
private static final int COLUMN_ALERTED_DATE = 1; // 提醒日期列索引
/**
* 广广
* @param context
* @param intent 广
*/
@Override
public void onReceive(Context context, Intent intent) {
long currentDate = System.currentTimeMillis();
long currentDate = System.currentTimeMillis(); // 获取当前时间戳
// 查询数据库:查找所有未来需要提醒的普通便签
// 条件:提醒日期 > 当前时间 且 类型为普通便签
Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
PROJECTION,
NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE,
new String[] { String.valueOf(currentDate) },
new String[] { String.valueOf(currentDate) }, // 参数:当前时间
null);
if (c != null) {
// 遍历查询结果,为每个未来的提醒设置闹钟
if (c.moveToFirst()) {
do {
long alertDate = c.getLong(COLUMN_ALERTED_DATE);
long alertDate = c.getLong(COLUMN_ALERTED_DATE); // 获取提醒时间
long noteId = c.getLong(COLUMN_ID); // 获取便签ID
// 创建闹钟触发时的广播意图
Intent sender = new Intent(context, AlarmReceiver.class);
sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID)));
// 设置数据URI便于AlarmReceiver识别具体便签
sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId));
// 创建待定意图,用于闹钟管理器
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0);
AlarmManager alermManager = (AlarmManager) context
// 获取闹钟管理器服务
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);
} while (c.moveToNext());
// 设置精确闹钟RTC_WAKEUP表示即使设备休眠也会唤醒并触发
alarmManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);
} while (c.moveToNext()); // 继续处理下一条记录
}
c.close();
c.close(); // 关闭游标,释放资源
}
}
}
}

@ -20,11 +20,29 @@ import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
/**
* - AlarmManager广
* 广
*/
public class AlarmReceiver extends BroadcastReceiver {
/**
*
* 广
*
* @param context Activity
* @param intent 广便URI
*/
@Override
public void onReceive(Context context, Intent intent) {
// 将当前意图的类设置为闹钟提醒活动
intent.setClass(context, AlarmAlertActivity.class);
// 添加标志确保在新的任务栈中启动Activity
// 这是必要的因为广播接收器本身没有Activity上下文
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// 启动闹钟提醒界面
context.startActivity(intent);
}
}
}

@ -21,92 +21,122 @@ 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;
/**
*
* AM/PM
* 1224
*/
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;
private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23;
private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1;
private static final int HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW = 12;
private static final int MINUT_SPINNER_MIN_VAL = 0;
private static final int MINUT_SPINNER_MAX_VAL = 59;
private static final int AMPM_SPINNER_MIN_VAL = 0;
private static final int AMPM_SPINNER_MAX_VAL = 1;
private final NumberPicker mDateSpinner;
private final NumberPicker mHourSpinner;
private final NumberPicker mMinuteSpinner;
private final NumberPicker mAmPmSpinner;
private Calendar mDate;
private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK];
private boolean mIsAm;
private boolean mIs24HourView;
private boolean mIsEnabled = DEFAULT_ENABLE_STATE;
private boolean mInitialising;
// 时间相关常量定义
private static final int HOURS_IN_HALF_DAY = 12; // 半天的小时数12小时制
private static final int HOURS_IN_ALL_DAY = 24; // 全天小时数24小时制
private static final int DAYS_IN_ALL_WEEK = 7; // 一周天数
// 各选择器的数值范围常量
private static final int DATE_SPINNER_MIN_VAL = 0; // 日期选择器最小值
private static final int DATE_SPINNER_MAX_VAL = DAYS_IN_ALL_WEEK - 1; // 日期选择器最大值
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; // AM/PM选择器最小值
private static final int AMPM_SPINNER_MAX_VAL = 1; // AM/PM选择器最大值
// UI组件
private final NumberPicker mDateSpinner; // 日期选择器
private final NumberPicker mHourSpinner; // 小时选择器
private final NumberPicker mMinuteSpinner; // 分钟选择器
private final NumberPicker mAmPmSpinner; // AM/PM选择器
// 数据状态
private Calendar mDate; // 当前选择的日期时间
private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK]; // 日期显示文本数组
private boolean mIsAm; // 是否为上午AM
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();
updateDateControl(); // 更新日期显示
onDateTimeChanged(); // 触发日期时间变化回调
}
};
/**
*
* 12/24
*/
private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
boolean isDateChanged = false;
boolean isDateChanged = false; // 标记是否需要调整日期
Calendar cal = Calendar.getInstance();
if (!mIs24HourView) {
// 12小时制下的特殊处理
// 下午11点->12点需要增加一天
if (!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1);
isDateChanged = true;
} else if (mIsAm && oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
}
// 上午12点->11点需要减少一天
else if (mIsAm && oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -1);
isDateChanged = true;
}
if (oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY ||
oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
mIsAm = !mIsAm;
updateAmPmControl();
// 处理AM/PM切换11点<->12点
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; // 切换AM/PM状态
updateAmPmControl(); // 更新AM/PM显示
}
} else {
// 24小时制下的特殊处理
// 23点->0点需要增加一天
if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1);
isDateChanged = true;
} else if (oldVal == 0 && newVal == HOURS_IN_ALL_DAY - 1) {
}
// 0点->23点需要减少一天
else if (oldVal == 0 && newVal == HOURS_IN_ALL_DAY - 1) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -1);
isDateChanged = true;
}
}
// 计算实际的小时值12小时制需要转换为24小时制
int newHour = mHourSpinner.getValue() % HOURS_IN_HALF_DAY + (mIsAm ? 0 : HOURS_IN_HALF_DAY);
mDate.set(Calendar.HOUR_OF_DAY, newHour);
onDateTimeChanged();
onDateTimeChanged(); // 触发回调
// 如果需要调整日期,则更新年月日
if (isDateChanged) {
setCurrentYear(cal.get(Calendar.YEAR));
setCurrentMonth(cal.get(Calendar.MONTH));
@ -115,111 +145,169 @@ public class DateTimePicker extends FrameLayout {
}
};
/**
*
*
*/
private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
int minValue = mMinuteSpinner.getMinValue();
int maxValue = mMinuteSpinner.getMaxValue();
int offset = 0;
int offset = 0; // 小时调整偏移量
// 处理分钟循环59->0需要增加1小时0->59需要减少1小时
if (oldVal == maxValue && newVal == minValue) {
offset += 1;
offset += 1; // 向前滚动增加1小时
} else if (oldVal == minValue && newVal == maxValue) {
offset -= 1;
offset -= 1; // 向后滚动减少1小时
}
// 如果需要调整小时
if (offset != 0) {
mDate.add(Calendar.HOUR_OF_DAY, offset);
mHourSpinner.setValue(getCurrentHour());
updateDateControl();
mDate.add(Calendar.HOUR_OF_DAY, offset); // 调整小时
mHourSpinner.setValue(getCurrentHour()); // 更新小时显示
updateDateControl(); // 更新日期显示(可能因小时调整而跨天)
// 检查并更新AM/PM状态
int newHour = getCurrentHourOfDay();
if (newHour >= HOURS_IN_HALF_DAY) {
mIsAm = false;
mIsAm = false; // 下午
updateAmPmControl();
} else {
mIsAm = true;
mIsAm = true; // 上午
updateAmPmControl();
}
}
// 设置新的分钟值
mDate.set(Calendar.MINUTE, newVal);
onDateTimeChanged();
onDateTimeChanged(); // 触发回调
}
};
/**
* AM/PM
* AM/PM12
*/
private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
mIsAm = !mIsAm;
mIsAm = !mIsAm; // 切换AM/PM状态
// 根据AM/PM切换调整12小时
if (mIsAm) {
mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY);
mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY); // PM->AM减少12小时
} else {
mDate.add(Calendar.HOUR_OF_DAY, HOURS_IN_HALF_DAY);
mDate.add(Calendar.HOUR_OF_DAY, HOURS_IN_HALF_DAY); // AM->PM增加12小时
}
updateAmPmControl();
onDateTimeChanged();
updateAmPmControl(); // 更新AM/PM显示
onDateTimeChanged(); // 触发回调
}
};
/**
*
*/
public interface OnDateTimeChangedListener {
/**
*
* @param view DateTimePicker
* @param year
* @param month 0-11
* @param dayOfMonth 1-31
* @param hourOfDay 0-23
* @param minute 0-59
*/
void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute);
int dayOfMonth, int hourOfDay, int minute);
}
/**
* - 使
* @param context
*/
public DateTimePicker(Context context) {
this(context, System.currentTimeMillis());
}
/**
* - 使
* @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;
mDate = Calendar.getInstance(); // 创建日历实例
mInitialising = true; // 标记开始初始化
// 根据当前时间判断初始AM/PM状态
mIsAm = (getCurrentHourOfDay() < HOURS_IN_HALF_DAY);
// 加载布局文件
inflate(context, R.layout.datetime_picker, this);
// 初始化日期选择器
mDateSpinner = (NumberPicker) findViewById(R.id.date);
mDateSpinner.setMinValue(DATE_SPINNER_MIN_VAL);
mDateSpinner.setMaxValue(DATE_SPINNER_MAX_VAL);
mDateSpinner.setOnValueChangedListener(mOnDateChangedListener);
// 初始化小时选择器
mHourSpinner = (NumberPicker) findViewById(R.id.hour);
mHourSpinner.setOnValueChangedListener(mOnHourChangedListener);
// 初始化分钟选择器
mMinuteSpinner = (NumberPicker) findViewById(R.id.minute);
mMinuteSpinner.setMinValue(MINUT_SPINNER_MIN_VAL);
mMinuteSpinner.setMaxValue(MINUT_SPINNER_MAX_VAL);
mMinuteSpinner.setOnLongPressUpdateInterval(100);
mMinuteSpinner.setOnLongPressUpdateInterval(100); // 设置长按更新间隔
mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener);
String[] stringsForAmPm = new DateFormatSymbols().getAmPmStrings();
// 初始化AM/PM选择器
String[] stringsForAmPm = new DateFormatSymbols().getAmPmStrings(); // 获取本地化的AM/PM文本
mAmPmSpinner = (NumberPicker) findViewById(R.id.amPm);
mAmPmSpinner.setMinValue(AMPM_SPINNER_MIN_VAL);
mAmPmSpinner.setMaxValue(AMPM_SPINNER_MAX_VAL);
mAmPmSpinner.setDisplayedValues(stringsForAmPm);
mAmPmSpinner.setDisplayedValues(stringsForAmPm); // 设置显示文本
mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener);
// update controls to initial state
updateDateControl();
updateHourControl();
updateAmPmControl();
// 更新各控件到初始状态
updateDateControl(); // 更新日期显示
updateHourControl(); // 更新小时显示范围
updateAmPmControl(); // 更新AM/PM显示
set24HourView(is24HourView);
set24HourView(is24HourView); // 设置时间显示格式
// set to current time
setCurrentDate(date);
setCurrentDate(date); // 设置初始时间
setEnabled(isEnabled());
setEnabled(isEnabled()); // 设置启用状态
// set the content descriptions
mInitialising = false;
mInitialising = false; // 标记初始化完成
}
/**
*
* @param enabled truefalse
*/
@Override
public void setEnabled(boolean enabled) {
if (mIsEnabled == enabled) {
return;
return; // 状态未变化,直接返回
}
super.setEnabled(enabled);
// 设置各子组件的启用状态
mDateSpinner.setEnabled(enabled);
mMinuteSpinner.setEnabled(enabled);
mHourSpinner.setEnabled(enabled);
@ -227,43 +315,45 @@ public class DateTimePicker extends FrameLayout {
mIsEnabled = enabled;
}
/**
*
* @return truefalse
*/
@Override
public boolean isEnabled() {
return mIsEnabled;
}
/**
* Get the current date in millis
*
* @return the current date in millis
*
* @return
*/
public long getCurrentDateInTimeMillis() {
return mDate.getTimeInMillis();
}
/**
* Set the current date
*
* @param date The current date in millis
*
* @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));
}
/**
* Set the current date
*
* @param year The current year
* @param month The current month
* @param dayOfMonth The current dayOfMonth
* @param hourOfDay The current hourOfDay
* @param minute The current minute
*
* @param year
* @param month 0-11
* @param dayOfMonth 1-31
* @param hourOfDay 0-23
* @param minute 0-59
*/
public void setCurrentDate(int year, int month,
int dayOfMonth, int hourOfDay, int minute) {
int dayOfMonth, int hourOfDay, int minute) {
setCurrentYear(year);
setCurrentMonth(month);
setCurrentDay(dayOfMonth);
@ -272,41 +362,38 @@ public class DateTimePicker extends FrameLayout {
}
/**
* Get current year
*
* @return The current year
*
* @return
*/
public int getCurrentYear() {
return mDate.get(Calendar.YEAR);
}
/**
* Set current year
*
* @param year The current year
*
* @param year
*/
public void setCurrentYear(int year) {
// 初始化期间或年份未变化时跳过回调
if (!mInitialising && year == getCurrentYear()) {
return;
}
mDate.set(Calendar.YEAR, year);
updateDateControl();
onDateTimeChanged();
updateDateControl(); // 更新日期显示
onDateTimeChanged(); // 触发回调
}
/**
* Get current month in the year
*
* @return The current month in the year
*
* @return 0-11
*/
public int getCurrentMonth() {
return mDate.get(Calendar.MONTH);
}
/**
* Set current month in the year
*
* @param month The month in the year
*
* @param month 0-11
*/
public void setCurrentMonth(int month) {
if (!mInitialising && month == getCurrentMonth()) {
@ -318,18 +405,16 @@ public class DateTimePicker extends FrameLayout {
}
/**
* Get current day of the month
*
* @return The day of the month
*
* @return 1-31
*/
public int getCurrentDay() {
return mDate.get(Calendar.DAY_OF_MONTH);
}
/**
* Set current day of the month
*
* @param dayOfMonth The day of the month
*
* @param dayOfMonth 1-31
*/
public void setCurrentDay(int dayOfMonth) {
if (!mInitialising && dayOfMonth == getCurrentDay()) {
@ -341,145 +426,179 @@ public class DateTimePicker extends FrameLayout {
}
/**
* Get current hour in 24 hour mode, in the range (0~23)
* @return The current hour in 24 hour mode
* 24
* @return 0-23
*/
public int getCurrentHourOfDay() {
return mDate.get(Calendar.HOUR_OF_DAY);
}
/**
* 12/24
* @return 121-12240-23
*/
private int getCurrentHour() {
if (mIs24HourView){
return getCurrentHourOfDay();
return getCurrentHourOfDay(); // 24小时制直接返回
} else {
int hour = getCurrentHourOfDay();
// 12小时制转换0点显示为1213-23点转换为1-11
if (hour > HOURS_IN_HALF_DAY) {
return hour - HOURS_IN_HALF_DAY;
return hour - HOURS_IN_HALF_DAY; // 下午时间13-23 -> 1-11
} else {
return hour == 0 ? HOURS_IN_HALF_DAY : hour;
return hour == 0 ? HOURS_IN_HALF_DAY : hour; // 0点显示为121-11点不变
}
}
}
/**
* Set current hour in 24 hour mode, in the range (0~23)
*
* @param hourOfDay
* 24
* @param hourOfDay 0-23
*/
public void setCurrentHour(int hourOfDay) {
if (!mInitialising && hourOfDay == getCurrentHourOfDay()) {
return;
}
mDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
// 12小时制需要额外处理AM/PM状态
if (!mIs24HourView) {
if (hourOfDay >= HOURS_IN_HALF_DAY) {
mIsAm = false;
mIsAm = false; // 下午
if (hourOfDay > HOURS_IN_HALF_DAY) {
hourOfDay -= HOURS_IN_HALF_DAY;
hourOfDay -= HOURS_IN_HALF_DAY; // 13-23点转换为1-11点
}
} else {
mIsAm = true;
mIsAm = true; // 上午
if (hourOfDay == 0) {
hourOfDay = HOURS_IN_HALF_DAY;
hourOfDay = HOURS_IN_HALF_DAY; // 0点转换为12点
}
}
updateAmPmControl();
updateAmPmControl(); // 更新AM/PM显示
}
mHourSpinner.setValue(hourOfDay);
onDateTimeChanged();
mHourSpinner.setValue(hourOfDay); // 设置小时选择器值
onDateTimeChanged(); // 触发回调
}
/**
* Get currentMinute
*
* @return The Current Minute
*
* @return 0-59
*/
public int getCurrentMinute() {
return mDate.get(Calendar.MINUTE);
}
/**
* Set current minute
*
* @param minute 0-59
*/
public void setCurrentMinute(int minute) {
if (!mInitialising && minute == getCurrentMinute()) {
return;
}
mMinuteSpinner.setValue(minute);
mDate.set(Calendar.MINUTE, minute);
onDateTimeChanged();
mMinuteSpinner.setValue(minute); // 设置分钟选择器值
mDate.set(Calendar.MINUTE, minute); // 设置日历分钟
onDateTimeChanged(); // 触发回调
}
/**
* @return true if this is in 24 hour view else false.
* 24
* @return true24false12
*/
public boolean is24HourView () {
return mIs24HourView;
}
/**
* Set whether in 24 hour or AM/PM mode.
*
* @param is24HourView True for 24 hour mode. False for AM/PM mode.
*
* @param is24HourView true24false12
*/
public void set24HourView(boolean is24HourView) {
if (mIs24HourView == is24HourView) {
return;
return; // 显示模式未变化,直接返回
}
mIs24HourView = is24HourView;
// 显示/隐藏AM/PM选择器
mAmPmSpinner.setVisibility(is24HourView ? View.GONE : View.VISIBLE);
int hour = getCurrentHourOfDay();
updateHourControl();
setCurrentHour(hour);
updateAmPmControl();
int hour = getCurrentHourOfDay(); // 保存当前小时
updateHourControl(); // 更新小时选择器范围
setCurrentHour(hour); // 重新设置小时(会进行格式转换)
updateAmPmControl(); // 更新AM/PM显示
}
/**
*
* 37
*/
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);
mDateSpinner.setDisplayedValues(null); // 清空显示值
// 生成7天的日期显示文本
for (int i = 0; i < DAYS_IN_ALL_WEEK; ++i) {
cal.add(Calendar.DAY_OF_YEAR, 1);
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();
mDateSpinner.setDisplayedValues(mDateDisplayValues); // 设置显示文本
mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2); // 选中中间项(当前日期)
mDateSpinner.invalidate(); // 刷新显示
}
/**
* AM/PM
* 24AM/PM
*/
private void updateAmPmControl() {
if (mIs24HourView) {
mAmPmSpinner.setVisibility(View.GONE);
mAmPmSpinner.setVisibility(View.GONE); // 24小时制隐藏AM/PM
} else {
int index = mIsAm ? Calendar.AM : Calendar.PM;
mAmPmSpinner.setValue(index);
mAmPmSpinner.setVisibility(View.VISIBLE);
int index = mIsAm ? Calendar.AM : Calendar.PM; // 计算AM/PM索引
mAmPmSpinner.setValue(index); // 设置AM/PM选择器值
mAmPmSpinner.setVisibility(View.VISIBLE); // 显示AM/PM选择器
}
}
/**
*
* 12/24
*/
private void updateHourControl() {
if (mIs24HourView) {
// 24小时制0-23
mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW);
mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW);
} else {
// 12小时制1-12
mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW);
mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW);
}
}
/**
* Set the callback that indicates the 'Set' button has been pressed.
* @param callback the callback, if null will do nothing
*
* @param callback
*/
public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) {
mOnDateTimeChangedListener = callback;
}
/**
*
*
*/
private void onDateTimeChanged() {
if (mOnDateTimeChangedListener != null) {
mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(),
getCurrentMonth(), getCurrentDay(), getCurrentHourOfDay(), getCurrentMinute());
}
}
}
}

@ -29,62 +29,133 @@ import android.content.DialogInterface.OnClickListener;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
/**
*
* DateTimePicker
* /
*/
public class DateTimePickerDialog extends AlertDialog implements OnClickListener {
// 当前选择的日期时间
private Calendar mDate = Calendar.getInstance();
// 是否为24小时制显示
private boolean mIs24HourView;
// 日期时间设置回调接口
private OnDateTimeSetListener mOnDateTimeSetListener;
// 内嵌的日期时间选择器
private DateTimePicker mDateTimePicker;
/**
*
*
*/
public interface OnDateTimeSetListener {
/**
*
* @param dialog
* @param date
*/
void OnDateTimeSet(AlertDialog dialog, long date);
}
/**
*
* @param context
* @param date
*/
public DateTimePickerDialog(Context context, long date) {
super(context);
// 创建日期时间选择器实例
mDateTimePicker = new DateTimePicker(context);
setView(mDateTimePicker);
setView(mDateTimePicker); // 将选择器设置为对话框内容视图
// 设置日期时间变化监听器
mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() {
/**
*
*
*/
public void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute) {
int dayOfMonth, int hourOfDay, int minute) {
// 更新内部 Calendar 对象
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);
mDate.set(Calendar.SECOND, 0); // 秒数设为0确保时间精度一致
// 更新日期时间选择器的显示
mDateTimePicker.setCurrentDate(mDate.getTimeInMillis());
setButton(context.getString(R.string.datetime_dialog_ok), this);
setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null);
// 设置对话框按钮
setButton(DialogInterface.BUTTON_POSITIVE, context.getString(R.string.datetime_dialog_ok), this);
setButton(DialogInterface.BUTTON_NEGATIVE, context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null);
// 根据系统设置确定时间显示格式
set24HourView(DateFormat.is24HourFormat(this.getContext()));
// 初始化对话框标题
updateTitle(mDate.getTimeInMillis());
}
/**
*
* @param is24HourView true24false12
*/
public void set24HourView(boolean is24HourView) {
mIs24HourView = is24HourView;
// 注意:这里应该调用 mDateTimePicker.set24HourView(is24HourView) 来同步内部选择器
// 当前实现可能存在问题,只更新了本地变量而没有更新内部选择器
}
/**
*
* @param callBack
*/
public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) {
mOnDateTimeSetListener = callBack;
}
/**
*
*
* @param date
*/
private void updateTitle(long date) {
// 设置日期时间显示格式标志
int flag =
DateUtils.FORMAT_SHOW_YEAR |
DateUtils.FORMAT_SHOW_DATE |
DateUtils.FORMAT_SHOW_TIME;
DateUtils.FORMAT_SHOW_YEAR | // 显示年份
DateUtils.FORMAT_SHOW_DATE | // 显示日期
DateUtils.FORMAT_SHOW_TIME; // 显示时间
// 设置时间格式24小时制或12小时制
flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR;
// 注意:上面的逻辑有误,应该是 FORMAT_24HOUR 或 FORMAT_12HOUR
// 正确写法flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_12HOUR;
// 格式化日期时间并设置为对话框标题
setTitle(DateUtils.formatDateTime(this.getContext(), date, flag));
}
/**
*
*
* @param arg0
* @param arg1 ID
*/
public void onClick(DialogInterface arg0, int arg1) {
// 触发日期时间设置完成回调
if (mOnDateTimeSetListener != null) {
mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis());
}
}
}

@ -27,17 +27,33 @@ import android.widget.PopupMenu.OnMenuItemClickListener;
import net.micode.notes.R;
/**
*
* PopupMenu
*
*/
public class DropdownMenu {
private Button mButton;
private PopupMenu mPopupMenu;
private Menu mMenu;
private Button mButton; // 触发下拉菜单的按钮
private PopupMenu mPopupMenu; // Android原生弹出菜单
private Menu mMenu; // 菜单对象
/**
*
* @param context
* @param button
* @param menuId IDR.menu.xxx
*/
public DropdownMenu(Context context, Button button, int menuId) {
mButton = button;
// 设置按钮背景为下拉图标
mButton.setBackgroundResource(R.drawable.dropdown_icon);
// 创建弹出菜单,锚点为按钮
mPopupMenu = new PopupMenu(context, mButton);
// 获取菜单对象
mMenu = mPopupMenu.getMenu();
// 从资源文件加载菜单项
mPopupMenu.getMenuInflater().inflate(menuId, mMenu);
// 设置按钮点击事件:点击时显示下拉菜单
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPopupMenu.show();
@ -45,17 +61,30 @@ public class DropdownMenu {
});
}
/**
*
* @param listener
*/
public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) {
if (mPopupMenu != null) {
mPopupMenu.setOnMenuItemClickListener(listener);
}
}
/**
* ID
* @param id ID
* @return null
*/
public MenuItem findItem(int id) {
return mMenu.findItem(id);
}
/**
*
* @param title
*/
public void setTitle(CharSequence title) {
mButton.setText(title);
}
}
}

@ -28,53 +28,102 @@ import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
/**
*
*
*/
public class FoldersListAdapter extends CursorAdapter {
// 数据库查询的列投影只需要ID和名称两列
public static final String [] PROJECTION = {
NoteColumns.ID,
NoteColumns.SNIPPET
NoteColumns.ID, // 文件夹ID
NoteColumns.SNIPPET // 文件夹名称存储在snippet字段中
};
public static final int ID_COLUMN = 0;
public static final int NAME_COLUMN = 1;
// 列索引常量
public static final int ID_COLUMN = 0; // ID列的索引
public static final int NAME_COLUMN = 1; // 名称列的索引
/**
*
* @param context
* @param c
*/
public FoldersListAdapter(Context context, Cursor c) {
super(context, c);
// TODO Auto-generated constructor stub
}
/**
*
* @param context
* @param cursor
* @param parent
* @return
*/
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// 创建自定义的文件夹列表项
return new FolderListItem(context);
}
/**
*
* @param view
* @param context
* @param cursor
*/
@Override
public void bindView(View view, Context context, Cursor cursor) {
// 检查视图类型是否正确
if (view instanceof FolderListItem) {
// 根据ID判断文件夹名称根文件夹显示特殊文本其他文件夹显示实际名称
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);
// 根据ID判断文件夹名称根文件夹显示"父文件夹",其他显示实际名称
return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
}
/**
*
*
*/
private class FolderListItem extends LinearLayout {
private TextView mName;
private TextView mName; // 显示文件夹名称的文本视图
/**
*
* @param context
*/
public FolderListItem(Context context) {
super(context);
// 从布局文件加载视图
inflate(context, R.layout.folder_list_item, this);
// 查找名称文本视图
mName = (TextView) findViewById(R.id.tv_folder_name);
}
/**
*
* @param name
*/
public void bind(String name) {
// 设置文件夹名称文本
mName.setText(name);
}
}
}
}

File diff suppressed because it is too large Load Diff

@ -37,115 +37,167 @@ import net.micode.notes.R;
import java.util.HashMap;
import java.util.Map;
/**
*
*
*/
public class NoteEditText extends EditText {
private static final String TAG = "NoteEditText";
private int mIndex;
private int mSelectionStartBeforeDelete;
private int mIndex; // 当前编辑框在清单列表中的索引位置
private int mSelectionStartBeforeDelete; // 记录删除操作前光标起始位置
private static final String SCHEME_TEL = "tel:" ;
private static final String SCHEME_HTTP = "http:" ;
private static final String SCHEME_EMAIL = "mailto:" ;
// 链接协议常量定义
private static final String SCHEME_TEL = "tel:" ; // 电话协议
private static final String SCHEME_HTTP = "http:" ; // 网页协议
private static final String SCHEME_EMAIL = "mailto:" ; // 邮件协议
// 链接协议与对应字符串资源的映射表
private static final Map<String, Integer> sSchemaActionResMap = new HashMap<String, Integer>();
static {
sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel);
sSchemaActionResMap.put(SCHEME_HTTP, R.string.note_link_web);
sSchemaActionResMap.put(SCHEME_EMAIL, R.string.note_link_email);
sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel); // 电话 -> "拨打电话"
sSchemaActionResMap.put(SCHEME_HTTP, R.string.note_link_web); // 网页 -> "打开网页"
sSchemaActionResMap.put(SCHEME_EMAIL, R.string.note_link_email); // 邮件 -> "发送邮件"
}
/**
* Call by the {@link NoteEditActivity} to delete or add edit text
*
* NoteEditActivity
*/
public interface OnTextViewChangeListener {
/**
* Delete current edit text when {@link KeyEvent#KEYCODE_DEL} happens
* and the text is null
*
* @param index
* @param text
*/
void onEditTextDelete(int index, String text);
/**
* Add edit text after current edit text when {@link KeyEvent#KEYCODE_ENTER}
* happen
*
* @param index +1
* @param text
*/
void onEditTextEnter(int index, String text);
/**
* Hide or show item option when text change
*
* @param index
* @param hasText
*/
void onTextChange(int index, boolean hasText);
}
private OnTextViewChangeListener mOnTextViewChangeListener;
/**
* 1Context
*/
public NoteEditText(Context context) {
super(context, null);
mIndex = 0;
mIndex = 0; // 初始化索引为0
}
/**
*
* @param index
*/
public void setIndex(int index) {
mIndex = index;
}
/**
*
* @param listener
*/
public void setOnTextViewChangeListener(OnTextViewChangeListener listener) {
mOnTextViewChangeListener = listener;
}
/**
* 2ContextAttributeSetXML使
*/
public NoteEditText(Context context, AttributeSet attrs) {
super(context, attrs, android.R.attr.editTextStyle);
}
/**
* 3ContextAttributeSet
*/
public NoteEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
/**
* -
*
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
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();
// 根据y坐标找到对应的行号
int line = layout.getLineForVertical(y);
// 根据x坐标在该行找到对应的字符偏移量
int off = layout.getOffsetForHorizontal(line, x);
// 将光标设置到计算出的偏移量位置
Selection.setSelection(getText(), off);
break;
}
// 调用父类方法处理其他触摸逻辑(如长按弹出菜单)
return super.onTouchEvent(event);
}
/**
*
*
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_ENTER:
case KeyEvent.KEYCODE_ENTER: // 回车键
if (mOnTextViewChangeListener != null) {
// 如果监听器存在返回false让onKeyUp处理
return false;
}
break;
case KeyEvent.KEYCODE_DEL:
case KeyEvent.KEYCODE_DEL: // 删除键(退格键)
// 记录删除前光标的起始位置用于在onKeyUp中判断是否在行首
mSelectionStartBeforeDelete = getSelectionStart();
break;
default:
break;
}
// 其他按键交给父类处理
return super.onKeyDown(keyCode, event);
}
/**
* -
*
*/
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch(keyCode) {
case KeyEvent.KEYCODE_DEL:
if (mOnTextViewChangeListener != null) {
// 判断条件光标在行首位置0且不是第一个编辑框索引不为0
if (0 == mSelectionStartBeforeDelete && mIndex != 0) {
// 触发删除监听通知Activity删除当前编辑框
mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString());
return true;
return true; // 消费此事件,阻止父类处理
}
} else {
Log.d(TAG, "OnTextViewChangeListener was not seted");
@ -153,9 +205,13 @@ public class NoteEditText extends EditText {
break;
case KeyEvent.KEYCODE_ENTER:
if (mOnTextViewChangeListener != null) {
// 获取当前光标位置
int selectionStart = getSelectionStart();
// 截取从光标位置到文本末尾的内容
String text = getText().subSequence(selectionStart, length()).toString();
// 将当前编辑框的文本设置为光标前的内容
setText(getText().subSequence(0, selectionStart));
// 触发回车监听通知Activity插入新编辑框并传递截取的文本
mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text);
} else {
Log.d(TAG, "OnTextViewChangeListener was not seted");
@ -167,51 +223,72 @@ public class NoteEditText extends EditText {
return super.onKeyUp(keyCode, event);
}
/**
*
*
*/
@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);
}
/**
*
*
*/
@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;
int defaultResId = 0; // 菜单项文本的资源ID
// 遍历协议映射检查链接的URL包含哪种协议
for(String schema: sSchemaActionResMap.keySet()) {
if(urls[0].getURL().indexOf(schema) >= 0) {
// 找到匹配的协议获取对应的字符串资源ID
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) {
// goto a new intent
// 触发链接的默认行为(如打开浏览器、拨号盘等)
urls[0].onClick(NoteEditText.this);
return true;
return true; // 消费此事件
}
});
}
}
// 调用父类方法添加系统默认的菜单项(复制、粘贴等)
super.onCreateContextMenu(menu);
}
}
}

@ -25,200 +25,343 @@ import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.tool.DataUtils;
/**
*
* Cursor
* 使JavaPOJO
*
*/
public class NoteItemData {
/**
* Projection
*
*/
static final String [] PROJECTION = new String [] {
NoteColumns.ID,
NoteColumns.ALERTED_DATE,
NoteColumns.BG_COLOR_ID,
NoteColumns.CREATED_DATE,
NoteColumns.HAS_ATTACHMENT,
NoteColumns.MODIFIED_DATE,
NoteColumns.NOTES_COUNT,
NoteColumns.PARENT_ID,
NoteColumns.SNIPPET,
NoteColumns.TYPE,
NoteColumns.WIDGET_ID,
NoteColumns.WIDGET_TYPE,
NoteColumns.ID, // 笔记ID
NoteColumns.ALERTED_DATE, // 提醒日期
NoteColumns.BG_COLOR_ID, // 背景颜色ID
NoteColumns.CREATED_DATE, // 创建日期
NoteColumns.HAS_ATTACHMENT, // 是否有附件
NoteColumns.MODIFIED_DATE, // 最后修改日期
NoteColumns.NOTES_COUNT, // 包含的笔记数量(针对文件夹)
NoteColumns.PARENT_ID, // 父文件夹ID
NoteColumns.SNIPPET, // 内容摘要/片段
NoteColumns.TYPE, // 类型(笔记、文件夹、系统文件夹等)
NoteColumns.WIDGET_ID, // 关联的小部件ID
NoteColumns.WIDGET_TYPE, // 小部件类型
};
private static final int ID_COLUMN = 0;
private static final int ALERTED_DATE_COLUMN = 1;
private static final int BG_COLOR_ID_COLUMN = 2;
private static final int CREATED_DATE_COLUMN = 3;
private static final int HAS_ATTACHMENT_COLUMN = 4;
private static final int MODIFIED_DATE_COLUMN = 5;
private static final int NOTES_COUNT_COLUMN = 6;
private static final int PARENT_ID_COLUMN = 7;
private static final int SNIPPET_COLUMN = 8;
private static final int TYPE_COLUMN = 9;
private static final int WIDGET_ID_COLUMN = 10;
private static final int WIDGET_TYPE_COLUMN = 11;
private long mId;
private long mAlertDate;
private int mBgColorId;
private long mCreatedDate;
private boolean mHasAttachment;
private long mModifiedDate;
private int mNotesCount;
private long mParentId;
private String mSnippet;
private int mType;
private int mWidgetId;
private int mWidgetType;
private String mName;
private String mPhoneNumber;
private boolean mIsLastItem;
private boolean mIsFirstItem;
private boolean mIsOnlyOneItem;
private boolean mIsOneNoteFollowingFolder;
private boolean mIsMultiNotesFollowingFolder;
/**
* PROJECTION
* 使0,1,2
*/
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; // 是否有附件true/false
private long mModifiedDate; // 最后修改时间戳(毫秒)
private int mNotesCount; // 文件夹中包含的笔记数量(如果是文件夹的话)
private long mParentId; // 父文件夹的ID
private String mSnippet; // 笔记内容的摘要/片段(用于列表显示)
private int mType; // 类型(笔记、文件夹、系统文件夹等)
private int mWidgetId; // 关联的桌面小部件ID
private int mWidgetType; // 桌面小部件的类型
// 额外添加的业务逻辑相关字段(不直接来自数据库)
private String mName; // 联系人姓名(如果是通话记录笔记)
private String mPhoneNumber; // 电话号码(如果是通话记录笔记)
// 位置状态标志,用于判断当前项在列表中的位置关系
private boolean mIsLastItem; // 是否是列表中的最后一项
private boolean mIsFirstItem; // 是否是列表中的第一项
private boolean mIsOnlyOneItem; // 是否是列表中唯一的一项
private boolean mIsOneNoteFollowingFolder; // 是否是一个紧跟在文件夹后面的笔记
private boolean mIsMultiNotesFollowingFolder; // 是否是多个紧跟在文件夹后面的笔记之一
/**
* Cursor
* @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);
// 将整数值转换为布尔值大于0表示有附件true否则为false
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) {
// 根据笔记ID查询对应的电话号码
mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId);
if (!TextUtils.isEmpty(mPhoneNumber)) {
// 如果电话号码不为空,通过联系人提供者查询对应的联系人姓名
mName = Contact.getContact(context, mPhoneNumber);
if (mName == null) {
// 如果查询不到联系人,则用电话号码本身作为显示名称
mName = mPhoneNumber;
}
}
}
// 确保姓名不为null避免后续使用时报错
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);
// 使用游标的方法判断位置
mIsLastItem = cursor.isLast() ? true : false; // 是否是最后一项
mIsFirstItem = cursor.isFirst() ? true : false; // 是否是第一项
mIsOnlyOneItem = (cursor.getCount() == 1); // 是否只有一项
// 初始化位置关系标志为false
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) {
// 判断当前项后面是否还有其他项
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");
}
}
}
}
// ========== 以下是一系列的getter方法用于外部获取对象的属性值 ==========
/**
*
* @return true
*/
public boolean isOneFollowingFolder() {
return mIsOneNoteFollowingFolder;
}
/**
*
* @return true
*/
public boolean isMultiFollowingFolder() {
return mIsMultiNotesFollowingFolder;
}
/**
*
* @return true
*/
public boolean isLast() {
return mIsLastItem;
}
/**
*
* @return
*/
public String getCallName() {
return mName;
}
/**
*
* @return true
*/
public boolean isFirst() {
return mIsFirstItem;
}
/**
*
* @return true
*/
public boolean isSingle() {
return mIsOnlyOneItem;
}
/**
* /ID
* @return ID
*/
public long getId() {
return mId;
}
/**
*
* @return
*/
public long getAlertDate() {
return mAlertDate;
}
/**
*
* @return
*/
public long getCreatedDate() {
return mCreatedDate;
}
/**
*
* @return truefalse
*/
public boolean hasAttachment() {
return mHasAttachment;
}
/**
*
* @return
*/
public long getModifiedDate() {
return mModifiedDate;
}
/**
* ID
* @return ID
*/
public int getBgColorId() {
return mBgColorId;
}
/**
* ID
* @return ID
*/
public long getParentId() {
return mParentId;
}
/**
*
* @return
*/
public int getNotesCount() {
return mNotesCount;
}
/**
* IDgetParentId()
* @return ID
*/
public long getFolderId () {
return mParentId;
}
/**
*
* @return
*/
public int getType() {
return mType;
}
/**
*
* @return
*/
public int getWidgetType() {
return mWidgetType;
}
/**
* ID
* @return ID
*/
public int getWidgetId() {
return mWidgetId;
}
/**
* /
* @return
*/
public String getSnippet() {
return mSnippet;
}
/**
*
* @return truemAlertDate > 0
*/
public boolean hasAlert() {
return (mAlertDate > 0);
}
/**
*
*
* @return true
*/
public boolean isCallRecord() {
return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber));
}
/**
*
* NoteItemData
* @param cursor
* @return
*/
public static int getNoteType(Cursor cursor) {
return cursor.getInt(TYPE_COLUMN);
}
}
}

File diff suppressed because it is too large Load Diff

@ -30,58 +30,110 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
/**
*
* CursorAdapter
*/
public class NotesListAdapter extends CursorAdapter {
private static final String TAG = "NotesListAdapter";
private Context mContext;
private Context mContext; // 上下文对象
// 存储选中状态的映射表key为位置索引value为是否选中
private HashMap<Integer, Boolean> mSelectedIndex;
private int mNotesCount;
private boolean mChoiceMode;
private int mNotesCount; // 笔记总数(不包括文件夹)
private boolean mChoiceMode; // 标记是否处于多选模式
/**
*
*/
public static class AppWidgetAttribute {
public int widgetId;
public int widgetType;
public int widgetId; // 小部件的唯一标识ID
public int widgetType; // 小部件的类型如2x2、4x4等
};
/**
*
* @param context
*/
public NotesListAdapter(Context context) {
super(context, null);
mSelectedIndex = new HashMap<Integer, Boolean>();
super(context, null); // 调用父类构造函数初始游标为null
mSelectedIndex = new HashMap<Integer, Boolean>(); // 初始化选中状态记录表
mContext = context;
mNotesCount = 0;
mNotesCount = 0; // 初始笔记数量为0
}
/**
*
* @param context
* @param cursor
* @param parent
* @return
*/
@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 truefalse
*/
public void setCheckedItem(final int position, final boolean checked) {
// 更新选中状态映射表
mSelectedIndex.put(position, checked);
// 通知数据发生变化,需要刷新列表显示
notifyDataSetChanged();
}
/**
*
* @return truefalse
*/
public boolean isInChoiceMode() {
return mChoiceMode;
}
/**
*
* @param mode truefalse退
*/
public void setChoiceMode(boolean mode) {
// 清空所有选中状态记录
mSelectedIndex.clear();
mChoiceMode = mode;
}
/**
*
* @param checked truefalse
*/
public void selectAll(boolean checked) {
// 获取当前数据游标
Cursor cursor = getCursor();
// 遍历所有列表项
for (int i = 0; i < getCount(); i++) {
// 将游标移动到指定位置
if (cursor.moveToPosition(i)) {
// 只对笔记类型进行选中操作,跳过文件夹
if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) {
setCheckedItem(i, checked);
}
@ -89,14 +141,24 @@ public class NotesListAdapter extends CursorAdapter {
}
}
/**
* ID
* @return ID
*/
public HashSet<Long> getSelectedItemIds() {
// 创建ID集合
HashSet<Long> itemSet = new HashSet<Long>();
// 遍历所有记录的位置
for (Integer position : mSelectedIndex.keySet()) {
// 检查该位置是否被选中
if (mSelectedIndex.get(position) == true) {
// 获取该项的笔记ID
Long id = getItemId(position);
// 安全检查确保不是根文件夹的ID
if (id == Notes.ID_ROOT_FOLDER) {
Log.d(TAG, "Wrong item id, should not happen");
} else {
// 将有效ID添加到集合中
itemSet.add(id);
}
}
@ -105,19 +167,30 @@ public class NotesListAdapter extends CursorAdapter {
return itemSet;
}
/**
*
* @return
*/
public HashSet<AppWidgetAttribute> getSelectedWidget() {
// 创建小部件属性集合
HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>();
// 遍历所有选中项
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);
/**
* Don't close cursor here, only the adapter could close it
*
*
*/
} else {
Log.e(TAG, "Invalid cursor");
@ -128,14 +201,21 @@ public class NotesListAdapter extends CursorAdapter {
return itemSet;
}
/**
*
* @return
*/
public int getSelectedCount() {
// 获取所有选中状态值
Collection<Boolean> values = mSelectedIndex.values();
if (null == values) {
return 0;
}
// 使用迭代器遍历统计选中数量
Iterator<Boolean> iter = values.iterator();
int count = 0;
while (iter.hasNext()) {
// 如果状态为true计数加1
if (true == iter.next()) {
count++;
}
@ -143,37 +223,65 @@ public class NotesListAdapter extends CursorAdapter {
return count;
}
/**
*
* @return truefalse
*/
public boolean isAllSelected() {
// 获取当前选中数量
int checkedCount = getSelectedCount();
// 全选条件选中数量等于笔记总数且不为0
return (checkedCount != 0 && checkedCount == mNotesCount);
}
/**
*
* @param position
* @return truefalse
*/
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;
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++;
mNotesCount++; // 笔记数量加1
}
} else {
Log.e(TAG, "Invalid cursor");
@ -181,4 +289,4 @@ public class NotesListAdapter extends CursorAdapter {
}
}
}
}
}

@ -29,94 +29,143 @@ import net.micode.notes.data.Notes;
import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.ResourceParser.NoteItemBgResources;
/**
*
* LinearLayout
*/
public class NotesListItem extends LinearLayout {
private ImageView mAlert;
private TextView mTitle;
private TextView mTime;
private TextView mCallName;
private NoteItemData mItemData;
private CheckBox mCheckBox;
private ImageView mAlert; // 提醒图标(时钟或通话记录图标)
private TextView mTitle; // 标题/内容文本
private TextView mTime; // 修改时间文本
private TextView mCallName; // 通话记录联系人姓名
private NoteItemData mItemData; // 绑定的数据对象
private CheckBox mCheckBox; // 多选模式下的复选框
/**
*
* @param context
*/
public NotesListItem(Context context) {
super(context);
// 从布局文件加载视图
inflate(context, R.layout.note_item, this);
// 初始化各个子视图组件
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);
// 使用系统预定义的checkbox ID
mCheckBox = (CheckBox) findViewById(android.R.id.checkbox);
}
/**
* UI
* @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;
// 根据数据类型显示不同的UI布局
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
mCallName.setVisibility(View.GONE);
mAlert.setVisibility(View.VISIBLE);
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
// 通话记录文件夹的特殊显示
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);
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()));
// 通话记录笔记的特殊显示
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.setImageResource(R.drawable.clock); // 时钟图标
mAlert.setVisibility(View.VISIBLE);
} else {
mAlert.setVisibility(View.GONE);
}
} else {
mCallName.setVisibility(View.GONE);
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
// 普通笔记或文件夹的显示
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);
data.getNotesCount()));
mAlert.setVisibility(View.GONE); // 文件夹不显示提醒图标
} else {
// 普通笔记显示:内容摘要
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
// 根据是否有提醒设置提醒图标
if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock);
mAlert.setImageResource(R.drawable.clock); // 时钟图标
mAlert.setVisibility(View.VISIBLE);
} else {
mAlert.setVisibility(View.GONE);
}
}
}
// 设置相对时间显示(如"2分钟前"、"昨天"等)
mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate()));
// 根据位置和类型设置背景
setBackground(data);
}
/**
*
*
* @param data
*/
private void setBackground(NoteItemData data) {
int id = data.getBgColorId();
int id = data.getBgColorId(); // 获取背景颜色ID
if (data.getType() == Notes.TYPE_NOTE) {
// 笔记类型的背景设置
if (data.isSingle() || data.isOneFollowingFolder()) {
// 单个笔记或紧跟在文件夹后的单个笔记:单一样式背景
setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id));
} else if (data.isLast()) {
// 列表中的最后一个笔记:底部样式背景
setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id));
} else if (data.isFirst() || data.isMultiFollowingFolder()) {
// 列表中的第一个笔记或多个紧跟在文件夹后的笔记:顶部样式背景
setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id));
} else {
// 中间位置的笔记:普通样式背景
setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id));
}
} else {
// 文件夹类型的背景:统一使用文件夹背景
setBackgroundResource(NoteItemBgResources.getFolderBgRes());
}
}
/**
*
* @return NoteItemData
*/
public NoteItemData getItemData() {
return mItemData;
}
}
}

@ -47,55 +47,67 @@ import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.remote.GTaskSyncService;
/**
*
* PreferenceActivityGoogle
*/
public class NotesPreferenceActivity extends PreferenceActivity {
// 偏好设置文件名
public static final String PREFERENCE_NAME = "notes_preferences";
// 同步账户名称的键
public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name";
// 最后同步时间的键
public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time";
// 背景颜色设置的键
public static final String PREFERENCE_SET_BG_COLOR_KEY = "pref_key_bg_random_appear";
// 同步账户分类的键
private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key";
// 账户权限过滤器键
private static final String AUTHORITIES_FILTER_KEY = "authorities";
private PreferenceCategory mAccountCategory;
private GTaskReceiver mReceiver;
private Account[] mOriAccounts;
private boolean mHasAddedAccount;
private PreferenceCategory mAccountCategory; // 账户设置分类
private GTaskReceiver mReceiver; // 同步服务广播接收器
private Account[] mOriAccounts; // 原始账户列表
private boolean mHasAddedAccount; // 标记是否添加了新账户
/**
* Activity
*/
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
/* using the app icon for navigation */
// 在ActionBar中显示返回按钮
getActionBar().setDisplayHomeAsUpEnabled(true);
// 从XML资源加载偏好设置
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);
}
/**
* Activity
*/
@Override
protected void onResume() {
super.onResume();
// need to set sync account automatically if user has added a new
// account
// 如果用户添加了新账户,自动设置同步账户
if (mHasAddedAccount) {
Account[] accounts = getGoogleAccounts();
// 比较新旧账户列表,找到新添加的账户
if (mOriAccounts != null && accounts.length > mOriAccounts.length) {
for (Account accountNew : accounts) {
boolean found = false;
@ -106,6 +118,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}
}
if (!found) {
// 设置新账户为同步账户
setSyncAccount(accountNew.name);
break;
}
@ -113,9 +126,13 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}
}
// 刷新界面显示
refreshUI();
}
/**
* Activity
*/
@Override
protected void onDestroy() {
if (mReceiver != null) {
@ -124,8 +141,11 @@ public class NotesPreferenceActivity extends PreferenceActivity {
super.onDestroy();
}
/**
*
*/
private void loadAccountPreference() {
mAccountCategory.removeAll();
mAccountCategory.removeAll(); // 清空现有设置项
Preference accountPref = new Preference(this);
final String defaultAccount = getSyncAccountName(this);
@ -133,18 +153,18 @@ public class NotesPreferenceActivity extends PreferenceActivity {
accountPref.setSummary(getString(R.string.preferences_account_summary));
accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
// 检查是否正在同步,同步过程中不允许修改账户
if (!GTaskSyncService.isSyncing()) {
if (TextUtils.isEmpty(defaultAccount)) {
// the first time to set account
// 首次设置账户,显示选择账户对话框
showSelectAccountAlertDialog();
} else {
// if the account has already been set, we need to promp
// user about the risk
// 已设置过账户,显示确认对话框
showChangeAccountConfirmAlertDialog();
}
} else {
Toast.makeText(NotesPreferenceActivity.this,
R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT)
R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT)
.show();
}
return true;
@ -154,11 +174,14 @@ public class NotesPreferenceActivity extends PreferenceActivity {
mAccountCategory.addPreference(accountPref);
}
/**
*
*/
private void loadSyncButton() {
Button syncButton = (Button) findViewById(R.id.preference_sync_button);
TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
// set button state
// 根据同步状态设置按钮文本和点击事件
if (GTaskSyncService.isSyncing()) {
syncButton.setText(getString(R.string.preferences_button_sync_cancel));
syncButton.setOnClickListener(new View.OnClickListener() {
@ -174,33 +197,44 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}
});
}
// 只有设置了同步账户才能启用同步按钮
syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this)));
// set last sync time
// 设置最后同步时间显示
if (GTaskSyncService.isSyncing()) {
// 显示同步进度
lastSyncTimeView.setText(GTaskSyncService.getProgressString());
lastSyncTimeView.setVisibility(View.VISIBLE);
} 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);
}
}
}
/**
*
*/
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));
@ -208,45 +242,49 @@ public class NotesPreferenceActivity extends PreferenceActivity {
subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips));
dialogBuilder.setCustomTitle(titleView);
dialogBuilder.setPositiveButton(null, null);
dialogBuilder.setPositiveButton(null, null); // 不显示确定按钮
Account[] accounts = getGoogleAccounts();
String defAccount = getSyncAccountName(this);
mOriAccounts = accounts;
mHasAddedAccount = false;
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;
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();
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;
mHasAddedAccount = true; // 标记正在添加账户
// 启动系统添加账户界面
Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] {
"gmail-ls"
"gmail-ls" // 限制只显示Gmail账户
});
startActivityForResult(intent, -1);
dialog.dismiss();
@ -254,17 +292,21 @@ public class NotesPreferenceActivity extends PreferenceActivity {
});
}
/**
*
*/
private void showChangeAccountConfirmAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_change_account_title,
getSyncAccountName(this)));
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),
@ -273,22 +315,32 @@ public class NotesPreferenceActivity extends PreferenceActivity {
dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
// 更改账户
showSelectAccountAlertDialog();
} else if (which == 1) {
// 移除账户
removeSyncAccount();
refreshUI();
}
// which == 2 取消操作,不做任何事
}
});
dialogBuilder.show();
}
/**
* Google
*/
private Account[] getGoogleAccounts() {
AccountManager accountManager = AccountManager.get(this);
return accountManager.getAccountsByType("com.google");
return accountManager.getAccountsByType("com.google"); // Google账户类型
}
/**
*
*/
private void setSyncAccount(String account) {
// 只有当账户发生变化时才更新
if (!getSyncAccountName(this).equals(account)) {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
@ -299,15 +351,15 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}
editor.commit();
// clean up last sync time
// 重置最后同步时间
setLastSyncTime(this, 0);
// clean up local gtask related info
// 在新线程中清理本地同步信息
new Thread(new Runnable() {
public void run() {
ContentValues values = new ContentValues();
values.put(NoteColumns.GTASK_ID, "");
values.put(NoteColumns.SYNC_ID, 0);
values.put(NoteColumns.GTASK_ID, ""); // 清空任务ID
values.put(NoteColumns.SYNC_ID, 0); // 重置同步ID
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
}
}).start();
@ -318,9 +370,13 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}
}
/**
*
*/
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);
}
@ -329,7 +385,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}
editor.commit();
// clean up local gtask related info
// 在新线程中清理本地同步信息
new Thread(new Runnable() {
public void run() {
ContentValues values = new ContentValues();
@ -340,12 +396,18 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}).start();
}
/**
*
*/
public static String getSyncAccountName(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
}
/**
*
*/
public static void setLastSyncTime(Context context, long time) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
@ -354,29 +416,38 @@ public class NotesPreferenceActivity extends PreferenceActivity {
editor.commit();
}
/**
*
*/
public static long getLastSyncTime(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0);
}
/**
* 广
*/
private class GTaskReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
refreshUI();
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);
@ -385,4 +456,4 @@ public class NotesPreferenceActivity extends PreferenceActivity {
return false;
}
}
}
}

@ -15,6 +15,7 @@
*/
package net.micode.notes.widget;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
@ -32,101 +33,181 @@ import net.micode.notes.tool.ResourceParser;
import net.micode.notes.ui.NoteEditActivity;
import net.micode.notes.ui.NotesListActivity;
/**
* 便
* 便
*
*/
public abstract class NoteWidgetProvider extends AppWidgetProvider {
/**
* -
*/
public static final String [] PROJECTION = new String [] {
NoteColumns.ID,
NoteColumns.BG_COLOR_ID,
NoteColumns.SNIPPET
NoteColumns.ID, // 便签ID
NoteColumns.BG_COLOR_ID, // 背景颜色ID
NoteColumns.SNIPPET // 便签内容摘要
};
public static final int COLUMN_ID = 0;
public static final int COLUMN_BG_COLOR_ID = 1;
public static final int COLUMN_SNIPPET = 2;
/**
*
*/
public static final int COLUMN_ID = 0; // ID列索引
public static final int COLUMN_BG_COLOR_ID = 1; // 背景颜色ID列索引
public static final int COLUMN_SNIPPET = 2; // 内容摘要列索引
/**
*
*/
private static final String TAG = "NoteWidgetProvider";
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
/**
*
*
*/
// 创建内容值用于清除小部件ID关联
ContentValues values = new ContentValues();
values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
// 遍历所有被删除的小部件ID
for (int i = 0; i < appWidgetIds.length; i++) {
// 更新数据库将对应的小部件ID设为无效值
context.getContentResolver().update(Notes.CONTENT_NOTE_URI,
values,
NoteColumns.WIDGET_ID + "=?",
NoteColumns.WIDGET_ID + "=?", // 条件小部件ID匹配
new String[] { String.valueOf(appWidgetIds[i])});
}
}
/**
* 便
* @param context
* @param widgetId ID
* @return 便Cursor
*/
private Cursor getNoteWidgetInfo(Context context, int widgetId) {
/**
* 便
* ID
*/
return context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
PROJECTION,
NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>?",
PROJECTION, // 查询的列
NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>?", // 查询条件
new String[] { String.valueOf(widgetId), String.valueOf(Notes.ID_TRASH_FOLER) },
null);
null); // 排序方式(无)
}
/**
*
* @param context
* @param appWidgetManager
* @param appWidgetIds ID
*/
protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// 调用私有更新方法,默认非隐私模式
update(context, appWidgetManager, appWidgetIds, false);
}
/**
*
* @param context
* @param appWidgetManager
* @param appWidgetIds ID
* @param privacyMode true:false:便
*/
private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds,
boolean privacyMode) {
boolean privacyMode) {
// 遍历所有需要更新的小部件
for (int i = 0; i < appWidgetIds.length; i++) {
// 检查小部件ID是否有效
if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) {
// 初始化默认背景颜色和内容摘要
int bgId = ResourceParser.getDefaultBgId(context);
String snippet = "";
// 创建点击小部件时启动的Intent指向便签编辑页面
Intent intent = new Intent(context, NoteEditActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, appWidgetIds[i]);
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, getWidgetType());
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); // 单例模式
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, appWidgetIds[i]); // 传递小部件ID
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;
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);
// 从数据库读取便签信息
snippet = c.getString(COLUMN_SNIPPET); // 获取内容摘要
bgId = c.getInt(COLUMN_BG_COLOR_ID); // 获取背景颜色ID
intent.putExtra(Intent.EXTRA_UID, c.getLong(COLUMN_ID)); // 传递便签ID
intent.setAction(Intent.ACTION_VIEW); // 设置为查看动作
} else {
// 没有找到关联的便签,显示默认内容
snippet = context.getResources().getString(R.string.widget_havenot_content);
intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
intent.setAction(Intent.ACTION_INSERT_OR_EDIT); // 设置为新建/编辑动作
}
// 关闭Cursor释放资源
if (c != null) {
c.close();
}
// 创建RemoteViews对象用于更新小部件界面
RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId());
// 设置小部件背景图片
rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId));
intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId);
intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId); // 传递背景颜色ID
/**
* Generate the pending intent to start host for the widget
* 宿ActivityPendingIntent
*
*/
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);
}
}
}
/**
* IDID
*
* @param bgId ID
* @return ID
*/
protected abstract int getBgResourceId(int bgId);
/**
* ID
*
* @return ID
*/
protected abstract int getLayoutId();
/**
*
*
* @return
*/
protected abstract int getWidgetType();
}
}

@ -23,25 +23,65 @@ import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.ResourceParser;
/**
* 2x2便
* NoteWidgetProvider2x2
* 2x2便
*/
public class NoteWidgetProvider_2x extends NoteWidgetProvider {
/**
*
*
*
* @param context
* @param appWidgetManager
* @param appWidgetIds ID
*/
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// 调用父类的通用更新逻辑,避免重复代码
// 父类已经实现了数据查询、界面更新等通用功能
super.update(context, appWidgetManager, appWidgetIds);
}
/**
* ID
* 2x2
*
* @return 2x2ID
*/
@Override
protected int getLayoutId() {
// 返回2x2尺寸小部件的布局文件
// R.layout.widget_2x 定义了2x2小部件的界面结构
return R.layout.widget_2x;
}
/**
* ID2x2ID
* 2x2
*
* @param bgId IDNotes.COLOR_YELLOW, Notes.COLOR_BLUE
* @return 2x2ID
*/
@Override
protected int getBgResourceId(int bgId) {
// 通过资源解析器获取2x2尺寸专用的背景图片
// 不同的颜色ID对应不同的背景图片资源
return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId);
}
/**
*
* 2x2
*
* @return 2x2
*/
@Override
protected int getWidgetType() {
// 返回2x2小部件的类型常量用于区分不同尺寸的小部件
// 在数据存储和Intent传递中标识这是2x2尺寸的小部件
return Notes.TYPE_WIDGET_2X;
}
}
}

@ -23,24 +23,69 @@ import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.ResourceParser;
/**
* 4x4便
* NoteWidgetProvider4x4
* 4x4便
*/
public class NoteWidgetProvider_4x extends NoteWidgetProvider {
/**
*
*
* 4x4使2x2
*
* @param context 访
* @param appWidgetManager
* @param appWidgetIds ID
*/
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// 直接调用父类的通用更新逻辑,避免代码重复
// 父类已实现数据查询、界面绑定、点击事件等完整的小部件更新流程
super.update(context, appWidgetManager, appWidgetIds);
}
/**
* 4x4ID
* 4x4
* 4x42x2
*
* @return 4x4IDR.layout.widget_4x
*/
@Override
protected int getLayoutId() {
// 返回4x4尺寸专用的布局文件
// 该布局针对4x4网格进行了优化可能包含更大的文本区域或额外的显示元素
return R.layout.widget_4x;
}
/**
* ID4x4ID
* 4x4
* 4x42x2
*
* @param bgId IDNotes.COLOR_YELLOW, Notes.COLOR_BLUE
* @return 4x4ID
*/
@Override
protected int getBgResourceId(int bgId) {
// 通过资源解析器获取4x4尺寸专用的背景图片资源
// ResourceParser.WidgetBgResources.getWidget4xBgResource()专门处理4x4尺寸的背景映射
return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId);
}
/**
*
* 4x4
* Intent
*
* @return 4x4Notes.TYPE_WIDGET_4X
*/
@Override
protected int getWidgetType() {
// 返回4x4小部件的类型常量
// 这个值会存储在数据库中,用于关联便签数据和小部件实例
return Notes.TYPE_WIDGET_4X;
}
}
}
Loading…
Cancel
Save