diff --git a/app/src/main/java/net/micode/notes/tool/BackupUtils.java b/app/src/main/java/net/micode/notes/tool/BackupUtils.java index 39f6ec4..ddaf63d 100644 --- a/app/src/main/java/net/micode/notes/tool/BackupUtils.java +++ b/app/src/main/java/net/micode/notes/tool/BackupUtils.java @@ -39,37 +39,43 @@ import java.io.PrintStream; public class BackupUtils { private static final String TAG = "BackupUtils"; // Singleton stuff - private static BackupUtils sInstance; + private static BackupUtils sInstance; //类里面为什么可以定义自身类的对象? public static synchronized BackupUtils getInstance(Context context) { + //ynchronized 关键字,代表这个方法加锁,相当于不管哪一个线程(例如线程A) + //运行到这个方法时,都要检查有没有其它线程B(或者C、 D等)正在用这个方法(或者该类的其他同步方法),有的话要等正在使用synchronized方法的线程B(或者C 、D)运行完这个方法后再运行此线程A,没有的话,锁定调用者,然后直接运行。 + //它包括两种用法:synchronized 方法和 synchronized 块。 if (sInstance == null) { + //如果当前备份不存在,则新声明一个 sInstance = new BackupUtils(context); } return sInstance; } + /** * Following states are signs to represents backup or restore * status */ // Currently, the sdcard is not mounted public static final int STATE_SD_CARD_UNMOUONTED = 0; - // The backup file not exist + // The backup file not exist 备份文件夹不存在 public static final int STATE_BACKUP_FILE_NOT_EXIST = 1; - // The data is not well formated, may be changed by other programs + // The data is not well formated, may be changed by other programs 数据已被破坏,可能被修改 public static final int STATE_DATA_DESTROIED = 2; - // Some run-time exception which causes restore or backup fails + // Some run-time exception which causes restore or backup fails 超时异常 public static final int STATE_SYSTEM_ERROR = 3; - // Backup or restore success + // Backup or restore success 成功存储 public static final int STATE_SUCCESS = 4; + private TextExport mTextExport; - private BackupUtils(Context context) { + private BackupUtils(Context context) { //初始化函数 mTextExport = new TextExport(context); } - private static boolean externalStorageAvailable() { + private static boolean externalStorageAvailable() { //外部存储功能是否可用 return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); } @@ -132,7 +138,7 @@ public class BackupUtils { mFileDirectory = ""; } - private String getFormat(int id) { + private String getFormat(int id) { //获取文本的组成部分 return TEXT_FORMAT[id]; } @@ -140,28 +146,27 @@ public class BackupUtils { * Export the folder identified by folder id to text */ private void exportFolderToText(String folderId, PrintStream ps) { - // Query notes belong to this folder + // Query notes belong to this folder 通过查询parent id是文件夹id的note来选出制定ID文件夹下的Note Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI, NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] { - folderId + folderId }, null); if (notesCursor != null) { if (notesCursor.moveToFirst()) { do { - // Print note's last modified date + // Print note's last modified date ps里面保存有这份note的日期 ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format( mContext.getString(R.string.format_datetime_mdhm), notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); // Query data belong to this note String noteId = notesCursor.getString(NOTE_COLUMN_ID); - exportNoteToText(noteId, ps); + exportNoteToText(noteId, ps); //将文件导出到text } while (notesCursor.moveToNext()); } notesCursor.close(); } } - /** * Export note identified by id to a print stream */ @@ -171,7 +176,7 @@ public class BackupUtils { noteId }, null); - if (dataCursor != null) { + if (dataCursor != null) { //利用光标来扫描内容,区别为callnote和note两种,靠ps.printline输出 if (dataCursor.moveToFirst()) { do { String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE); @@ -181,7 +186,7 @@ public class BackupUtils { long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE); String location = dataCursor.getString(DATA_COLUMN_CONTENT); - if (!TextUtils.isEmpty(phoneNumber)) { + if (!TextUtils.isEmpty(phoneNumber)) { //判断是否为空字符 ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), phoneNumber)); } @@ -214,11 +219,10 @@ public class BackupUtils { Log.e(TAG, e.toString()); } } - /** * Note will be exported as text which is user readable */ - public int exportToText() { + public int exportToText() { //总函数,调用上面的exportFolder和exportNote if (!externalStorageAvailable()) { Log.d(TAG, "Media was not mounted"); return STATE_SD_CARD_UNMOUONTED; @@ -229,7 +233,7 @@ public class BackupUtils { Log.e(TAG, "get print stream error"); return STATE_SYSTEM_ERROR; } - // First export folder and its notes + // First export folder and its notes 导出文件夹,就是导出里面包含的便签 Cursor folderCursor = mContext.getContentResolver().query( Notes.CONTENT_NOTE_URI, NOTE_PROJECTION, @@ -257,7 +261,7 @@ public class BackupUtils { folderCursor.close(); } - // Export notes in root's folder + // Export notes in root's folder 将根目录里的便签导出(由于不属于任何文件夹,因此无法通过文件夹导出来实现这一部分便签的导出) Cursor noteCursor = mContext.getContentResolver().query( Notes.CONTENT_NOTE_URI, NOTE_PROJECTION, @@ -281,7 +285,6 @@ public class BackupUtils { return STATE_SUCCESS; } - /** * Get a print stream pointed to the file {@generateExportedTextFile} */ @@ -297,7 +300,7 @@ public class BackupUtils { PrintStream ps = null; try { FileOutputStream fos = new FileOutputStream(file); - ps = new PrintStream(fos); + ps = new PrintStream(fos); //将ps输出流输出到特定的文件,目的就是导出到文件,而不是直接输出 } catch (FileNotFoundException e) { e.printStackTrace(); return null; @@ -314,16 +317,16 @@ public class BackupUtils { */ 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(Environment.getExternalStorageDirectory()); //外部(SD卡)的存储路径 + sb.append(context.getString(filePathResId)); //文件的存储路径 + File filedir = new File(sb.toString()); //filedir应该就是用来存储路径信息 sb.append(context.getString( fileNameFormatResId, DateFormat.format(context.getString(R.string.format_date_ymd), System.currentTimeMillis()))); File file = new File(sb.toString()); - try { + try { //如果这些文件不存在,则新建 if (!filedir.exists()) { filedir.mkdir(); } @@ -336,7 +339,7 @@ public class BackupUtils { } catch (IOException e) { e.printStackTrace(); } - +// try catch 异常处理 return null; } } diff --git a/app/src/main/java/net/micode/notes/tool/DataUtils.java b/app/src/main/java/net/micode/notes/tool/DataUtils.java index 2a14982..d43b754 100644 --- a/app/src/main/java/net/micode/notes/tool/DataUtils.java +++ b/app/src/main/java/net/micode/notes/tool/DataUtils.java @@ -35,9 +35,10 @@ import java.util.ArrayList; import java.util.HashSet; + public class DataUtils { public static final String TAG = "DataUtils"; - public static boolean batchDeleteNotes(ContentResolver resolver, HashSet ids) { + public static boolean batchDeleteNotes(ContentResolver resolver, HashSet ids) { //直接删除多个笔记 if (ids == null) { Log.d(TAG, "the ids is null"); return true; @@ -47,18 +48,19 @@ public class DataUtils { return true; } - ArrayList operationList = new ArrayList(); + ArrayList operationList = new ArrayList(); //提供一个任务列表 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()); + .newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); //用newDelete实现删除功能 + operationList.add(builder.build()); // } try { - ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); + ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);//主机名(或叫Authority)用于唯一标识这个ContentProvider,外部调用者可以根据这个标识来找到它。 + //数据库事务,数据库事务是由一组数据库操作序列组成,事务作为一个整体被执行 if (results == null || results.length == 0 || results[0] == null) { Log.d(TAG, "delete notes failed, ids:" + ids.toString()); return false; @@ -72,16 +74,18 @@ public class DataUtils { return false; } + + 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); - resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null); + resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null); //对需要移动的便签进行数据更新,然后用update实现 } public static boolean batchMoveToFolder(ContentResolver resolver, HashSet ids, - long folderId) { + long folderId) { if (ids == null) { Log.d(TAG, "the ids is null"); return true; @@ -90,14 +94,14 @@ public class DataUtils { ArrayList operationList = new ArrayList(); for (long id : ids) { ContentProviderOperation.Builder builder = ContentProviderOperation - .newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); + .newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); //通过withAppendedId方法,为该Uri加上ID builder.withValue(NoteColumns.PARENT_ID, folderId); builder.withValue(NoteColumns.LOCAL_MODIFIED, 1); operationList.add(builder.build()); - } + }//将ids里包含的每一列的数据逐次加入到operationList中,等待最后的批量处理 try { - ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); + ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); //applyBatch一次性处理一个操作列表 if (results == null || results.length == 0 || results[0] == null) { Log.d(TAG, "delete notes failed, ids:" + ids.toString()); return false; @@ -119,7 +123,7 @@ public class DataUtils { new String[] { "COUNT(*)" }, NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?", new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)}, - null); + null); //筛选条件:源文件不为trash folder int count = 0; if(cursor != null) { @@ -137,15 +141,15 @@ public class DataUtils { } public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) { - Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), + Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), //通过withAppendedId方法,为该Uri加上ID null, NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER, new String [] {String.valueOf(type)}, - null); + null); //查询条件:type符合,且不属于垃圾文件夹 boolean exist = false; if (cursor != null) { - if (cursor.getCount() > 0) { + if (cursor.getCount() > 0) {//用getcount函数判断cursor是否为空 exist = true; } cursor.close(); @@ -153,6 +157,7 @@ public class DataUtils { return exist; } + public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) { Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null, null, null, null); @@ -184,9 +189,10 @@ public class DataUtils { 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) { if(cursor.getCount() > 0) { @@ -202,7 +208,7 @@ public class DataUtils { new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE }, NoteColumns.PARENT_ID + "=?", new String[] { String.valueOf(folderId) }, - null); + null); //查询条件:父ID是传入的folderId; HashSet set = null; if (c != null) { @@ -211,13 +217,13 @@ public class DataUtils { do { try { AppWidgetAttribute widget = new AppWidgetAttribute(); - widget.widgetId = c.getInt(0); - widget.widgetType = c.getInt(1); + widget.widgetId = c.getInt(0); //0对应的NoteColumns.WIDGET_ID + widget.widgetType = c.getInt(1); //1对应的NoteColumns.WIDGET_TYPE set.add(widget); } catch (IndexOutOfBoundsException e) { Log.e(TAG, e.toString()); } - } while (c.moveToNext()); + } while (c.moveToNext()); //查询下一条 } c.close(); } @@ -247,14 +253,15 @@ public class DataUtils { 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); + //通过数据库操作,查询条件是(callDate和phoneNumber匹配传入参数的值) if (cursor != null) { if (cursor.moveToFirst()) { try { - return cursor.getLong(0); + return cursor.getLong(0); //0对应的CallNote.NOTE_ID } catch (IndexOutOfBoundsException e) { Log.e(TAG, "Get call note id fails " + e.toString()); } @@ -264,12 +271,13 @@ public class DataUtils { return 0; } + public static String getSnippetById(ContentResolver resolver, long noteId) { Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, new String [] { NoteColumns.SNIPPET }, NoteColumns.ID + "=?", new String [] { String.valueOf(noteId)}, - null); + null);//查询条件:noteId if (cursor != null) { String snippet = ""; @@ -281,8 +289,7 @@ public class DataUtils { } throw new IllegalArgumentException("Note is not found with id: " + noteId); } - - public static String getFormattedSnippet(String snippet) { + public static String getFormattedSnippet(String snippet) { //对字符串进行格式处理,将字符串两头的空格去掉,同时将换行符去掉 if (snippet != null) { snippet = snippet.trim(); int index = snippet.indexOf('\n'); @@ -293,3 +300,5 @@ public class DataUtils { return snippet; } } + + diff --git a/app/src/main/java/net/micode/notes/tool/GTaskStringUtils.java b/app/src/main/java/net/micode/notes/tool/GTaskStringUtils.java index 666b729..5e82916 100644 --- a/app/src/main/java/net/micode/notes/tool/GTaskStringUtils.java +++ b/app/src/main/java/net/micode/notes/tool/GTaskStringUtils.java @@ -1,23 +1,9 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +//简介:定义了很多的静态字符串,目的就是为了提供jsonObject中相应字符串的"key"。把这些静态的定义单独写到了一个类里面,这是非常好的编程规范 package net.micode.notes.tool; +//这个类就是定义了一堆static string,实际就是为jsonObject提供Key,把这些定义全部写到一个类里,方便查看管理,是一个非常好的编程习惯 public class GTaskStringUtils { - public final static String GTASK_JSON_ACTION_ID = "action_id"; public final static String GTASK_JSON_ACTION_LIST = "action_list"; diff --git a/app/src/main/java/net/micode/notes/tool/ResourceParser.java b/app/src/main/java/net/micode/notes/tool/ResourceParser.java index 1ad3ad6..0e6ff03 100644 --- a/app/src/main/java/net/micode/notes/tool/ResourceParser.java +++ b/app/src/main/java/net/micode/notes/tool/ResourceParser.java @@ -22,38 +22,54 @@ import android.preference.PreferenceManager; import net.micode.notes.R; import net.micode.notes.ui.NotesPreferenceActivity; +/*简介:字面意义是资源分析器,实际上就是获取资源并且在程序中使用,比如颜色图片等 + * 实现方法:主要利用R.java这个类,其中包括 + * R.id 组件资源引用 + * R.drawable 图片资源 (被使用) + * R.layout 布局资源 + * R.menu 菜单资源 + * R.String 文字资源 + * R.style 主题资源 (被使用) + * 在按顺序设置好相应的id后,就可以编写简单的getXXX函数获取需要的资源 + * + * 特殊的变量 : + * @BG_DEFAULT_COLOR 默认背景颜色(黄) + * BG_DEFAULT_FONT_SIZE 默认文本大小(中) + */ + 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 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 TEXT_SMALL = 0; + public static final int TEXT_MEDIUM = 1; + public static final int TEXT_LARGE = 2; + public static final int TEXT_SUPER = 3; public static final int BG_DEFAULT_FONT_SIZE = TEXT_MEDIUM; + //直接获取默认的背景颜色。 public static class NoteBgResources { - private final static int [] BG_EDIT_RESOURCES = new int [] { - R.drawable.edit_yellow, - R.drawable.edit_blue, - R.drawable.edit_white, - R.drawable.edit_green, - R.drawable.edit_red + private final static int[] BG_EDIT_RESOURCES = new int[]{ + R.drawable.edit_yellow, + R.drawable.edit_blue, + R.drawable.edit_white, + R.drawable.edit_green, + R.drawable.edit_red }; - private final static int [] BG_EDIT_TITLE_RESOURCES = new int [] { - R.drawable.edit_title_yellow, - R.drawable.edit_title_blue, - R.drawable.edit_title_white, - R.drawable.edit_title_green, - R.drawable.edit_title_red + 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 }; public static int getNoteBgResource(int id) { @@ -75,36 +91,36 @@ public class ResourceParser { } public static class NoteItemBgResources { - private final static int [] BG_FIRST_RESOURCES = new int [] { - R.drawable.list_yellow_up, - R.drawable.list_blue_up, - R.drawable.list_white_up, - R.drawable.list_green_up, - R.drawable.list_red_up + private final static int[] BG_FIRST_RESOURCES = new int[]{ + R.drawable.list_yellow_up, + R.drawable.list_blue_up, + R.drawable.list_white_up, + R.drawable.list_green_up, + R.drawable.list_red_up }; - private final static int [] BG_NORMAL_RESOURCES = new int [] { - R.drawable.list_yellow_middle, - R.drawable.list_blue_middle, - R.drawable.list_white_middle, - R.drawable.list_green_middle, - R.drawable.list_red_middle + private final static int[] BG_NORMAL_RESOURCES = new int[]{ + R.drawable.list_yellow_middle, + R.drawable.list_blue_middle, + R.drawable.list_white_middle, + R.drawable.list_green_middle, + R.drawable.list_red_middle }; - private final static int [] BG_LAST_RESOURCES = new int [] { - R.drawable.list_yellow_down, - R.drawable.list_blue_down, - R.drawable.list_white_down, - R.drawable.list_green_down, - R.drawable.list_red_down, + private final static int[] BG_LAST_RESOURCES = new int[]{ + R.drawable.list_yellow_down, + R.drawable.list_blue_down, + R.drawable.list_white_down, + R.drawable.list_green_down, + R.drawable.list_red_down, }; - private final static int [] BG_SINGLE_RESOURCES = new int [] { - R.drawable.list_yellow_single, - R.drawable.list_blue_single, - R.drawable.list_white_single, - R.drawable.list_green_single, - R.drawable.list_red_single + 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 }; public static int getNoteBgFirstRes(int id) { @@ -129,24 +145,24 @@ public class ResourceParser { } public static class WidgetBgResources { - 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, + 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, }; public static int getWidget2xBgResource(int id) { return BG_2X_RESOURCES[id]; } - 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 + 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 }; public static int getWidget4xBgResource(int id) { @@ -155,13 +171,14 @@ public class ResourceParser { } public static class TextAppearanceResources { - private final static int [] TEXTAPPEARANCE_RESOURCES = new int [] { - R.style.TextAppearanceNormal, - R.style.TextAppearanceMedium, - R.style.TextAppearanceLarge, - R.style.TextAppearanceSuper + private final static int[] TEXTAPPEARANCE_RESOURCES = new int[]{ + R.style.TextAppearanceNormal, + R.style.TextAppearanceMedium, + R.style.TextAppearanceLarge, + R.style.TextAppearanceSuper }; + //这里有一个容错的函数,防止输入的id大于资源总量,若如此,则自动返回默认的设置结果 public static int getTexAppearanceResource(int id) { /** * HACKME: Fix bug of store the resource id in shared preference. @@ -179,3 +196,4 @@ public class ResourceParser { } } } + diff --git a/app/src/main/java/net/micode/notes/ui/DateTimePickerDialog.java b/app/src/main/java/net/micode/notes/ui/DateTimePickerDialog.java index 2c47ba4..d236a74 100644 --- a/app/src/main/java/net/micode/notes/ui/DateTimePickerDialog.java +++ b/app/src/main/java/net/micode/notes/ui/DateTimePickerDialog.java @@ -29,38 +29,51 @@ import android.content.DialogInterface.OnClickListener; import android.text.format.DateFormat; import android.text.format.DateUtils; + public class DateTimePickerDialog extends AlertDialog implements OnClickListener { private Calendar mDate = Calendar.getInstance(); + //创建一个Calendar类型的变量 mDate,方便时间的操作 private boolean mIs24HourView; private OnDateTimeSetListener mOnDateTimeSetListener; + //声明一个时间日期滚动选择控件 mOnDateTimeSetListener private DateTimePicker mDateTimePicker; + //DateTimePicker控件,控件一般用于让用户可以从日期列表中选择单个值。 + //运行时,单击控件边上的下拉箭头,会显示为两个部分:一个下拉列表,一个用于选择日期的 public interface OnDateTimeSetListener { void OnDateTimeSet(AlertDialog dialog, long date); } public DateTimePickerDialog(Context context, long date) { + //对该界面对话框的实例化 super(context); + //对数据库的操作 mDateTimePicker = new DateTimePicker(context); setView(mDateTimePicker); + //添加一个子视图 mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() { public void onDateTimeChanged(DateTimePicker view, int year, int month, - int dayOfMonth, int hourOfDay, int minute) { + int dayOfMonth, int hourOfDay, int minute) { mDate.set(Calendar.YEAR, year); mDate.set(Calendar.MONTH, month); mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth); mDate.set(Calendar.HOUR_OF_DAY, hourOfDay); mDate.set(Calendar.MINUTE, minute); + //将视图中的各选项设置为系统当前时间 updateTitle(mDate.getTimeInMillis()); } }); mDate.setTimeInMillis(date); + //得到系统时间 mDate.set(Calendar.SECOND, 0); + //将秒数设置为0 mDateTimePicker.setCurrentDate(mDate.getTimeInMillis()); setButton(context.getString(R.string.datetime_dialog_ok), this); - setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null); + setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener) null); + //设置按钮 set24HourView(DateFormat.is24HourFormat(this.getContext())); + //时间标准化打印 updateTitle(mDate.getTimeInMillis()); } @@ -70,21 +83,21 @@ public class DateTimePickerDialog extends AlertDialog implements OnClickListener public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) { mOnDateTimeSetListener = callBack; - } + }//将时间日期滚动选择控件实例化 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; flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR; setTitle(DateUtils.formatDateTime(this.getContext(), date, flag)); - } + }//android开发中常见日期管理工具类(API)——DateUtils:按照上下午显示时间 public void onClick(DialogInterface arg0, int arg1) { if (mOnDateTimeSetListener != null) { mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis()); } - } - -} \ No newline at end of file + }//第一个参数arg0是接收到点击事件的对话框 + //第二个参数arg1是该对话框上的按钮 +} diff --git a/app/src/main/java/net/micode/notes/ui/DropdownMenu.java b/app/src/main/java/net/micode/notes/ui/DropdownMenu.java index 613dc74..42f6884 100644 --- a/app/src/main/java/net/micode/notes/ui/DropdownMenu.java +++ b/app/src/main/java/net/micode/notes/ui/DropdownMenu.java @@ -27,17 +27,22 @@ import android.widget.PopupMenu.OnMenuItemClickListener; import net.micode.notes.R; + public class DropdownMenu { private Button mButton; private PopupMenu mPopupMenu; + //声明一个下拉菜单 private Menu mMenu; public DropdownMenu(Context context, Button button, int menuId) { mButton = button; mButton.setBackgroundResource(R.drawable.dropdown_icon); + //设置这个view的背景 mPopupMenu = new PopupMenu(context, mButton); mMenu = mPopupMenu.getMenu(); mPopupMenu.getMenuInflater().inflate(menuId, mMenu); + //MenuInflater是用来实例化Menu目录下的Menu布局文件 + //根据ID来确认menu的内容选项 mButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mPopupMenu.show(); @@ -48,14 +53,14 @@ public class DropdownMenu { public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) { if (mPopupMenu != null) { mPopupMenu.setOnMenuItemClickListener(listener); - } + }//设置菜单的监听 } public MenuItem findItem(int id) { return mMenu.findItem(id); - } + }//对于菜单选项的初始化,根据索引搜索菜单需要的选项 public void setTitle(CharSequence title) { mButton.setText(title); - } -} + }//布局文件,设置标题 +} \ No newline at end of file diff --git a/app/src/main/java/net/micode/notes/ui/FoldersListAdapter.java b/app/src/main/java/net/micode/notes/ui/FoldersListAdapter.java index 96b77da..202a8d8 100644 --- a/app/src/main/java/net/micode/notes/ui/FoldersListAdapter.java +++ b/app/src/main/java/net/micode/notes/ui/FoldersListAdapter.java @@ -29,24 +29,30 @@ import net.micode.notes.data.Notes; import net.micode.notes.data.Notes.NoteColumns; + public class FoldersListAdapter extends CursorAdapter { - public static final String [] PROJECTION = { - NoteColumns.ID, - NoteColumns.SNIPPET - }; + //CursorAdapter是Cursor和ListView的接口 + //FoldersListAdapter继承了CursorAdapter的类 + //主要作用是便签数据库和用户的交互 + //这里就是用folder(文件夹)的形式展现给用户 + public static final String[] PROJECTION = { + NoteColumns.ID, + NoteColumns.SNIPPET + };//调用数据库中便签的ID和片段 - public static final int ID_COLUMN = 0; + public static final int ID_COLUMN = 0; public static final int NAME_COLUMN = 1; public FoldersListAdapter(Context context, Cursor c) { super(context, c); // TODO Auto-generated constructor stub - } + }//数据库操作 @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { + //ViewGroup是容器 return new FolderListItem(context); - } + }//创建一个文件夹,对于各文件夹中子标签的初始化 @Override public void bindView(View view, Context context, Cursor cursor) { @@ -55,20 +61,22 @@ public class FoldersListAdapter extends CursorAdapter { .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); ((FolderListItem) view).bind(folderName); } - } + }//将各个布局文件绑定起来 public String getFolderName(Context context, int position) { Cursor cursor = (Cursor) getItem(position); return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); - } + }//根据数据库中标签的ID得到标签的各项内容 private class FolderListItem extends LinearLayout { private TextView mName; public FolderListItem(Context context) { super(context); + //操作数据库 inflate(context, R.layout.folder_list_item, this); + //根据布局文件的名字等信息将其找出来 mName = (TextView) findViewById(R.id.tv_folder_name); } @@ -76,5 +84,4 @@ public class FoldersListAdapter extends CursorAdapter { mName.setText(name); } } - } diff --git a/app/src/main/java/net/micode/notes/ui/NoteEditText.java b/app/src/main/java/net/micode/notes/ui/NoteEditText.java index 2afe2a8..917608c 100644 --- a/app/src/main/java/net/micode/notes/ui/NoteEditText.java +++ b/app/src/main/java/net/micode/notes/ui/NoteEditText.java @@ -37,16 +37,19 @@ import net.micode.notes.R; import java.util.HashMap; import java.util.Map; +//继承edittext,设置便签设置文本框 public class NoteEditText extends EditText { private static final String TAG = "NoteEditText"; private int mIndex; private int mSelectionStartBeforeDelete; - private static final String SCHEME_TEL = "tel:" ; - 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:"; + ///建立一个字符和整数的hash表,用于链接电话,网站,还有邮箱 private static final Map sSchemaActionResMap = new HashMap(); + static { sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel); sSchemaActionResMap.put(SCHEME_HTTP, R.string.note_link_web); @@ -56,17 +59,20 @@ public class NoteEditText extends EditText { /** * 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 */ + //处理删除按键时的操作 void onEditTextDelete(int index, String text); /** * Add edit text after current edit text when {@link KeyEvent#KEYCODE_ENTER} * happen */ + //处理进入按键时的操作 void onEditTextEnter(int index, String text); /** @@ -77,33 +83,43 @@ public class NoteEditText extends EditText { private OnTextViewChangeListener mOnTextViewChangeListener; + //根据context设置文本 public NoteEditText(Context context) { - super(context, null); + super(context, null);//用super引用父类变量 mIndex = 0; } + //设置当前光标 public void setIndex(int index) { mIndex = index; } + //初始化文本修改标记 public void setOnTextViewChangeListener(OnTextViewChangeListener listener) { mOnTextViewChangeListener = listener; } + //AttributeSet 百度了一下是自定义空控件属性,用于维护便签动态变化的属性 + //初始化便签 public NoteEditText(Context context, AttributeSet attrs) { super(context, attrs, android.R.attr.editTextStyle); } + // 根据defstyle自动初始化 public NoteEditText(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); - // TODO Auto-generated constructor stub + // TODO Auto-generated construct or stub } @Override + //view里的函数,处理手机屏幕的所有事件 + /*参数event为手机屏幕触摸事件封装类的对象,其中封装了该事件的所有信息, + 例如触摸的位置、触摸的类型以及触摸的时间等。该对象会在用户触摸手机屏幕时被创建。*/ public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { + //重写了需要处理屏幕被按下的事件 case MotionEvent.ACTION_DOWN: - + //跟新当前坐标值 int x = (int) event.getX(); int y = (int) event.getY(); x -= getTotalPaddingLeft(); @@ -111,9 +127,12 @@ public class NoteEditText extends EditText { x += getScrollX(); y += getScrollY(); + //用布局控件layout根据x,y的新值设置新的位置 Layout layout = getLayout(); int line = layout.getLineForVertical(y); int off = layout.getOffsetForHorizontal(line, x); + + //更新光标新的位置 Selection.setSelection(getText(), off); break; } @@ -122,96 +141,148 @@ public class NoteEditText extends EditText { } @Override + /* + * 函数功能:处理用户按下一个键盘按键时会触发 的事件 + * 实现过程:如下注释 + */ public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { + //根据按键的 Unicode 编码值来处理 case KeyEvent.KEYCODE_ENTER: + //“进入”按键 if (mOnTextViewChangeListener != null) { return false; } break; case KeyEvent.KEYCODE_DEL: + //“删除”按键 mSelectionStartBeforeDelete = getSelectionStart(); break; default: break; } + //继续执行父类的其他点击事件 return super.onKeyDown(keyCode, event); } @Override + /* + * 函数功能:处理用户松开一个键盘按键时会触发 的事件 + * 实现方式:如下注释 + */ public boolean onKeyUp(int keyCode, KeyEvent event) { - switch(keyCode) { + switch (keyCode) { + //根据按键的 Unicode 编码值来处理,有删除和进入2种操作 case KeyEvent.KEYCODE_DEL: if (mOnTextViewChangeListener != null) { + //若是被修改过 if (0 == mSelectionStartBeforeDelete && mIndex != 0) { + //若之前有被修改并且文档不为空 mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString()); + //利用上文OnTextViewChangeListener对KEYCODE_DEL按键情况的删除函数进行删除 return true; } } else { Log.d(TAG, "OnTextViewChangeListener was not seted"); + //其他情况报错,文档的改动监听器并没有建立 } break; case KeyEvent.KEYCODE_ENTER: + //同上也是分为监听器是否建立2种情况 if (mOnTextViewChangeListener != null) { int selectionStart = getSelectionStart(); + //获取当前位置 String text = getText().subSequence(selectionStart, length()).toString(); + //获取当前文本 setText(getText().subSequence(0, selectionStart)); + //根据获取的文本设置当前文本 mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text); + //当{@link KeyEvent#KEYCODE_ENTER}添加新文本 } else { Log.d(TAG, "OnTextViewChangeListener was not seted"); + //其他情况报错,文档的改动监听器并没有建立 } break; default: break; } + //继续执行父类的其他按键弹起的事件 return super.onKeyUp(keyCode, event); } @Override + /* + * 函数功能:当焦点发生变化时,会自动调用该方法来处理焦点改变的事件 + * 实现方式:如下注释 + * 参数:focused表示触发该事件的View是否获得了焦点,当该控件获得焦点时,Focused等于true,否则等于false。 + direction表示焦点移动的方向,用数值表示 + Rect:表示在触发事件的View的坐标系中,前一个获得焦点的矩形区域,即表示焦点是从哪里来的。如果不可用则为null + */ protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { if (mOnTextViewChangeListener != null) { + //若监听器已经建立 if (!focused && TextUtils.isEmpty(getText())) { + //获取到焦点并且文本不为空 mOnTextViewChangeListener.onTextChange(mIndex, false); + //mOnTextViewChangeListener子函数,置false隐藏事件选项 } else { mOnTextViewChangeListener.onTextChange(mIndex, true); + //mOnTextViewChangeListener子函数,置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); + //设置url的信息的范围值 if (urls.length == 1) { int defaultResId = 0; - for(String schema: sSchemaActionResMap.keySet()) { - if(urls[0].getURL().indexOf(schema) >= 0) { + for (String schema : sSchemaActionResMap.keySet()) { + //获取计划表中所有的key值 + if (urls[0].getURL().indexOf(schema) >= 0) { + //若url可以添加则在添加后将defaultResId置为key所映射的值 defaultResId = sSchemaActionResMap.get(schema); break; } } if (defaultResId == 0) { + //defaultResId == 0则说明url并没有添加任何东西,所以置为连接其他SchemaActionResMap的值 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; } }); } } + //继续执行父类的其他菜单创建的事件 super.onCreateContextMenu(menu); } } + diff --git a/app/src/main/java/net/micode/notes/ui/NoteItemData.java b/app/src/main/java/net/micode/notes/ui/NoteItemData.java index 0f5a878..6a1091e 100644 --- a/app/src/main/java/net/micode/notes/ui/NoteItemData.java +++ b/app/src/main/java/net/micode/notes/ui/NoteItemData.java @@ -41,7 +41,7 @@ public class NoteItemData { NoteColumns.WIDGET_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; @@ -75,8 +75,9 @@ public class NoteItemData { private boolean mIsOnlyOneItem; private boolean mIsOneNoteFollowingFolder; private boolean mIsMultiNotesFollowingFolder; - + //初始化NoteItemData,主要利用光标cursor获取的东西 public NoteItemData(Context context, Cursor cursor) { + //getxxx为转换格式 mId = cursor.getLong(ID_COLUMN); mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN); mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN); @@ -91,7 +92,7 @@ public class NoteItemData { mType = cursor.getInt(TYPE_COLUMN); mWidgetId = cursor.getInt(WIDGET_ID_COLUMN); mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN); - + //初始化电话号码的信息 mPhoneNumber = ""; if (mParentId == Notes.ID_CALL_RECORD_FOLDER) { mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId); @@ -109,25 +110,29 @@ public class NoteItemData { checkPostion(cursor); } + ///根据鼠标的位置设置标记,和位置 private void checkPostion(Cursor cursor) { + //初始化几个标记,cursor具体功能笔记中已提到,不一一叙述 mIsLastItem = cursor.isLast() ? true : false; mIsFirstItem = cursor.isFirst() ? true : false; mIsOnlyOneItem = (cursor.getCount() == 1); + //初始化“多重子文件”“单一子文件”2个标记 mIsMultiNotesFollowingFolder = false; mIsOneNoteFollowingFolder = false; - if (mType == Notes.TYPE_NOTE && !mIsFirstItem) { + //主要是设置上诉2标记 + if (mType == Notes.TYPE_NOTE && !mIsFirstItem) {//若是note格式并且不是第一个元素 int position = cursor.getPosition(); - if (cursor.moveToPrevious()) { + if (cursor.moveToPrevious()) {//获取光标位置后看上一行 if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER - || cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) { + || cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) {//若光标满足系统或note格式 if (cursor.getCount() > (position + 1)) { - mIsMultiNotesFollowingFolder = true; + mIsMultiNotesFollowingFolder = true;//若是数据行数大于但前位置+1则设置成正确 } else { - mIsOneNoteFollowingFolder = true; + mIsOneNoteFollowingFolder = true;//否则单一文件夹标记为true } } - if (!cursor.moveToNext()) { + if (!cursor.moveToNext()) {//若不能再往下走则报错 throw new IllegalStateException("cursor move to previous but can't move back"); } } @@ -213,7 +218,7 @@ public class NoteItemData { public boolean hasAlert() { return (mAlertDate > 0); } - + //若数据父id为保存至文件夹模式的id且满足电话号码单元不为空,则isCallRecord为true public boolean isCallRecord() { return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber)); } diff --git a/app/src/main/java/net/micode/notes/ui/NotesListAdapter.java b/app/src/main/java/net/micode/notes/ui/NotesListAdapter.java index 51c9cb9..8d5e1a0 100644 --- a/app/src/main/java/net/micode/notes/ui/NotesListAdapter.java +++ b/app/src/main/java/net/micode/notes/ui/NotesListAdapter.java @@ -31,55 +31,97 @@ import java.util.HashSet; import java.util.Iterator; + +/* + * 功能:直译为便签表连接器,继承了CursorAdapter,它为cursor和ListView提供了连接的桥梁。 + * 所以NotesListAdapter实现的是鼠标和编辑便签链接的桥梁 + */ public class NotesListAdapter extends CursorAdapter { private static final String TAG = "NotesListAdapter"; private Context mContext; private HashMap mSelectedIndex; - private int mNotesCount; - private boolean mChoiceMode; + private int mNotesCount; //便签数 + private boolean mChoiceMode; //选择模式标记 + /* + * 桌面widget的属性,包括编号和类型 + */ public static class AppWidgetAttribute { public int widgetId; public int widgetType; }; + /* + * 函数功能:初始化便签链接器 + * 函数实现:根据传进来的内容设置相关变量 + */ public NotesListAdapter(Context context) { - super(context, null); - mSelectedIndex = new HashMap(); + super(context, null); //父类对象置空 + mSelectedIndex = new HashMap(); //新建选项下标的hash表 mContext = context; mNotesCount = 0; } + @Override + /* + * 函数功能:新建一个视图来存储光标所指向的数据 + * 函数实现:使用兄弟类NotesListItem新建一个项目选项 + */ public View newView(Context context, Cursor cursor, ViewGroup parent) { return new NotesListItem(context); } + /* + * 函数功能:将已经存在的视图和鼠标指向的数据进行捆绑 + * 函数实现:如下注释 + */ + @Override public void bindView(View view, Context context, Cursor cursor) { if (view instanceof NotesListItem) { + //若view是NotesListItem的一个实例 NoteItemData itemData = new NoteItemData(context, cursor); ((NotesListItem) view).bind(context, itemData, mChoiceMode, isSelectedItem(cursor.getPosition())); + //则新建一个项目选项并且用bind跟将view和鼠标,内容,便签数据捆绑在一起 } } + /* + * 函数功能:设置勾选框 + * 函数实现:如下注释 + */ public void setCheckedItem(final int position, final boolean checked) { mSelectedIndex.put(position, checked); + //根据定位和是否勾选设置下标 notifyDataSetChanged(); + //在修改后刷新activity } + /* + * 函数功能:判断单选按钮是否勾选 + */ public boolean isInChoiceMode() { return mChoiceMode; } + /* + * 函数功能:设置单项选项框 + * 函数实现:重置下标并且根据参数mode设置选项 + */ public void setChoiceMode(boolean mode) { mSelectedIndex.clear(); mChoiceMode = mode; } + /* + * 函数功能:选择全部选项 + * 函数实现:如下注释 + */ public void selectAll(boolean checked) { Cursor cursor = getCursor(); + //获取光标位置 for (int i = 0; i < getCount(); i++) { if (cursor.moveToPosition(i)) { if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) { @@ -87,30 +129,47 @@ public class NotesListAdapter extends CursorAdapter { } } } + //遍历所有光标可用的位置在判断为便签类型之后勾选单项框 } + /* + * 函数功能:建立选择项的下标列表 + * 函数实现:如下注释 + */ public HashSet getSelectedItemIds() { HashSet itemSet = new HashSet(); + //建立hash表 for (Integer position : mSelectedIndex.keySet()) { + //遍历所有的关键 if (mSelectedIndex.get(position) == true) { + //若光标位置可用 Long id = getItemId(position); if (id == Notes.ID_ROOT_FOLDER) { + //原文件不需要添加 Log.d(TAG, "Wrong item id, should not happen"); } else { itemSet.add(id); } + //则将id该下标假如选项集合中 + } } return itemSet; } + /* + * 函数功能:建立桌面Widget的选项表 + * 函数实现:如下注释 + */ public HashSet getSelectedWidget() { HashSet itemSet = new HashSet(); for (Integer position : mSelectedIndex.keySet()) { if (mSelectedIndex.get(position) == true) { Cursor c = (Cursor) getItem(position); + //以上4句和getSelectedItemIds一样,不再重复 if (c != null) { + //光标位置可用的话就建立新的Widget属性并编辑下标和类型,最后添加到选项集中 AppWidgetAttribute widget = new AppWidgetAttribute(); NoteItemData item = new NoteItemData(mContext, c); widget.widgetId = item.getWidgetId(); @@ -128,26 +187,42 @@ public class NotesListAdapter extends CursorAdapter { return itemSet; } + /* + * 函数功能:获取选项个数 + * 函数实现:如下注释 + */ public int getSelectedCount() { Collection values = mSelectedIndex.values(); + //首先获取选项下标的值 if (null == values) { return 0; } Iterator iter = values.iterator(); + //初始化叠加器 int count = 0; while (iter.hasNext()) { if (true == iter.next()) { + //若value值为真计数+1 count++; } } return count; } + /* + * 函数功能:判断是否全部选中 + * 函数实现:如下注释 + */ public boolean isAllSelected() { int checkedCount = getSelectedCount(); return (checkedCount != 0 && checkedCount == mNotesCount); + //获取选项数看是否等于便签的个数 } + /* + * 函数功能:判断是否为选项表 + * 函数实现:通过传递的下标来确定 + */ public boolean isSelectedItem(final int position) { if (null == mSelectedIndex.get(position)) { return false; @@ -156,29 +231,46 @@ public class NotesListAdapter extends CursorAdapter { } @Override + /* + * 函数功能:在activity内容发生局部变动的时候回调该函数计算便签的数量 + * 函数实现:如下注释 + */ protected void onContentChanged() { super.onContentChanged(); + //执行基类函数 calcNotesCount(); } @Override + /* + * 函数功能:在activity光标发生局部变动的时候回调该函数计算便签的数量 + */ public void changeCursor(Cursor cursor) { super.changeCursor(cursor); + //执行基类函数 calcNotesCount(); } + /* + * 函数功能:计算便签数量 + * + */ private void calcNotesCount() { mNotesCount = 0; for (int i = 0; i < getCount(); i++) { + //获取总数同时遍历 Cursor c = (Cursor) getItem(i); if (c != null) { if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) { mNotesCount++; + //若该位置不为空并且文本类型为便签就+1 } } else { Log.e(TAG, "Invalid cursor"); return; } + //否则报错 } } } + diff --git a/app/src/main/java/net/micode/notes/ui/NotesListItem.java b/app/src/main/java/net/micode/notes/ui/NotesListItem.java index 1221e80..547f0c6 100644 --- a/app/src/main/java/net/micode/notes/ui/NotesListItem.java +++ b/app/src/main/java/net/micode/notes/ui/NotesListItem.java @@ -30,17 +30,21 @@ import net.micode.notes.tool.DataUtils; import net.micode.notes.tool.ResourceParser.NoteItemBgResources; + +//创建便签列表项目选项 public class NotesListItem extends LinearLayout { - private ImageView mAlert; - private TextView mTitle; - private TextView mTime; - private TextView mCallName; - private NoteItemData mItemData; - private CheckBox mCheckBox; + private ImageView mAlert;//闹钟图片 + private TextView mTitle; //标题 + private TextView mTime; //时间 + private TextView mCallName; // + private NoteItemData mItemData; //标签数据 + private CheckBox mCheckBox; //打钩框 + /*初始化基本信息*/ public NotesListItem(Context context) { - super(context); - inflate(context, R.layout.note_item, this); + super(context); //super()它的主要作用是调整调用父类构造函数的顺序 + inflate(context, R.layout.note_item, this);//Inflate可用于将一个xml中定义的布局控件找出来,这里的xml是r。layout + //findViewById用于从contentView中查找指定ID的View,转换出来的形式根据需要而定; mAlert = (ImageView) findViewById(R.id.iv_alert_icon); mTitle = (TextView) findViewById(R.id.tv_title); mTime = (TextView) findViewById(R.id.tv_time); @@ -48,19 +52,23 @@ public class NotesListItem extends LinearLayout { mCheckBox = (CheckBox) findViewById(android.R.id.checkbox); } + ///根据data的属性对各个控件的属性的控制,主要是可见性Visibility,内容setText,格式setTextAppearance 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); + mCheckBox.setVisibility(View.VISIBLE); ///设置可见行为可见 + mCheckBox.setChecked(checked); ///格子打钩 } else { mCheckBox.setVisibility(View.GONE); } mItemData = data; + ///设置控件属性,一共三种情况,由data的id和父id是否与保存到文件夹的id一致来决定 if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { mCallName.setVisibility(View.GONE); mAlert.setVisibility(View.VISIBLE); + //设置该textview的style mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); + //settext为设置内容 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); @@ -69,8 +77,9 @@ public class NotesListItem extends LinearLayout { 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); @@ -78,45 +87,50 @@ public class NotesListItem extends LinearLayout { } else { mCallName.setVisibility(View.GONE); mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); - + ///设置title格式 if (data.getType() == Notes.TYPE_FOLDER) { mTitle.setText(data.getSnippet() + context.getString(R.string.format_folder_files_count, - data.getNotesCount())); + 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); } } } - mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate())); + ///设置内容,获取相关时间,从data里编辑的日期中获取 + mTime. setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate())); setBackground(data); } + //根据data的文件属性来设置背景 private void setBackground(NoteItemData data) { int id = data.getBgColorId(); + //,若是note型文件,则4种情况,对于4种不同情况的背景来源 if (data.getType() == Notes.TYPE_NOTE) { + //单个数据并且只有一个子文件夹 if (data.isSingle() || data.isOneFollowingFolder()) { setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id)); - } else if (data.isLast()) { + } else if (data.isLast()) {//是最后一个数据 setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id)); - } else if (data.isFirst() || data.isMultiFollowingFolder()) { + } else if (data.isFirst() || data.isMultiFollowingFolder()) {//是一个数据并有多个子文件夹 setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id)); } else { setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id)); } } else { + //若不是note直接调用文件夹的背景来源 setBackgroundResource(NoteItemBgResources.getFolderBgRes()); } } - public NoteItemData getItemData() { return mItemData; } } + diff --git a/app/src/main/java/net/micode/notes/ui/NotesPreferenceActivity.java b/app/src/main/java/net/micode/notes/ui/NotesPreferenceActivity.java index 07c5f7e..6be753e 100644 --- a/app/src/main/java/net/micode/notes/ui/NotesPreferenceActivity.java +++ b/app/src/main/java/net/micode/notes/ui/NotesPreferenceActivity.java @@ -48,65 +48,95 @@ import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.gtask.remote.GTaskSyncService; +/* + *该类功能:NotesPreferenceActivity,在小米便签中主要实现的是对背景颜色和字体大小的数据储存。 + * 继承了PreferenceActivity主要功能为对系统信息和配置进行自动保存的Activity + */ 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; + //账户的hash标记 + @Override + /* + *函数功能:创建一个activity,在函数里要完成所有的正常静态设置 + *参数:Bundle icicle:存放了 activity 当前的状态 + *函数实现:如下注释 + */ protected void onCreate(Bundle icicle) { + //先执行父类的创建函数 super.onCreate(icicle); /* using the app icon for navigation */ getActionBar().setDisplayHomeAsUpEnabled(true); + //给左上角图标的左边加上一个返回的图标 addPreferencesFromResource(R.xml.preferences); + //添加xml来源并显示 xml 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); + //获取listvivew,ListView的作用:用于列出所有选择 getListView().addHeaderView(header, null, true); + //在listview组件上方添加其他组件 } + + @Override + /* + * 函数功能:activity交互功能的实现,用于接受用户的输入 + * 函数实现:如下注释 + */ protected void onResume() { + //先执行父类 的交互实现 super.onResume(); // need to set sync account automatically if user has added a new // account if (mHasAddedAccount) { + //若用户新加了账户则自动设置同步账户 Account[] accounts = getGoogleAccounts(); + //获取google同步账户 if (mOriAccounts != null && accounts.length > mOriAccounts.length) { + //若原账户不为空且当前账户有增加 for (Account accountNew : accounts) { boolean found = false; for (Account accountOld : mOriAccounts) { if (TextUtils.equals(accountOld.name, accountNew.name)) { + //更新账户 found = true; break; } } if (!found) { setSyncAccount(accountNew.name); + //若是没有找到旧的账户,那么同步账号中就只添加新账户 break; } } @@ -114,58 +144,86 @@ public class NotesPreferenceActivity extends PreferenceActivity { } refreshUI(); + //刷新标签界面 } + @Override + /* + * 函数功能:销毁一个activity + * 函数实现:如下注释 + */ protected void onDestroy() { if (mReceiver != null) { unregisterReceiver(mReceiver); + //注销接收器 } super.onDestroy(); + //执行父类的销毁动作 } + /* + * 函数功能:重新设置账户信息 + * 函数实现:如下注释 + */ private void loadAccountPreference() { mAccountCategory.removeAll(); - + //销毁所有的分组 Preference accountPref = new Preference(this); + //建立首选项 final String defaultAccount = getSyncAccountName(this); accountPref.setTitle(getString(R.string.preferences_account_title)); accountPref.setSummary(getString(R.string.preferences_account_summary)); + //设置首选项的大标题和小标题 accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { + //建立监听器 if (!GTaskSyncService.isSyncing()) { if (TextUtils.isEmpty(defaultAccount)) { // 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中显示不能修改 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; } }); + //根据新建首选项编辑新的账户分组 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() { public void onClick(View v) { GTaskSyncService.cancelSync(NotesPreferenceActivity.this); } }); + //设置按钮显示的文本为“取消同步”以及监听器 } else { syncButton.setText(getString(R.string.preferences_button_sync_immediately)); syncButton.setOnClickListener(new View.OnClickListener() { @@ -173,50 +231,67 @@ public class NotesPreferenceActivity extends PreferenceActivity { GTaskSyncService.startSync(NotesPreferenceActivity.this); } }); + //若是不同步则设置按钮显示的文本为“立即同步”以及对应监听器 } 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)); TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle); subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips)); - + //设置标题以及子标题的内容 dialogBuilder.setCustomTitle(titleView); dialogBuilder.setPositiveButton(null, null); - + //设置对话框的自定义标题,建立一个YES的按钮 Account[] accounts = getGoogleAccounts(); String defAccount = getSyncAccountName(this); - + //获取同步账户信息 mOriAccounts = accounts; mHasAddedAccount = false; if (accounts.length > 0) { + //若账户不为空 CharSequence[] items = new CharSequence[accounts.length]; final CharSequence[] itemMapping = items; int checkedItem = -1; @@ -224,83 +299,119 @@ public class NotesPreferenceActivity extends PreferenceActivity { for (Account account : accounts) { if (TextUtils.equals(account.name, defAccount)) { checkedItem = index; + //在账户列表中查询到所需账户 } items[index++] = account.name; } dialogBuilder.setSingleChoiceItems(items, checkedItem, + //在对话框建立一个单选的复选框 new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { setSyncAccount(itemMapping[which].toString()); dialog.dismiss(); + //取消对话框 refreshUI(); } + //设置点击后执行的事件,包括检录新同步账户和刷新标签界面 }); + //建立对话框网络版的监听器 } View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null); dialogBuilder.setView(addAccountView); + //给新加账户对话框设置自定义样式 final AlertDialog dialog = dialogBuilder.show(); + //显示对话框 addAccountView.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mHasAddedAccount = true; + //将新加账户的hash置true Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS"); + //建立网络建立组件 intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] { - "gmail-ls" + "gmail-ls" }); startActivityForResult(intent, -1); + //跳回上一个选项 dialog.dismiss(); } }); + //建立新加账户对话框的监听器 } + /* + * 函数功能:显示账户选择对话框和相关账户操作 + * 函数实现:如下注释 + */ private void showChangeAccountConfirmAlertDialog() { AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); - + //创建一个新的对话框 View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title); titleTextView.setText(getString(R.string.preferences_dialog_change_account_title, getSyncAccountName(this))); TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle); subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg)); + //根据同步修改的账户信息设置标题以及子标题的内容 dialogBuilder.setCustomTitle(titleView); - + //设置对话框的自定义标题 CharSequence[] menuItemArray = new CharSequence[] { getString(R.string.preferences_menu_change_account), getString(R.string.preferences_menu_remove_account), getString(R.string.preferences_menu_cancel) }; + //定义一些标记字符串 dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() { + //设置对话框要显示的一个list,用于显示几个命令时,即change,remove,cancel public void onClick(DialogInterface dialog, int which) { + //按键功能,由which来决定 if (which == 0) { + //进入账户选择对话框 showSelectAccountAlertDialog(); } else if (which == 1) { + //删除账户并且跟新便签界面 removeSyncAccount(); refreshUI(); } } }); dialogBuilder.show(); + //显示对话框 } + /* + *函数功能:获取谷歌账户 + *函数实现:通过账户管理器直接获取 + */ private Account[] getGoogleAccounts() { AccountManager accountManager = AccountManager.get(this); return accountManager.getAccountsByType("com.google"); } + /* + * 函数功能:设置同步账户 + * 函数实现:如下注释: + */ private void setSyncAccount(String account) { if (!getSyncAccountName(this).equals(account)) { + //假如该账号不在同步账号列表中 SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); + //编辑共享的首选项 if (account != null) { editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account); } else { editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); } + //将该账号加入到首选项中 + editor.commit(); + //提交修改的数据 + - // clean up last sync time setLastSyncTime(this, 0); + //将最后同步时间清零 // clean up local gtask related info new Thread(new Runnable() { @@ -311,23 +422,34 @@ public class NotesPreferenceActivity extends PreferenceActivity { getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null); } }).start(); + //重置当地同步任务的信息 Toast.makeText(NotesPreferenceActivity.this, getString(R.string.preferences_toast_success_set_accout, account), Toast.LENGTH_SHORT).show(); + //将toast的文本信息置为“设置账户成功”并显示出来 } } + /* + * 函数功能:删除同步账户 + * 函数实现:如下注释: + */ private void removeSyncAccount() { SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); + //设置共享首选项 + if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) { editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME); + //假如当前首选项中有账户就删除 } if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) { editor.remove(PREFERENCE_LAST_SYNC_TIME); + //删除当前首选项中有账户时间 } editor.commit(); + //提交更新后的数据 // clean up local gtask related info new Thread(new Runnable() { @@ -338,51 +460,80 @@ public class NotesPreferenceActivity extends PreferenceActivity { getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null); } }).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); SharedPreferences.Editor editor = settings.edit(); + // 从共享首选项中找到相关账户并获取其编辑器 editor.putLong(PREFERENCE_LAST_SYNC_TIME, time); 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); } + /* + * 函数功能:接受同步信息 + * 函数实现:继承BroadcastReceiver + */ private class GTaskReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { refreshUI(); if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) { + //获取随广播而来的Intent中的同步服务的数据 TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview); syncStatus.setText(intent .getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG)); + //通过获取的数据在设置系统的状态 } } } + /* + * 函数功能:处理菜单的选项 + * 函数实现:如下注释 + * 参数:MenuItem菜单选项 + */ public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { + //根据选项的id选择,这里只有一个主页 case android.R.id.home: Intent intent = new Intent(this, NotesListActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); return true; + //在主页情况下在创建连接组件intent,发出清空的信号并开始一个相应的activity default: return false; } } } +