Compare commits

..

No commits in common. 'lyl_branch' and 'main' have entirely different histories.

@ -1 +0,0 @@
Subproject commit 85ad4e7b6c62b539ad3bffcdf964e05becfa0bba

Binary file not shown.

Before

Width:  |  Height:  |  Size: 191 KiB

@ -0,0 +1,279 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.data;
import android.net.Uri;
public class Notes {
public static final String AUTHORITY = "micode_notes";
public static final String TAG = "Notes";
public static final int TYPE_NOTE = 0;
public static final int TYPE_FOLDER = 1;
public static final int TYPE_SYSTEM = 2;
/**
* Following IDs are system folders' identifiers
* {@link Notes#ID_ROOT_FOLDER } is default folder
* {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder
* {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records
*/
public static final int ID_ROOT_FOLDER = 0;
public static final int ID_TEMPARAY_FOLDER = -1;
public static final int ID_CALL_RECORD_FOLDER = -2;
public static final int ID_TRASH_FOLER = -3;
public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date";
public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id";
public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id";
public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type";
public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id";
public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date";
public static final int TYPE_WIDGET_INVALIDE = -1;
public static final int TYPE_WIDGET_2X = 0;
public static final int TYPE_WIDGET_4X = 1;
public static class DataConstants {
public static final String NOTE = TextNote.CONTENT_ITEM_TYPE;
public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE;
}
/**
* Uri to query all notes and folders
*/
public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note");
/**
* Uri to query data
*/
public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data");
public interface NoteColumns {
/**
* The unique ID for a row
* <P> Type: INTEGER (long) </P>
*/
public static final String ID = "_id";
/**
* The parent's id for note or folder
* <P> Type: INTEGER (long) </P>
*/
public static final String PARENT_ID = "parent_id";
/**
* Created data for note or folder
* <P> Type: INTEGER (long) </P>
*/
public static final String CREATED_DATE = "created_date";
/**
* Latest modified date
* <P> Type: INTEGER (long) </P>
*/
public static final String MODIFIED_DATE = "modified_date";
/**
* Alert date
* <P> Type: INTEGER (long) </P>
*/
public static final String ALERTED_DATE = "alert_date";
/**
* Folder's name or text content of note
* <P> Type: TEXT </P>
*/
public static final String SNIPPET = "snippet";
/**
* Note's widget id
* <P> Type: INTEGER (long) </P>
*/
public static final String WIDGET_ID = "widget_id";
/**
* Note's widget type
* <P> Type: INTEGER (long) </P>
*/
public static final String WIDGET_TYPE = "widget_type";
/**
* Note's background color's id
* <P> Type: INTEGER (long) </P>
*/
public static final String BG_COLOR_ID = "bg_color_id";
/**
* For text note, it doesn't has attachment, for multi-media
* note, it has at least one attachment
* <P> Type: INTEGER </P>
*/
public static final String HAS_ATTACHMENT = "has_attachment";
/**
* Folder's count of notes
* <P> Type: INTEGER (long) </P>
*/
public static final String NOTES_COUNT = "notes_count";
/**
* The file type: folder or note
* <P> Type: INTEGER </P>
*/
public static final String TYPE = "type";
/**
* The last sync id
* <P> Type: INTEGER (long) </P>
*/
public static final String SYNC_ID = "sync_id";
/**
* Sign to indicate local modified or not
* <P> Type: INTEGER </P>
*/
public static final String LOCAL_MODIFIED = "local_modified";
/**
* Original parent id before moving into temporary folder
* <P> Type : INTEGER </P>
*/
public static final String ORIGIN_PARENT_ID = "origin_parent_id";
/**
* The gtask id
* <P> Type : TEXT </P>
*/
public static final String GTASK_ID = "gtask_id";
/**
* The version code
* <P> Type : INTEGER (long) </P>
*/
public static final String VERSION = "version";
}
public interface DataColumns {
/**
* The unique ID for a row
* <P> Type: INTEGER (long) </P>
*/
public static final String ID = "_id";
/**
* The MIME type of the item represented by this row.
* <P> Type: Text </P>
*/
public static final String MIME_TYPE = "mime_type";
/**
* The reference id to note that this data belongs to
* <P> Type: INTEGER (long) </P>
*/
public static final String NOTE_ID = "note_id";
/**
* Created data for note or folder
* <P> Type: INTEGER (long) </P>
*/
public static final String CREATED_DATE = "created_date";
/**
* Latest modified date
* <P> Type: INTEGER (long) </P>
*/
public static final String MODIFIED_DATE = "modified_date";
/**
* Data's content
* <P> Type: TEXT </P>
*/
public static final String CONTENT = "content";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* integer data type
* <P> Type: INTEGER </P>
*/
public static final String DATA1 = "data1";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* integer data type
* <P> Type: INTEGER </P>
*/
public static final String DATA2 = "data2";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type
* <P> Type: TEXT </P>
*/
public static final String DATA3 = "data3";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type
* <P> Type: TEXT </P>
*/
public static final String DATA4 = "data4";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type
* <P> Type: TEXT </P>
*/
public static final String DATA5 = "data5";
}
public static final class TextNote implements DataColumns {
/**
* Mode to indicate the text in check list mode or not
* <P> Type: Integer 1:check list mode 0: normal mode </P>
*/
public static final String MODE = DATA1;
public static final int MODE_CHECK_LIST = 1;
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note");
}
public static final class CallNote implements DataColumns {
/**
* Call date for this record
* <P> Type: INTEGER (long) </P>
*/
public static final String CALL_DATE = DATA1;
/**
* Phone number for this record
* <P> Type: TEXT </P>
*/
public static final String PHONE_NUMBER = DATA3;
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note");
}
}

@ -0,0 +1,305 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.data;
import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import net.micode.notes.R;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.NotesDatabaseHelper.TABLE;
public class NotesProvider extends ContentProvider {
private static final UriMatcher mMatcher;
private NotesDatabaseHelper mHelper;
private static final String TAG = "NotesProvider";
private static final int URI_NOTE = 1;
private static final int URI_NOTE_ITEM = 2;
private static final int URI_DATA = 3;
private static final int URI_DATA_ITEM = 4;
private static final int URI_SEARCH = 5;
private static final int URI_SEARCH_SUGGEST = 6;
static {
mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE);
mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM);
mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA);
mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM);
mMatcher.addURI(Notes.AUTHORITY, "search", URI_SEARCH);
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, URI_SEARCH_SUGGEST);
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST);
}
/**
* x'0A' represents the '\n' character in sqlite. For title and content in the search result,
* we will trim '\n' and white space in order to show more information.
*/
private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + ","
+ NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + ","
+ "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_1 + ","
+ "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_2 + ","
+ R.drawable.search_result + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1 + ","
+ "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + ","
+ "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA;
private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION
+ " FROM " + TABLE.NOTE
+ " WHERE " + NoteColumns.SNIPPET + " LIKE ?"
+ " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER
+ " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE;
@Override
public boolean onCreate() {
mHelper = NotesDatabaseHelper.getInstance(getContext());
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
Cursor c = null;
SQLiteDatabase db = mHelper.getReadableDatabase();
String id = null;
switch (mMatcher.match(uri)) {
case URI_NOTE:
c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null,
sortOrder);
break;
case URI_NOTE_ITEM:
id = uri.getPathSegments().get(1);
c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder);
break;
case URI_DATA:
c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null,
sortOrder);
break;
case URI_DATA_ITEM:
id = uri.getPathSegments().get(1);
c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder);
break;
case URI_SEARCH:
case URI_SEARCH_SUGGEST:
if (sortOrder != null || projection != null) {
throw new IllegalArgumentException(
"do not specify sortOrder, selection, selectionArgs, or projection" + "with this query");
}
String searchString = null;
if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) {
if (uri.getPathSegments().size() > 1) {
searchString = uri.getPathSegments().get(1);
}
} else {
searchString = uri.getQueryParameter("pattern");
}
if (TextUtils.isEmpty(searchString)) {
return null;
}
try {
searchString = String.format("%%%s%%", searchString);
c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY,
new String[] { searchString });
} catch (IllegalStateException ex) {
Log.e(TAG, "got exception: " + ex.toString());
}
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (c != null) {
c.setNotificationUri(getContext().getContentResolver(), uri);
}
return c;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = mHelper.getWritableDatabase();
long dataId = 0, noteId = 0, insertedId = 0;
switch (mMatcher.match(uri)) {
case URI_NOTE:
insertedId = noteId = db.insert(TABLE.NOTE, null, values);
break;
case URI_DATA:
if (values.containsKey(DataColumns.NOTE_ID)) {
noteId = values.getAsLong(DataColumns.NOTE_ID);
} else {
Log.d(TAG, "Wrong data format without note id:" + values.toString());
}
insertedId = dataId = db.insert(TABLE.DATA, null, values);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
// Notify the note uri
if (noteId > 0) {
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null);
}
// Notify the data uri
if (dataId > 0) {
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null);
}
return ContentUris.withAppendedId(uri, insertedId);
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int count = 0;
String id = null;
SQLiteDatabase db = mHelper.getWritableDatabase();
boolean deleteData = false;
switch (mMatcher.match(uri)) {
case URI_NOTE:
selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 ";
count = db.delete(TABLE.NOTE, selection, selectionArgs);
break;
case URI_NOTE_ITEM:
id = uri.getPathSegments().get(1);
/**
* ID that smaller than 0 is system folder which is not allowed to
* trash
*/
long noteId = Long.valueOf(id);
if (noteId <= 0) {
break;
}
count = db.delete(TABLE.NOTE,
NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
break;
case URI_DATA:
count = db.delete(TABLE.DATA, selection, selectionArgs);
deleteData = true;
break;
case URI_DATA_ITEM:
id = uri.getPathSegments().get(1);
count = db.delete(TABLE.DATA,
DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
deleteData = true;
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (count > 0) {
if (deleteData) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
}
getContext().getContentResolver().notifyChange(uri, null);
}
return count;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int count = 0;
String id = null;
SQLiteDatabase db = mHelper.getWritableDatabase();
boolean updateData = false;
switch (mMatcher.match(uri)) {
case URI_NOTE:
increaseNoteVersion(-1, selection, selectionArgs);
count = db.update(TABLE.NOTE, values, selection, selectionArgs);
break;
case URI_NOTE_ITEM:
id = uri.getPathSegments().get(1);
increaseNoteVersion(Long.valueOf(id), selection, selectionArgs);
count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs);
break;
case URI_DATA:
count = db.update(TABLE.DATA, values, selection, selectionArgs);
updateData = true;
break;
case URI_DATA_ITEM:
id = uri.getPathSegments().get(1);
count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs);
updateData = true;
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (count > 0) {
if (updateData) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
}
getContext().getContentResolver().notifyChange(uri, null);
}
return count;
}
private String parseSelection(String selection) {
return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
}
private void increaseNoteVersion(long id, String selection, String[] selectionArgs) {
StringBuilder sql = new StringBuilder(120);
sql.append("UPDATE ");
sql.append(TABLE.NOTE);
sql.append(" SET ");
sql.append(NoteColumns.VERSION);
sql.append("=" + NoteColumns.VERSION + "+1 ");
if (id > 0 || !TextUtils.isEmpty(selection)) {
sql.append(" WHERE ");
}
if (id > 0) {
sql.append(NoteColumns.ID + "=" + String.valueOf(id));
}
if (!TextUtils.isEmpty(selection)) {
String selectString = id > 0 ? parseSelection(selection) : selection;
for (String args : selectionArgs) {
selectString = selectString.replaceFirst("\\?", args);
}
sql.append(selectString);
}
mHelper.getWritableDatabase().execSQL(sql.toString());
}
@Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
return null;
}
}

@ -28,52 +28,37 @@ import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
// 定义一个名为AlarmInitReceiver的类继承自BroadcastReceiver
public class AlarmInitReceiver extends BroadcastReceiver { public class AlarmInitReceiver extends BroadcastReceiver {
// 定义一个字符串数组包含NoteColumns中的ID和ALERTED_DATE
private static final String [] PROJECTION = new String [] { private static final String [] PROJECTION = new String [] {
NoteColumns.ID, NoteColumns.ID,
NoteColumns.ALERTED_DATE NoteColumns.ALERTED_DATE
}; };
// 定义两个常量分别表示ID和ALERTED_DATE的列索引
private static final int COLUMN_ID = 0; private static final int COLUMN_ID = 0;
private static final int COLUMN_ALERTED_DATE = 1; private static final int COLUMN_ALERTED_DATE = 1;
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
// 获取当前时间
long currentDate = System.currentTimeMillis(); long currentDate = System.currentTimeMillis();
// 查询数据库,获取所有未提醒的笔记
Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI, Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
PROJECTION, PROJECTION,
NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE, NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE,
new String[] { String.valueOf(currentDate) }, new String[] { String.valueOf(currentDate) },
null); null);
// 如果c不为空
if (c != null) { if (c != null) {
// 如果c可以移动到第一行
if (c.moveToFirst()) { if (c.moveToFirst()) {
// 循环遍历c
do { do {
// 获取提醒日期
long alertDate = c.getLong(COLUMN_ALERTED_DATE); long alertDate = c.getLong(COLUMN_ALERTED_DATE);
// 创建一个Intent指向AlarmReceiver类
Intent sender = new Intent(context, AlarmReceiver.class); Intent sender = new Intent(context, AlarmReceiver.class);
// 设置Intent的数据指向Notes.CONTENT_NOTE_URI并添加c.getLong(COLUMN_ID)作为参数
sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID))); sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID)));
// 创建一个PendingIntent用于发送广播
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0);
// 获取AlarmManager服务
AlarmManager alermManager = (AlarmManager) context AlarmManager alermManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE); .getSystemService(Context.ALARM_SERVICE);
// 设置闹钟在alertDate时间点唤醒设备并发送广播
alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent); alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);
} while (c.moveToNext()); } while (c.moveToNext());
} }
// 关闭c
c.close(); c.close();
} }
} }

@ -67,11 +67,8 @@ public class DateTimePicker extends FrameLayout {
private NumberPicker.OnValueChangeListener mOnDateChangedListener = new NumberPicker.OnValueChangeListener() { private NumberPicker.OnValueChangeListener mOnDateChangedListener = new NumberPicker.OnValueChangeListener() {
@Override @Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) { public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// 将日期增加或减少指定的天数
mDate.add(Calendar.DAY_OF_YEAR, newVal - oldVal); mDate.add(Calendar.DAY_OF_YEAR, newVal - oldVal);
// 更新日期控件
updateDateControl(); updateDateControl();
// 日期时间改变时调用
onDateTimeChanged(); onDateTimeChanged();
} }
}; };
@ -79,52 +76,37 @@ public class DateTimePicker extends FrameLayout {
private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() { private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() {
@Override @Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) { public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// 判断是否日期改变
boolean isDateChanged = false; boolean isDateChanged = false;
// 获取当前时间
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
// 判断是否为24小时制
if (!mIs24HourView) { if (!mIs24HourView) {
// 判断是否为上午
if (!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) { if (!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) {
// 如果当前时间是上午11点并且选择的时间是下午12点则日期加1天
cal.setTimeInMillis(mDate.getTimeInMillis()); cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1); cal.add(Calendar.DAY_OF_YEAR, 1);
isDateChanged = true; isDateChanged = true;
} else if (mIsAm && oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) { } else if (mIsAm && oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
// 如果当前时间是下午12点并且选择的时间是上午11点则日期减1天
cal.setTimeInMillis(mDate.getTimeInMillis()); cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -1); cal.add(Calendar.DAY_OF_YEAR, -1);
isDateChanged = true; isDateChanged = true;
} }
// 判断是否跨过12点
if (oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY || if (oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY ||
oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) { oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
// 跨过12点则上午和下午互换
mIsAm = !mIsAm; mIsAm = !mIsAm;
updateAmPmControl(); updateAmPmControl();
} }
} else { } else {
// 判断是否跨过24点
if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) { if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) {
// 如果当前时间是23点并且选择的时间是0点则日期加1天
cal.setTimeInMillis(mDate.getTimeInMillis()); cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1); cal.add(Calendar.DAY_OF_YEAR, 1);
isDateChanged = true; isDateChanged = true;
} else if (oldVal == 0 && newVal == HOURS_IN_ALL_DAY - 1) { } else if (oldVal == 0 && newVal == HOURS_IN_ALL_DAY - 1) {
// 如果当前时间是0点并且选择的时间是23点则日期减1天
cal.setTimeInMillis(mDate.getTimeInMillis()); cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -1); cal.add(Calendar.DAY_OF_YEAR, -1);
isDateChanged = true; isDateChanged = true;
} }
} }
// 计算新的小时数
int newHour = mHourSpinner.getValue() % HOURS_IN_HALF_DAY + (mIsAm ? 0 : HOURS_IN_HALF_DAY); int newHour = mHourSpinner.getValue() % HOURS_IN_HALF_DAY + (mIsAm ? 0 : HOURS_IN_HALF_DAY);
// 设置新的小时数
mDate.set(Calendar.HOUR_OF_DAY, newHour); mDate.set(Calendar.HOUR_OF_DAY, newHour);
// 通知时间改变
onDateTimeChanged(); onDateTimeChanged();
// 如果日期改变,则更新日期
if (isDateChanged) { if (isDateChanged) {
setCurrentYear(cal.get(Calendar.YEAR)); setCurrentYear(cal.get(Calendar.YEAR));
setCurrentMonth(cal.get(Calendar.MONTH)); setCurrentMonth(cal.get(Calendar.MONTH));
@ -136,120 +118,84 @@ public class DateTimePicker extends FrameLayout {
private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() { private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() {
@Override @Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) { public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// 获取分钟选择器的最小值和最大值
int minValue = mMinuteSpinner.getMinValue(); int minValue = mMinuteSpinner.getMinValue();
int maxValue = mMinuteSpinner.getMaxValue(); int maxValue = mMinuteSpinner.getMaxValue();
int offset = 0; int offset = 0;
// 如果旧值等于最大值且新值等于最小值则偏移量为1
if (oldVal == maxValue && newVal == minValue) { if (oldVal == maxValue && newVal == minValue) {
offset += 1; offset += 1;
// 如果旧值等于最小值且新值等于最大值,则偏移量为-1
} else if (oldVal == minValue && newVal == maxValue) { } else if (oldVal == minValue && newVal == maxValue) {
offset -= 1; offset -= 1;
} }
// 如果偏移量不为0则更新日期和时间
if (offset != 0) { if (offset != 0) {
mDate.add(Calendar.HOUR_OF_DAY, offset); mDate.add(Calendar.HOUR_OF_DAY, offset);
mHourSpinner.setValue(getCurrentHour()); mHourSpinner.setValue(getCurrentHour());
updateDateControl(); updateDateControl();
int newHour = getCurrentHourOfDay(); int newHour = getCurrentHourOfDay();
// 如果新小时数大于等于半天的小时数,则更新上午/下午控制
if (newHour >= HOURS_IN_HALF_DAY) { if (newHour >= HOURS_IN_HALF_DAY) {
mIsAm = false; mIsAm = false;
updateAmPmControl(); updateAmPmControl();
// 否则,更新上午/下午控制
} else { } else {
mIsAm = true; mIsAm = true;
updateAmPmControl(); updateAmPmControl();
} }
} }
// 设置新分钟值
mDate.set(Calendar.MINUTE, newVal); mDate.set(Calendar.MINUTE, newVal);
// 日期时间改变
onDateTimeChanged(); onDateTimeChanged();
} }
}; };
// 定义一个NumberPicker的值改变监听器
private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() { private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() {
@Override @Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) { public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// 切换AM/PM
mIsAm = !mIsAm; mIsAm = !mIsAm;
// 如果是AM则将时间减去12小时
if (mIsAm) { if (mIsAm) {
mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY); mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY);
// 如果是PM则将时间加上12小时
} else { } else {
mDate.add(Calendar.HOUR_OF_DAY, HOURS_IN_HALF_DAY); mDate.add(Calendar.HOUR_OF_DAY, HOURS_IN_HALF_DAY);
} }
// 更新AM/PM控制
updateAmPmControl(); updateAmPmControl();
// 日期时间改变
onDateTimeChanged(); onDateTimeChanged();
} }
}; };
public interface OnDateTimeChangedListener { public interface OnDateTimeChangedListener {
// 当日期时间改变时调用的方法
void onDateTimeChanged(DateTimePicker view, int year, int month, void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute); int dayOfMonth, int hourOfDay, int minute);
} }
// 构造方法,使用当前时间作为日期时间
public DateTimePicker(Context context) { public DateTimePicker(Context context) {
this(context, System.currentTimeMillis()); this(context, System.currentTimeMillis());
} }
// 构造方法,使用指定时间作为日期时间
public DateTimePicker(Context context, long date) { public DateTimePicker(Context context, long date) {
this(context, date, DateFormat.is24HourFormat(context)); this(context, date, DateFormat.is24HourFormat(context));
} }
public DateTimePicker(Context context, long date, boolean is24HourView) { public DateTimePicker(Context context, long date, boolean is24HourView) {
super(context); super(context);
// 获取当前日期
mDate = Calendar.getInstance(); mDate = Calendar.getInstance();
mInitialising = true; mInitialising = true;
// 判断当前小时是否大于等于12
mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY; mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY;
// 加载布局文件
inflate(context, R.layout.datetime_picker, this); inflate(context, R.layout.datetime_picker, this);
// 获取日期选择器
mDateSpinner = (NumberPicker) findViewById(R.id.date); mDateSpinner = (NumberPicker) findViewById(R.id.date);
// 设置日期选择器的最小值
mDateSpinner.setMinValue(DATE_SPINNER_MIN_VAL); mDateSpinner.setMinValue(DATE_SPINNER_MIN_VAL);
// 设置日期选择器的最大值
mDateSpinner.setMaxValue(DATE_SPINNER_MAX_VAL); mDateSpinner.setMaxValue(DATE_SPINNER_MAX_VAL);
// 设置日期选择器的值改变监听器
mDateSpinner.setOnValueChangedListener(mOnDateChangedListener); mDateSpinner.setOnValueChangedListener(mOnDateChangedListener);
// 获取小时选择器
mHourSpinner = (NumberPicker) findViewById(R.id.hour); mHourSpinner = (NumberPicker) findViewById(R.id.hour);
// 设置小时选择器的值改变监听器
mHourSpinner.setOnValueChangedListener(mOnHourChangedListener); mHourSpinner.setOnValueChangedListener(mOnHourChangedListener);
// 获取分钟选择器
mMinuteSpinner = (NumberPicker) findViewById(R.id.minute); mMinuteSpinner = (NumberPicker) findViewById(R.id.minute);
// 设置分钟选择器的最小值
mMinuteSpinner.setMinValue(MINUT_SPINNER_MIN_VAL); mMinuteSpinner.setMinValue(MINUT_SPINNER_MIN_VAL);
// 设置分钟选择器的最大值
mMinuteSpinner.setMaxValue(MINUT_SPINNER_MAX_VAL); mMinuteSpinner.setMaxValue(MINUT_SPINNER_MAX_VAL);
// 设置分钟选择器的长按更新间隔
mMinuteSpinner.setOnLongPressUpdateInterval(100); mMinuteSpinner.setOnLongPressUpdateInterval(100);
// 设置分钟选择器的值改变监听器
mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener); mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener);
// 获取上午下午选择器
String[] stringsForAmPm = new DateFormatSymbols().getAmPmStrings(); String[] stringsForAmPm = new DateFormatSymbols().getAmPmStrings();
mAmPmSpinner = (NumberPicker) findViewById(R.id.amPm); mAmPmSpinner = (NumberPicker) findViewById(R.id.amPm);
// 设置上午下午选择器的最小值
mAmPmSpinner.setMinValue(AMPM_SPINNER_MIN_VAL); mAmPmSpinner.setMinValue(AMPM_SPINNER_MIN_VAL);
// 设置上午下午选择器的最大值
mAmPmSpinner.setMaxValue(AMPM_SPINNER_MAX_VAL); mAmPmSpinner.setMaxValue(AMPM_SPINNER_MAX_VAL);
// 设置上午下午选择器的显示值
mAmPmSpinner.setDisplayedValues(stringsForAmPm); mAmPmSpinner.setDisplayedValues(stringsForAmPm);
// 设置上午下午选择器的值改变监听器
mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener); mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener);
// update controls to initial state // update controls to initial state
@ -269,29 +215,20 @@ public class DateTimePicker extends FrameLayout {
} }
@Override @Override
// 重写setEnabled方法
public void setEnabled(boolean enabled) { public void setEnabled(boolean enabled) {
// 如果当前状态和传入的状态相同,则直接返回
if (mIsEnabled == enabled) { if (mIsEnabled == enabled) {
return; return;
} }
// 调用父类的setEnabled方法
super.setEnabled(enabled); super.setEnabled(enabled);
// 设置日期选择器是否可用
mDateSpinner.setEnabled(enabled); mDateSpinner.setEnabled(enabled);
// 设置分钟选择器是否可用
mMinuteSpinner.setEnabled(enabled); mMinuteSpinner.setEnabled(enabled);
// 设置小时选择器是否可用
mHourSpinner.setEnabled(enabled); mHourSpinner.setEnabled(enabled);
// 设置上午/下午选择器是否可用
mAmPmSpinner.setEnabled(enabled); mAmPmSpinner.setEnabled(enabled);
// 更新当前状态
mIsEnabled = enabled; mIsEnabled = enabled;
} }
@Override @Override
public boolean isEnabled() { public boolean isEnabled() {
// 返回mIsEnabled的值
return mIsEnabled; return mIsEnabled;
} }
@ -310,11 +247,8 @@ public class DateTimePicker extends FrameLayout {
* @param date The current date in millis * @param date The current date in millis
*/ */
public void setCurrentDate(long date) { public void setCurrentDate(long date) {
// 获取当前日期
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
// 将传入的日期转换为毫秒
cal.setTimeInMillis(date); cal.setTimeInMillis(date);
// 设置当前日期
setCurrentDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 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)); cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE));
} }
@ -330,15 +264,10 @@ public class DateTimePicker extends FrameLayout {
*/ */
public void setCurrentDate(int year, int month, public void setCurrentDate(int year, int month,
int dayOfMonth, int hourOfDay, int minute) { int dayOfMonth, int hourOfDay, int minute) {
// 设置当前年份
setCurrentYear(year); setCurrentYear(year);
// 设置当前月份
setCurrentMonth(month); setCurrentMonth(month);
// 设置当前日期
setCurrentDay(dayOfMonth); setCurrentDay(dayOfMonth);
// 设置当前小时
setCurrentHour(hourOfDay); setCurrentHour(hourOfDay);
// 设置当前分钟
setCurrentMinute(minute); setCurrentMinute(minute);
} }
@ -348,7 +277,6 @@ public class DateTimePicker extends FrameLayout {
* @return The current year * @return The current year
*/ */
public int getCurrentYear() { public int getCurrentYear() {
// 获取当前年份
return mDate.get(Calendar.YEAR); return mDate.get(Calendar.YEAR);
} }
@ -358,15 +286,11 @@ public class DateTimePicker extends FrameLayout {
* @param year The current year * @param year The current year
*/ */
public void setCurrentYear(int year) { public void setCurrentYear(int year) {
// 如果当前年份与传入的年份相同,则不进行任何操作
if (!mInitialising && year == getCurrentYear()) { if (!mInitialising && year == getCurrentYear()) {
return; return;
} }
// 设置当前年份
mDate.set(Calendar.YEAR, year); mDate.set(Calendar.YEAR, year);
// 更新日期控件
updateDateControl(); updateDateControl();
// 日期时间改变
onDateTimeChanged(); onDateTimeChanged();
} }
@ -376,7 +300,6 @@ public class DateTimePicker extends FrameLayout {
* @return The current month in the year * @return The current month in the year
*/ */
public int getCurrentMonth() { public int getCurrentMonth() {
// 获取当前月份
return mDate.get(Calendar.MONTH); return mDate.get(Calendar.MONTH);
} }
@ -386,15 +309,11 @@ public class DateTimePicker extends FrameLayout {
* @param month The month in the year * @param month The month in the year
*/ */
public void setCurrentMonth(int month) { public void setCurrentMonth(int month) {
// 如果当前月份和要设置的月份相同,则不进行设置
if (!mInitialising && month == getCurrentMonth()) { if (!mInitialising && month == getCurrentMonth()) {
return; return;
} }
// 设置当前月份
mDate.set(Calendar.MONTH, month); mDate.set(Calendar.MONTH, month);
// 更新日期控件
updateDateControl(); updateDateControl();
// 日期改变回调
onDateTimeChanged(); onDateTimeChanged();
} }
@ -403,9 +322,7 @@ public class DateTimePicker extends FrameLayout {
* *
* @return The day of the month * @return The day of the month
*/ */
// 获取当前日期
public int getCurrentDay() { public int getCurrentDay() {
// 获取当前日期的日
return mDate.get(Calendar.DAY_OF_MONTH); return mDate.get(Calendar.DAY_OF_MONTH);
} }
@ -415,15 +332,11 @@ public class DateTimePicker extends FrameLayout {
* @param dayOfMonth The day of the month * @param dayOfMonth The day of the month
*/ */
public void setCurrentDay(int dayOfMonth) { public void setCurrentDay(int dayOfMonth) {
// 如果当前不在初始化状态,并且传入的日期与当前日期相同,则直接返回
if (!mInitialising && dayOfMonth == getCurrentDay()) { if (!mInitialising && dayOfMonth == getCurrentDay()) {
return; return;
} }
// 设置当前日期
mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth); mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
// 更新日期控件
updateDateControl(); updateDateControl();
// 日期改变时触发
onDateTimeChanged(); onDateTimeChanged();
} }
@ -431,26 +344,18 @@ public class DateTimePicker extends FrameLayout {
* Get current hour in 24 hour mode, in the range (0~23) * Get current hour in 24 hour mode, in the range (0~23)
* @return The current hour in 24 hour mode * @return The current hour in 24 hour mode
*/ */
// 获取当前小时
public int getCurrentHourOfDay() { public int getCurrentHourOfDay() {
return mDate.get(Calendar.HOUR_OF_DAY); return mDate.get(Calendar.HOUR_OF_DAY);
} }
// 获取当前小时
private int getCurrentHour() { private int getCurrentHour() {
// 如果是24小时制
if (mIs24HourView){ if (mIs24HourView){
// 获取当前小时
return getCurrentHourOfDay(); return getCurrentHourOfDay();
} else { } else {
// 获取当前小时
int hour = getCurrentHourOfDay(); int hour = getCurrentHourOfDay();
// 如果当前小时大于12
if (hour > HOURS_IN_HALF_DAY) { if (hour > HOURS_IN_HALF_DAY) {
// 返回当前小时减去12
return hour - HOURS_IN_HALF_DAY; return hour - HOURS_IN_HALF_DAY;
} else { } else {
// 如果当前小时等于0返回12
return hour == 0 ? HOURS_IN_HALF_DAY : hour; return hour == 0 ? HOURS_IN_HALF_DAY : hour;
} }
} }
@ -461,40 +366,26 @@ public class DateTimePicker extends FrameLayout {
* *
* @param hourOfDay * @param hourOfDay
*/ */
// 设置当前小时
public void setCurrentHour(int hourOfDay) { public void setCurrentHour(int hourOfDay) {
// 如果当前正在初始化,或者当前小时和要设置的小时相同,则直接返回
if (!mInitialising && hourOfDay == getCurrentHourOfDay()) { if (!mInitialising && hourOfDay == getCurrentHourOfDay()) {
return; return;
} }
// 设置当前小时
mDate.set(Calendar.HOUR_OF_DAY, hourOfDay); mDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
// 如果不是24小时制
if (!mIs24HourView) { if (!mIs24HourView) {
// 如果当前小时大于等于12
if (hourOfDay >= HOURS_IN_HALF_DAY) { if (hourOfDay >= HOURS_IN_HALF_DAY) {
// 设置为下午
mIsAm = false; mIsAm = false;
// 如果当前小时大于12
if (hourOfDay > HOURS_IN_HALF_DAY) { if (hourOfDay > HOURS_IN_HALF_DAY) {
// 当前小时减去12
hourOfDay -= HOURS_IN_HALF_DAY; hourOfDay -= HOURS_IN_HALF_DAY;
} }
} else { } else {
// 设置为上午
mIsAm = true; mIsAm = true;
// 如果当前小时为0
if (hourOfDay == 0) { if (hourOfDay == 0) {
// 当前小时设置为12
hourOfDay = HOURS_IN_HALF_DAY; hourOfDay = HOURS_IN_HALF_DAY;
} }
} }
// 更新上午/下午控制
updateAmPmControl(); updateAmPmControl();
} }
// 设置小时选择器的值
mHourSpinner.setValue(hourOfDay); mHourSpinner.setValue(hourOfDay);
// 日期时间改变
onDateTimeChanged(); onDateTimeChanged();
} }
@ -503,7 +394,6 @@ public class DateTimePicker extends FrameLayout {
* *
* @return The Current Minute * @return The Current Minute
*/ */
// 获取当前分钟
public int getCurrentMinute() { public int getCurrentMinute() {
return mDate.get(Calendar.MINUTE); return mDate.get(Calendar.MINUTE);
} }
@ -512,22 +402,17 @@ public class DateTimePicker extends FrameLayout {
* Set current minute * Set current minute
*/ */
public void setCurrentMinute(int minute) { public void setCurrentMinute(int minute) {
// 如果mInitialising为false且minute等于getCurrentMinute(),则直接返回
if (!mInitialising && minute == getCurrentMinute()) { if (!mInitialising && minute == getCurrentMinute()) {
return; return;
} }
// 设置mMinuteSpinner的值为minute
mMinuteSpinner.setValue(minute); mMinuteSpinner.setValue(minute);
// 设置mDate的分钟为minute
mDate.set(Calendar.MINUTE, minute); mDate.set(Calendar.MINUTE, minute);
// 调用onDateTimeChanged()方法
onDateTimeChanged(); onDateTimeChanged();
} }
/** /**
* @return true if this is in 24 hour view else false. * @return true if this is in 24 hour view else false.
*/ */
// 判断是否为24小时制
public boolean is24HourView () { public boolean is24HourView () {
return mIs24HourView; return mIs24HourView;
} }
@ -538,73 +423,47 @@ public class DateTimePicker extends FrameLayout {
* @param is24HourView True for 24 hour mode. False for AM/PM mode. * @param is24HourView True for 24 hour mode. False for AM/PM mode.
*/ */
public void set24HourView(boolean is24HourView) { public void set24HourView(boolean is24HourView) {
// 如果当前时间格式和传入的时间格式相同,则直接返回
if (mIs24HourView == is24HourView) { if (mIs24HourView == is24HourView) {
return; return;
} }
// 更新时间格式
mIs24HourView = is24HourView; mIs24HourView = is24HourView;
// 如果是24小时制则隐藏上午/下午选择器
mAmPmSpinner.setVisibility(is24HourView ? View.GONE : View.VISIBLE); mAmPmSpinner.setVisibility(is24HourView ? View.GONE : View.VISIBLE);
// 获取当前小时数
int hour = getCurrentHourOfDay(); int hour = getCurrentHourOfDay();
// 更新小时选择器
updateHourControl(); updateHourControl();
// 设置当前小时数
setCurrentHour(hour); setCurrentHour(hour);
// 更新上午/下午选择器
updateAmPmControl(); updateAmPmControl();
} }
private void updateDateControl() { private void updateDateControl() {
// 获取当前日期
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
// 将当前日期设置为mDate的时间
cal.setTimeInMillis(mDate.getTimeInMillis()); cal.setTimeInMillis(mDate.getTimeInMillis());
// 将当前日期向前推DAYS_IN_ALL_WEEK / 2 - 1天
cal.add(Calendar.DAY_OF_YEAR, -DAYS_IN_ALL_WEEK / 2 - 1); cal.add(Calendar.DAY_OF_YEAR, -DAYS_IN_ALL_WEEK / 2 - 1);
// 清空mDateSpinner的显示值
mDateSpinner.setDisplayedValues(null); mDateSpinner.setDisplayedValues(null);
// 循环DAYS_IN_ALL_WEEK次
for (int i = 0; i < DAYS_IN_ALL_WEEK; ++i) { for (int i = 0; i < DAYS_IN_ALL_WEEK; ++i) {
// 将当前日期加1天
cal.add(Calendar.DAY_OF_YEAR, 1); cal.add(Calendar.DAY_OF_YEAR, 1);
// 将当前日期格式化为"MM.dd EEEE"的字符串
mDateDisplayValues[i] = (String) DateFormat.format("MM.dd EEEE", cal); mDateDisplayValues[i] = (String) DateFormat.format("MM.dd EEEE", cal);
} }
// 将mDateSpinner的显示值设置为mDateDisplayValues
mDateSpinner.setDisplayedValues(mDateDisplayValues); mDateSpinner.setDisplayedValues(mDateDisplayValues);
// 将mDateSpinner的值设置为DAYS_IN_ALL_WEEK / 2
mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2); mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2);
// 使mDateSpinner无效
mDateSpinner.invalidate(); mDateSpinner.invalidate();
} }
private void updateAmPmControl() { private void updateAmPmControl() {
// 如果是24小时制则隐藏上午/下午选择器
if (mIs24HourView) { if (mIs24HourView) {
mAmPmSpinner.setVisibility(View.GONE); mAmPmSpinner.setVisibility(View.GONE);
} else { } else {
// 如果是上午,则选择上午,否则选择下午
int index = mIsAm ? Calendar.AM : Calendar.PM; int index = mIsAm ? Calendar.AM : Calendar.PM;
mAmPmSpinner.setValue(index); mAmPmSpinner.setValue(index);
// 显示上午/下午选择器
mAmPmSpinner.setVisibility(View.VISIBLE); mAmPmSpinner.setVisibility(View.VISIBLE);
} }
} }
// 更新小时控件
private void updateHourControl() { private void updateHourControl() {
// 如果是24小时制
if (mIs24HourView) { if (mIs24HourView) {
// 设置小时选择器的最小值为24小时制最小值
mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW); mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW);
// 设置小时选择器的最大值为24小时制最大值
mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW); mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW);
} else { } else {
// 设置小时选择器的最小值为12小时制最小值
mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW); mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW);
// 设置小时选择器的最大值为12小时制最大值
mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW); mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW);
} }
} }
@ -613,16 +472,12 @@ public class DateTimePicker extends FrameLayout {
* Set the callback that indicates the 'Set' button has been pressed. * Set the callback that indicates the 'Set' button has been pressed.
* @param callback the callback, if null will do nothing * @param callback the callback, if null will do nothing
*/ */
// 设置日期时间改变监听器
public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) { public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) {
mOnDateTimeChangedListener = callback; mOnDateTimeChangedListener = callback;
} }
// 日期时间改变时调用
private void onDateTimeChanged() { private void onDateTimeChanged() {
// 如果日期时间改变监听器不为空
if (mOnDateTimeChangedListener != null) { if (mOnDateTimeChangedListener != null) {
// 调用日期时间改变监听器的onDateTimeChanged方法并传入当前日期时间
mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(), mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(),
getCurrentMonth(), getCurrentDay(), getCurrentHourOfDay(), getCurrentMinute()); getCurrentMonth(), getCurrentDay(), getCurrentHourOfDay(), getCurrentMinute());
} }

@ -31,83 +31,57 @@ import android.text.format.DateUtils;
public class DateTimePickerDialog extends AlertDialog implements OnClickListener { public class DateTimePickerDialog extends AlertDialog implements OnClickListener {
// 定义一个Calendar对象用于存储日期和时间
private Calendar mDate = Calendar.getInstance(); private Calendar mDate = Calendar.getInstance();
// 定义一个布尔变量用于判断是否为24小时制
private boolean mIs24HourView; private boolean mIs24HourView;
// 定义一个OnDateTimeSetListener对象用于监听日期时间的设置
private OnDateTimeSetListener mOnDateTimeSetListener; private OnDateTimeSetListener mOnDateTimeSetListener;
// 定义一个DateTimePicker对象用于显示日期时间选择器
private DateTimePicker mDateTimePicker; private DateTimePicker mDateTimePicker;
// 定义一个接口,用于监听日期时间设置
public interface OnDateTimeSetListener { public interface OnDateTimeSetListener {
// 当日期时间设置时,调用此方法
void OnDateTimeSet(AlertDialog dialog, long date); void OnDateTimeSet(AlertDialog dialog, long date);
} }
// 定义一个DateTimePickerDialog类传入Context和long类型的date参数
public DateTimePickerDialog(Context context, long date) { public DateTimePickerDialog(Context context, long date) {
// 调用父类的构造方法
super(context); super(context);
// 创建一个DateTimePicker对象
mDateTimePicker = new DateTimePicker(context); mDateTimePicker = new DateTimePicker(context);
// 设置视图
setView(mDateTimePicker); setView(mDateTimePicker);
// 设置DateTimePicker的监听器
mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() { mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() {
public void onDateTimeChanged(DateTimePicker view, int year, int month, 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.YEAR, year);
mDate.set(Calendar.MONTH, month); mDate.set(Calendar.MONTH, month);
mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth); mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
mDate.set(Calendar.HOUR_OF_DAY, hourOfDay); mDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
mDate.set(Calendar.MINUTE, minute); mDate.set(Calendar.MINUTE, minute);
// 更新标题
updateTitle(mDate.getTimeInMillis()); updateTitle(mDate.getTimeInMillis());
} }
}); });
// 设置日期
mDate.setTimeInMillis(date); mDate.setTimeInMillis(date);
mDate.set(Calendar.SECOND, 0); mDate.set(Calendar.SECOND, 0);
// 设置当前日期
mDateTimePicker.setCurrentDate(mDate.getTimeInMillis()); mDateTimePicker.setCurrentDate(mDate.getTimeInMillis());
// 设置按钮
setButton(context.getString(R.string.datetime_dialog_ok), this); 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);
// 设置24小时制
set24HourView(DateFormat.is24HourFormat(this.getContext())); set24HourView(DateFormat.is24HourFormat(this.getContext()));
// 更新标题
updateTitle(mDate.getTimeInMillis()); updateTitle(mDate.getTimeInMillis());
} }
// 设置是否为24小时制
public void set24HourView(boolean is24HourView) { public void set24HourView(boolean is24HourView) {
mIs24HourView = is24HourView; mIs24HourView = is24HourView;
} }
// 设置日期时间设置监听器
public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) { public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) {
// 将传入的监听器赋值给成员变量
mOnDateTimeSetListener = callBack; mOnDateTimeSetListener = callBack;
} }
// 更新标题
private void updateTitle(long date) { private void updateTitle(long date) {
// 设置日期格式
int flag = int flag =
DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_YEAR |
DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_DATE |
DateUtils.FORMAT_SHOW_TIME; DateUtils.FORMAT_SHOW_TIME;
// 如果是24小时制则设置格式为24小时制
flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR; flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR;
// 格式化日期并设置标题
setTitle(DateUtils.formatDateTime(this.getContext(), date, flag)); setTitle(DateUtils.formatDateTime(this.getContext(), date, flag));
} }
public void onClick(DialogInterface arg0, int arg1) { public void onClick(DialogInterface arg0, int arg1) {
// 如果mOnDateTimeSetListener不为空则调用其OnDateTimeSet方法传入当前对象和mDate的时间戳
if (mOnDateTimeSetListener != null) { if (mOnDateTimeSetListener != null) {
mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis()); mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis());
} }

@ -30,68 +30,49 @@ import net.micode.notes.data.Notes.NoteColumns;
public class FoldersListAdapter extends CursorAdapter { public class FoldersListAdapter extends CursorAdapter {
// 定义一个静态常量,用于存储查询结果的列名
public static final String [] PROJECTION = { public static final String [] PROJECTION = {
NoteColumns.ID, // 存储笔记的ID NoteColumns.ID,
NoteColumns.SNIPPET // 存储笔记的摘要 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 static final int NAME_COLUMN = 1;
// 构造函数用于初始化FoldersListAdapter对象
public FoldersListAdapter(Context context, Cursor c) { public FoldersListAdapter(Context context, Cursor c) {
super(context, c); super(context, c);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
@Override @Override
// 重写newView方法用于创建新的视图
public View newView(Context context, Cursor cursor, ViewGroup parent) { public View newView(Context context, Cursor cursor, ViewGroup parent) {
// 创建一个新的FolderListItem视图
return new FolderListItem(context); return new FolderListItem(context);
} }
@Override @Override
public void bindView(View view, Context context, Cursor cursor) { public void bindView(View view, Context context, Cursor cursor) {
// 判断view是否为FolderListItem类型
if (view instanceof FolderListItem) { if (view instanceof FolderListItem) {
// 获取文件夹名称
String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
// 绑定文件夹名称
((FolderListItem) view).bind(folderName); ((FolderListItem) view).bind(folderName);
} }
} }
// 根据位置获取文件夹名称
public String getFolderName(Context context, int position) { public String getFolderName(Context context, int position) {
// 获取指定位置的Cursor对象
Cursor cursor = (Cursor) getItem(position); Cursor cursor = (Cursor) getItem(position);
// 如果Cursor对象的ID列的值为Notes.ID_ROOT_FOLDER则返回菜单移动到父文件夹的字符串否则返回Cursor对象的NAME列的值
return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
} }
// 定义一个内部类FolderListItem继承自LinearLayout
private class FolderListItem extends LinearLayout { private class FolderListItem extends LinearLayout {
// 定义一个TextView变量mName
private TextView mName; private TextView mName;
// 构造方法传入Context参数
public FolderListItem(Context context) { public FolderListItem(Context context) {
super(context); super(context);
// 使用inflate方法加载布局文件R.layout.folder_list_item并将布局文件添加到当前LinearLayout中
inflate(context, R.layout.folder_list_item, this); inflate(context, R.layout.folder_list_item, this);
// 通过findViewById方法获取布局文件中的TextView控件并赋值给mName变量
mName = (TextView) findViewById(R.id.tv_folder_name); mName = (TextView) findViewById(R.id.tv_folder_name);
} }
// 绑定方法传入一个String参数name
public void bind(String name) { public void bind(String name) {
// 将传入的name参数设置给mName控件的文本
mName.setText(name); mName.setText(name);
} }
} }

@ -74,26 +74,18 @@ import java.util.regex.Pattern;
public class NoteEditActivity extends Activity implements OnClickListener, public class NoteEditActivity extends Activity implements OnClickListener,
NoteSettingChangedListener, OnTextViewChangeListener { NoteSettingChangedListener, OnTextViewChangeListener {
// 定义一个内部类HeadViewHolder用于保存头部视图的控件
private class HeadViewHolder { private class HeadViewHolder {
// 保存修改日期的TextView
public TextView tvModified; public TextView tvModified;
// 保存提醒图标的ImageView
public ImageView ivAlertIcon; public ImageView ivAlertIcon;
// 保存提醒日期的TextView
public TextView tvAlertDate; public TextView tvAlertDate;
// 保存设置背景颜色的ImageView
public ImageView ibSetBgColor; public ImageView ibSetBgColor;
} }
// 定义一个静态的Map用于存储背景选择按钮的ID和对应的颜色值
private static final Map<Integer, Integer> sBgSelectorBtnsMap = new HashMap<Integer, Integer>(); private static final Map<Integer, Integer> sBgSelectorBtnsMap = new HashMap<Integer, Integer>();
// 静态代码块用于初始化Map
static { static {
// 将背景选择按钮的ID和对应的颜色值放入Map中
sBgSelectorBtnsMap.put(R.id.iv_bg_yellow, ResourceParser.YELLOW); sBgSelectorBtnsMap.put(R.id.iv_bg_yellow, ResourceParser.YELLOW);
sBgSelectorBtnsMap.put(R.id.iv_bg_red, ResourceParser.RED); sBgSelectorBtnsMap.put(R.id.iv_bg_red, ResourceParser.RED);
sBgSelectorBtnsMap.put(R.id.iv_bg_blue, ResourceParser.BLUE); sBgSelectorBtnsMap.put(R.id.iv_bg_blue, ResourceParser.BLUE);
@ -102,24 +94,16 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
private static final Map<Integer, Integer> sBgSelectorSelectionMap = new HashMap<Integer, Integer>(); private static final Map<Integer, Integer> sBgSelectorSelectionMap = new HashMap<Integer, Integer>();
// 初始化静态变量sBgSelectorSelectionMap用于存储背景选择器的资源ID
static { static {
// 将ResourceParser.YELLOW对应的资源ID存入sBgSelectorSelectionMap
sBgSelectorSelectionMap.put(ResourceParser.YELLOW, R.id.iv_bg_yellow_select); sBgSelectorSelectionMap.put(ResourceParser.YELLOW, R.id.iv_bg_yellow_select);
// 将ResourceParser.RED对应的资源ID存入sBgSelectorSelectionMap
sBgSelectorSelectionMap.put(ResourceParser.RED, R.id.iv_bg_red_select); sBgSelectorSelectionMap.put(ResourceParser.RED, R.id.iv_bg_red_select);
// 将ResourceParser.BLUE对应的资源ID存入sBgSelectorSelectionMap
sBgSelectorSelectionMap.put(ResourceParser.BLUE, R.id.iv_bg_blue_select); sBgSelectorSelectionMap.put(ResourceParser.BLUE, R.id.iv_bg_blue_select);
// 将ResourceParser.GREEN对应的资源ID存入sBgSelectorSelectionMap
sBgSelectorSelectionMap.put(ResourceParser.GREEN, R.id.iv_bg_green_select); sBgSelectorSelectionMap.put(ResourceParser.GREEN, R.id.iv_bg_green_select);
// 将ResourceParser.WHITE对应的资源ID存入sBgSelectorSelectionMap
sBgSelectorSelectionMap.put(ResourceParser.WHITE, R.id.iv_bg_white_select); sBgSelectorSelectionMap.put(ResourceParser.WHITE, R.id.iv_bg_white_select);
} }
// 定义一个静态常量用于存储字体大小按钮的ID和对应的字体大小
private static final Map<Integer, Integer> sFontSizeBtnsMap = new HashMap<Integer, Integer>(); private static final Map<Integer, Integer> sFontSizeBtnsMap = new HashMap<Integer, Integer>();
static { static {
// 将字体大小按钮的ID和对应的字体大小放入Map中
sFontSizeBtnsMap.put(R.id.ll_font_large, ResourceParser.TEXT_LARGE); sFontSizeBtnsMap.put(R.id.ll_font_large, ResourceParser.TEXT_LARGE);
sFontSizeBtnsMap.put(R.id.ll_font_small, ResourceParser.TEXT_SMALL); sFontSizeBtnsMap.put(R.id.ll_font_small, ResourceParser.TEXT_SMALL);
sFontSizeBtnsMap.put(R.id.ll_font_normal, ResourceParser.TEXT_MEDIUM); sFontSizeBtnsMap.put(R.id.ll_font_normal, ResourceParser.TEXT_MEDIUM);
@ -127,7 +111,6 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
private static final Map<Integer, Integer> sFontSelectorSelectionMap = new HashMap<Integer, Integer>(); private static final Map<Integer, Integer> sFontSelectorSelectionMap = new HashMap<Integer, Integer>();
// 初始化字体选择器选择映射
static { static {
sFontSelectorSelectionMap.put(ResourceParser.TEXT_LARGE, R.id.iv_large_select); sFontSelectorSelectionMap.put(ResourceParser.TEXT_LARGE, R.id.iv_large_select);
sFontSelectorSelectionMap.put(ResourceParser.TEXT_SMALL, R.id.iv_small_select); sFontSelectorSelectionMap.put(ResourceParser.TEXT_SMALL, R.id.iv_small_select);
@ -137,67 +120,45 @@ public class NoteEditActivity extends Activity implements OnClickListener,
private static final String TAG = "NoteEditActivity"; private static final String TAG = "NoteEditActivity";
// 头部视图持有者
private HeadViewHolder mNoteHeaderHolder; private HeadViewHolder mNoteHeaderHolder;
// 头部视图面板
private View mHeadViewPanel; private View mHeadViewPanel;
// 笔记背景颜色选择器
private View mNoteBgColorSelector; private View mNoteBgColorSelector;
// 字体大小选择器
private View mFontSizeSelector; private View mFontSizeSelector;
// 笔记编辑器
private EditText mNoteEditor; private EditText mNoteEditor;
// 笔记编辑器面板
private View mNoteEditorPanel; private View mNoteEditorPanel;
// 工作中的笔记
private WorkingNote mWorkingNote; private WorkingNote mWorkingNote;
// 共享偏好设置
private SharedPreferences mSharedPrefs; private SharedPreferences mSharedPrefs;
// 字体大小ID
private int mFontSizeId; private int mFontSizeId;
// 字体大小偏好设置键
private static final String PREFERENCE_FONT_SIZE = "pref_font_size"; private static final String PREFERENCE_FONT_SIZE = "pref_font_size";
// 快捷图标标题最大长度
private static final int SHORTCUT_ICON_TITLE_MAX_LEN = 10; private static final int SHORTCUT_ICON_TITLE_MAX_LEN = 10;
// 已选中的标签
public static final String TAG_CHECKED = String.valueOf('\u221A'); public static final String TAG_CHECKED = String.valueOf('\u221A');
// 未选中的标签
public static final String TAG_UNCHECKED = String.valueOf('\u25A1'); public static final String TAG_UNCHECKED = String.valueOf('\u25A1');
// 编辑文本列表
private LinearLayout mEditTextList; private LinearLayout mEditTextList;
// 用户查询
private String mUserQuery; private String mUserQuery;
// 正则表达式
private Pattern mPattern; private Pattern mPattern;
@Override @Override
// 重写onCreate方法
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
// 调用父类的onCreate方法
this.setContentView(R.layout.note_edit); this.setContentView(R.layout.note_edit);
// 设置当前Activity的布局文件为note_edit.xml
if (savedInstanceState == null && !initActivityState(getIntent())) { if (savedInstanceState == null && !initActivityState(getIntent())) {
// 如果savedInstanceState为空且initActivityState方法返回false
finish(); finish();
// 结束当前Activity
return; return;
} }
initResources(); initResources();
// 初始化资源
} }
/** /**
@ -205,25 +166,16 @@ public class NoteEditActivity extends Activity implements OnClickListener,
* user load this activity, we should restore the former state * user load this activity, we should restore the former state
*/ */
@Override @Override
// 重写onRestoreInstanceState方法
protected void onRestoreInstanceState(Bundle savedInstanceState) { protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState); super.onRestoreInstanceState(savedInstanceState);
// 调用父类的onRestoreInstanceState方法
if (savedInstanceState != null && savedInstanceState.containsKey(Intent.EXTRA_UID)) { if (savedInstanceState != null && savedInstanceState.containsKey(Intent.EXTRA_UID)) {
// 如果savedInstanceState不为空且包含Intent.EXTRA_UID键
Intent intent = new Intent(Intent.ACTION_VIEW); Intent intent = new Intent(Intent.ACTION_VIEW);
// 创建一个Intent对象并设置Action为Intent.ACTION_VIEW
intent.putExtra(Intent.EXTRA_UID, savedInstanceState.getLong(Intent.EXTRA_UID)); intent.putExtra(Intent.EXTRA_UID, savedInstanceState.getLong(Intent.EXTRA_UID));
// 将savedInstanceState中的Intent.EXTRA_UID键对应的值添加到Intent对象中
if (!initActivityState(intent)) { if (!initActivityState(intent)) {
// 如果initActivityState方法返回false
finish(); finish();
// 结束当前Activity
return; return;
} }
// 如果initActivityState方法返回true
Log.d(TAG, "Restoring from killed activity"); Log.d(TAG, "Restoring from killed activity");
// 打印日志表示从被杀掉的Activity中恢复
} }
} }
@ -245,7 +197,6 @@ public class NoteEditActivity extends Activity implements OnClickListener,
mUserQuery = intent.getStringExtra(SearchManager.USER_QUERY); mUserQuery = intent.getStringExtra(SearchManager.USER_QUERY);
} }
// Check if the note exists
if (!DataUtils.visibleInNoteDatabase(getContentResolver(), noteId, Notes.TYPE_NOTE)) { if (!DataUtils.visibleInNoteDatabase(getContentResolver(), noteId, Notes.TYPE_NOTE)) {
Intent jump = new Intent(this, NotesListActivity.class); Intent jump = new Intent(this, NotesListActivity.class);
startActivity(jump); startActivity(jump);
@ -253,7 +204,6 @@ public class NoteEditActivity extends Activity implements OnClickListener,
finish(); finish();
return false; return false;
} else { } else {
// Load the note
mWorkingNote = WorkingNote.load(this, noteId); mWorkingNote = WorkingNote.load(this, noteId);
if (mWorkingNote == null) { if (mWorkingNote == null) {
Log.e(TAG, "load note failed with note id" + noteId); Log.e(TAG, "load note failed with note id" + noteId);
@ -261,7 +211,6 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return false; return false;
} }
} }
// Set the soft input mode
getWindow().setSoftInputMode( getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN
| WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
@ -301,7 +250,6 @@ public class NoteEditActivity extends Activity implements OnClickListener,
bgResId); bgResId);
} }
// Set the soft input mode
getWindow().setSoftInputMode( getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
| WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
@ -310,7 +258,6 @@ public class NoteEditActivity extends Activity implements OnClickListener,
finish(); finish();
return false; return false;
} }
// Set the listener for the note
mWorkingNote.setOnSettingStatusChangedListener(this); mWorkingNote.setOnSettingStatusChangedListener(this);
return true; return true;
} }
@ -318,33 +265,24 @@ public class NoteEditActivity extends Activity implements OnClickListener,
@Override @Override
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
// Initialize the note screen
initNoteScreen(); initNoteScreen();
} }
private void initNoteScreen() { private void initNoteScreen() {
// Set the text appearance of the note editor
mNoteEditor.setTextAppearance(this, TextAppearanceResources mNoteEditor.setTextAppearance(this, TextAppearanceResources
.getTexAppearanceResource(mFontSizeId)); .getTexAppearanceResource(mFontSizeId));
// Check if the note is in check list mode
if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {
// Switch to list mode
switchToListMode(mWorkingNote.getContent()); switchToListMode(mWorkingNote.getContent());
} else { } else {
// Set the text of the note editor
mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery)); mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery));
// Set the selection of the note editor
mNoteEditor.setSelection(mNoteEditor.getText().length()); mNoteEditor.setSelection(mNoteEditor.getText().length());
} }
// Set the visibility of the background selector
for (Integer id : sBgSelectorSelectionMap.keySet()) { for (Integer id : sBgSelectorSelectionMap.keySet()) {
findViewById(sBgSelectorSelectionMap.get(id)).setVisibility(View.GONE); findViewById(sBgSelectorSelectionMap.get(id)).setVisibility(View.GONE);
} }
// Set the background of the header and note editor panel
mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId()); mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId());
mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId()); mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId());
// Set the modified date of the note
mNoteHeaderHolder.tvModified.setText(DateUtils.formatDateTime(this, mNoteHeaderHolder.tvModified.setText(DateUtils.formatDateTime(this,
mWorkingNote.getModifiedDate(), DateUtils.FORMAT_SHOW_DATE mWorkingNote.getModifiedDate(), DateUtils.FORMAT_SHOW_DATE
| DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_SHOW_TIME
@ -354,42 +292,29 @@ public class NoteEditActivity extends Activity implements OnClickListener,
* TODO: Add the menu for setting alert. Currently disable it because the DateTimePicker * TODO: Add the menu for setting alert. Currently disable it because the DateTimePicker
* is not ready * is not ready
*/ */
// Show the alert header
showAlertHeader(); showAlertHeader();
} }
private void showAlertHeader() { private void showAlertHeader() {
// 如果当前笔记设置了提醒
if (mWorkingNote.hasClockAlert()) { if (mWorkingNote.hasClockAlert()) {
// 获取当前时间
long time = System.currentTimeMillis(); long time = System.currentTimeMillis();
// 如果当前时间大于提醒时间
if (time > mWorkingNote.getAlertDate()) { if (time > mWorkingNote.getAlertDate()) {
// 设置提醒日期为已过期
mNoteHeaderHolder.tvAlertDate.setText(R.string.note_alert_expired); mNoteHeaderHolder.tvAlertDate.setText(R.string.note_alert_expired);
} else { } else {
// 设置提醒日期为相对时间
mNoteHeaderHolder.tvAlertDate.setText(DateUtils.getRelativeTimeSpanString( mNoteHeaderHolder.tvAlertDate.setText(DateUtils.getRelativeTimeSpanString(
mWorkingNote.getAlertDate(), time, DateUtils.MINUTE_IN_MILLIS)); mWorkingNote.getAlertDate(), time, DateUtils.MINUTE_IN_MILLIS));
} }
// 显示提醒日期
mNoteHeaderHolder.tvAlertDate.setVisibility(View.VISIBLE); mNoteHeaderHolder.tvAlertDate.setVisibility(View.VISIBLE);
// 显示提醒图标
mNoteHeaderHolder.ivAlertIcon.setVisibility(View.VISIBLE); mNoteHeaderHolder.ivAlertIcon.setVisibility(View.VISIBLE);
} else { } else {
// 隐藏提醒日期
mNoteHeaderHolder.tvAlertDate.setVisibility(View.GONE); mNoteHeaderHolder.tvAlertDate.setVisibility(View.GONE);
// 隐藏提醒图标
mNoteHeaderHolder.ivAlertIcon.setVisibility(View.GONE); mNoteHeaderHolder.ivAlertIcon.setVisibility(View.GONE);
}; };
} }
// 重写onNewIntent方法
@Override @Override
protected void onNewIntent(Intent intent) { protected void onNewIntent(Intent intent) {
// 调用父类的onNewIntent方法
super.onNewIntent(intent); super.onNewIntent(intent);
// 初始化活动状态
initActivityState(intent); initActivityState(intent);
} }
@ -401,93 +326,64 @@ public class NoteEditActivity extends Activity implements OnClickListener,
* generate a id. If the editing note is not worth saving, there * generate a id. If the editing note is not worth saving, there
* is no id which is equivalent to create new note * is no id which is equivalent to create new note
*/ */
// 如果当前编辑的笔记没有note id我们首先应该保存它以生成一个id。如果编辑的笔记不值得保存那么没有id相当于创建新笔记
if (!mWorkingNote.existInDatabase()) { if (!mWorkingNote.existInDatabase()) {
saveNote(); saveNote();
} }
// 将当前编辑的笔记的id保存到Bundle中
outState.putLong(Intent.EXTRA_UID, mWorkingNote.getNoteId()); outState.putLong(Intent.EXTRA_UID, mWorkingNote.getNoteId());
// 打印日志记录当前编辑的笔记的id
Log.d(TAG, "Save working note id: " + mWorkingNote.getNoteId() + " onSaveInstanceState"); Log.d(TAG, "Save working note id: " + mWorkingNote.getNoteId() + " onSaveInstanceState");
} }
@Override @Override
public boolean dispatchTouchEvent(MotionEvent ev) { public boolean dispatchTouchEvent(MotionEvent ev) {
// 如果mNoteBgColorSelector可见且不在mNoteBgColorSelector范围内则隐藏mNoteBgColorSelector
if (mNoteBgColorSelector.getVisibility() == View.VISIBLE if (mNoteBgColorSelector.getVisibility() == View.VISIBLE
&& !inRangeOfView(mNoteBgColorSelector, ev)) { && !inRangeOfView(mNoteBgColorSelector, ev)) {
mNoteBgColorSelector.setVisibility(View.GONE); mNoteBgColorSelector.setVisibility(View.GONE);
return true; return true;
} }
// 如果mFontSizeSelector可见且不在mFontSizeSelector范围内则隐藏mFontSizeSelector
if (mFontSizeSelector.getVisibility() == View.VISIBLE if (mFontSizeSelector.getVisibility() == View.VISIBLE
&& !inRangeOfView(mFontSizeSelector, ev)) { && !inRangeOfView(mFontSizeSelector, ev)) {
mFontSizeSelector.setVisibility(View.GONE); mFontSizeSelector.setVisibility(View.GONE);
return true; return true;
} }
// 否则调用父类的dispatchTouchEvent方法
return super.dispatchTouchEvent(ev); return super.dispatchTouchEvent(ev);
} }
private boolean inRangeOfView(View view, MotionEvent ev) { private boolean inRangeOfView(View view, MotionEvent ev) {
// 获取view在屏幕上的位置
int []location = new int[2]; int []location = new int[2];
view.getLocationOnScreen(location); view.getLocationOnScreen(location);
// 获取view的x坐标
int x = location[0]; int x = location[0];
// 获取view的y坐标
int y = location[1]; int y = location[1];
// 判断ev的x坐标是否在view的范围内
if (ev.getX() < x if (ev.getX() < x
// 判断ev的x坐标是否在view的范围内
|| ev.getX() > (x + view.getWidth()) || ev.getX() > (x + view.getWidth())
// 判断ev的y坐标是否在view的范围内
|| ev.getY() < y || ev.getY() < y
// 判断ev的y坐标是否在view的范围内
|| ev.getY() > (y + view.getHeight())) { || ev.getY() > (y + view.getHeight())) {
// 如果不在范围内返回false
return false; return false;
} }
// 如果在范围内返回true
return true; return true;
} }
private void initResources() { private void initResources() {
// 初始化标题栏
mHeadViewPanel = findViewById(R.id.note_title); mHeadViewPanel = findViewById(R.id.note_title);
// 初始化标题栏的ViewHolder
mNoteHeaderHolder = new HeadViewHolder(); mNoteHeaderHolder = new HeadViewHolder();
// 初始化标题栏中的修改日期TextView
mNoteHeaderHolder.tvModified = (TextView) findViewById(R.id.tv_modified_date); mNoteHeaderHolder.tvModified = (TextView) findViewById(R.id.tv_modified_date);
// 初始化标题栏中的提醒图标ImageView
mNoteHeaderHolder.ivAlertIcon = (ImageView) findViewById(R.id.iv_alert_icon); mNoteHeaderHolder.ivAlertIcon = (ImageView) findViewById(R.id.iv_alert_icon);
// 初始化标题栏中的提醒日期TextView
mNoteHeaderHolder.tvAlertDate = (TextView) findViewById(R.id.tv_alert_date); mNoteHeaderHolder.tvAlertDate = (TextView) findViewById(R.id.tv_alert_date);
// 初始化标题栏中的设置背景颜色按钮ImageView
mNoteHeaderHolder.ibSetBgColor = (ImageView) findViewById(R.id.btn_set_bg_color); mNoteHeaderHolder.ibSetBgColor = (ImageView) findViewById(R.id.btn_set_bg_color);
// 设置设置背景颜色按钮的点击事件
mNoteHeaderHolder.ibSetBgColor.setOnClickListener(this); mNoteHeaderHolder.ibSetBgColor.setOnClickListener(this);
// 初始化笔记编辑框
mNoteEditor = (EditText) findViewById(R.id.note_edit_view); mNoteEditor = (EditText) findViewById(R.id.note_edit_view);
// 初始化笔记编辑框的面板
mNoteEditorPanel = findViewById(R.id.sv_note_edit); mNoteEditorPanel = findViewById(R.id.sv_note_edit);
// 初始化笔记背景颜色选择器
mNoteBgColorSelector = findViewById(R.id.note_bg_color_selector); mNoteBgColorSelector = findViewById(R.id.note_bg_color_selector);
// 遍历背景颜色选择器中的按钮,并设置点击事件
for (int id : sBgSelectorBtnsMap.keySet()) { for (int id : sBgSelectorBtnsMap.keySet()) {
ImageView iv = (ImageView) findViewById(id); ImageView iv = (ImageView) findViewById(id);
iv.setOnClickListener(this); iv.setOnClickListener(this);
} }
// 初始化字体大小选择器
mFontSizeSelector = findViewById(R.id.font_size_selector); mFontSizeSelector = findViewById(R.id.font_size_selector);
// 遍历字体大小选择器中的按钮,并设置点击事件
for (int id : sFontSizeBtnsMap.keySet()) { for (int id : sFontSizeBtnsMap.keySet()) {
View view = findViewById(id); View view = findViewById(id);
view.setOnClickListener(this); view.setOnClickListener(this);
}; };
// 获取默认的SharedPreferences
mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
mFontSizeId = mSharedPrefs.getInt(PREFERENCE_FONT_SIZE, ResourceParser.BG_DEFAULT_FONT_SIZE); mFontSizeId = mSharedPrefs.getInt(PREFERENCE_FONT_SIZE, ResourceParser.BG_DEFAULT_FONT_SIZE);
/** /**
@ -501,176 +397,121 @@ public class NoteEditActivity extends Activity implements OnClickListener,
mEditTextList = (LinearLayout) findViewById(R.id.note_edit_list); mEditTextList = (LinearLayout) findViewById(R.id.note_edit_list);
} }
// 重写onPause方法
@Override @Override
protected void onPause() { protected void onPause() {
// 调用父类的onPause方法
super.onPause(); super.onPause();
// 如果保存笔记数据成功
if(saveNote()) { if(saveNote()) {
// 打印日志,显示笔记数据的长度
Log.d(TAG, "Note data was saved with length:" + mWorkingNote.getContent().length()); Log.d(TAG, "Note data was saved with length:" + mWorkingNote.getContent().length());
} }
// 清除设置状态
clearSettingState(); clearSettingState();
} }
private void updateWidget() { private void updateWidget() {
// 创建一个Intent用于更新AppWidget
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE); Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
// 判断当前笔记的Widget类型
if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_2X) { if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_2X) {
// 如果是2x类型的Widget设置Intent的Class为NoteWidgetProvider_2x
intent.setClass(this, NoteWidgetProvider_2x.class); intent.setClass(this, NoteWidgetProvider_2x.class);
} else if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_4X) { } else if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_4X) {
// 如果是4x类型的Widget设置Intent的Class为NoteWidgetProvider_4x
intent.setClass(this, NoteWidgetProvider_4x.class); intent.setClass(this, NoteWidgetProvider_4x.class);
} else { } else {
// 如果是其他类型的Widget输出错误日志并返回
Log.e(TAG, "Unspported widget type"); Log.e(TAG, "Unspported widget type");
return; return;
} }
// 将当前笔记的WidgetId添加到Intent中
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] {
mWorkingNote.getWidgetId() mWorkingNote.getWidgetId()
}); });
// 发送广播更新AppWidget
sendBroadcast(intent); sendBroadcast(intent);
// 设置结果为RESULT_OK
setResult(RESULT_OK, intent); setResult(RESULT_OK, intent);
} }
public void onClick(View v) { public void onClick(View v) {
// 获取点击的View的id
int id = v.getId(); int id = v.getId();
// 如果点击的是设置背景颜色的按钮
if (id == R.id.btn_set_bg_color) { if (id == R.id.btn_set_bg_color) {
// 显示背景颜色选择器
mNoteBgColorSelector.setVisibility(View.VISIBLE); mNoteBgColorSelector.setVisibility(View.VISIBLE);
// 显示当前背景颜色选择器
findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(
- View.VISIBLE); - View.VISIBLE);
// 如果点击的是背景颜色选择器中的按钮
} else if (sBgSelectorBtnsMap.containsKey(id)) { } else if (sBgSelectorBtnsMap.containsKey(id)) {
// 隐藏当前背景颜色选择器
findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(
View.GONE); View.GONE);
// 设置当前背景颜色
mWorkingNote.setBgColorId(sBgSelectorBtnsMap.get(id)); mWorkingNote.setBgColorId(sBgSelectorBtnsMap.get(id));
// 隐藏背景颜色选择器
mNoteBgColorSelector.setVisibility(View.GONE); mNoteBgColorSelector.setVisibility(View.GONE);
// 如果点击的是字体大小选择器中的按钮
} else if (sFontSizeBtnsMap.containsKey(id)) { } else if (sFontSizeBtnsMap.containsKey(id)) {
// 隐藏当前字体大小选择器
findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.GONE); findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.GONE);
// 设置当前字体大小
mFontSizeId = sFontSizeBtnsMap.get(id); mFontSizeId = sFontSizeBtnsMap.get(id);
// 保存当前字体大小到SharedPreferences
mSharedPrefs.edit().putInt(PREFERENCE_FONT_SIZE, mFontSizeId).commit(); mSharedPrefs.edit().putInt(PREFERENCE_FONT_SIZE, mFontSizeId).commit();
// 显示当前字体大小选择器
findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.VISIBLE); findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.VISIBLE);
// 如果当前笔记处于清单模式
if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {
// 获取当前笔记内容
getWorkingText(); getWorkingText();
// 切换到清单模式
switchToListMode(mWorkingNote.getContent()); switchToListMode(mWorkingNote.getContent());
// 如果当前笔记不处于清单模式
} else { } else {
// 设置当前笔记的字体大小
mNoteEditor.setTextAppearance(this, mNoteEditor.setTextAppearance(this,
TextAppearanceResources.getTexAppearanceResource(mFontSizeId)); TextAppearanceResources.getTexAppearanceResource(mFontSizeId));
} }
// 隐藏字体大小选择器
mFontSizeSelector.setVisibility(View.GONE); mFontSizeSelector.setVisibility(View.GONE);
} }
} }
@Override @Override
public void onBackPressed() { public void onBackPressed() {
// 如果清除设置状态成功,则直接返回
if(clearSettingState()) { if(clearSettingState()) {
return; return;
} }
// 保存笔记
saveNote(); saveNote();
// 调用父类的方法
super.onBackPressed(); super.onBackPressed();
} }
private boolean clearSettingState() { private boolean clearSettingState() {
// 如果mNoteBgColorSelector可见则将其设置为不可见并返回true
if (mNoteBgColorSelector.getVisibility() == View.VISIBLE) { if (mNoteBgColorSelector.getVisibility() == View.VISIBLE) {
mNoteBgColorSelector.setVisibility(View.GONE); mNoteBgColorSelector.setVisibility(View.GONE);
return true; return true;
// 如果mFontSizeSelector可见则将其设置为不可见并返回true
} else if (mFontSizeSelector.getVisibility() == View.VISIBLE) { } else if (mFontSizeSelector.getVisibility() == View.VISIBLE) {
mFontSizeSelector.setVisibility(View.GONE); mFontSizeSelector.setVisibility(View.GONE);
return true; return true;
} }
// 如果以上两种情况都不满足则返回false
return false; return false;
} }
// 当背景颜色改变时调用
public void onBackgroundColorChanged() { public void onBackgroundColorChanged() {
// 根据当前笔记的背景颜色ID找到对应的背景颜色选择器并将其可见性设置为可见
findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(
View.VISIBLE); View.VISIBLE);
// 设置笔记编辑面板的背景颜色为当前笔记的背景颜色资源ID
mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId()); mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId());
// 设置标题面板的背景颜色为当前笔记的标题背景颜色资源ID
mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId()); mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId());
} }
@Override @Override
public boolean onPrepareOptionsMenu(Menu menu) { public boolean onPrepareOptionsMenu(Menu menu) {
// 如果Activity正在结束则返回true
if (isFinishing()) { if (isFinishing()) {
return true; return true;
} }
// 清除设置状态
clearSettingState(); clearSettingState();
// 清空菜单
menu.clear(); menu.clear();
// 如果当前笔记是通话记录,则加载通话记录编辑菜单
if (mWorkingNote.getFolderId() == Notes.ID_CALL_RECORD_FOLDER) { if (mWorkingNote.getFolderId() == Notes.ID_CALL_RECORD_FOLDER) {
getMenuInflater().inflate(R.menu.call_note_edit, menu); getMenuInflater().inflate(R.menu.call_note_edit, menu);
// 否则加载普通编辑菜单
} else { } else {
getMenuInflater().inflate(R.menu.note_edit, menu); getMenuInflater().inflate(R.menu.note_edit, menu);
} }
// 如果当前笔记是清单模式,则将菜单项的标题设置为普通模式
if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {
menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_normal_mode); menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_normal_mode);
// 否则将菜单项的标题设置为清单模式
} else { } else {
menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_list_mode); menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_list_mode);
} }
// 如果当前笔记有闹钟提醒,则隐藏提醒菜单项
if (mWorkingNote.hasClockAlert()) { if (mWorkingNote.hasClockAlert()) {
menu.findItem(R.id.menu_alert).setVisible(false); menu.findItem(R.id.menu_alert).setVisible(false);
// 否则隐藏删除提醒菜单项
} else { } else {
menu.findItem(R.id.menu_delete_remind).setVisible(false); menu.findItem(R.id.menu_delete_remind).setVisible(false);
} }
// 返回true
return true; return true;
} }
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
// 根据菜单项的id执行相应的操作
switch (item.getItemId()) { switch (item.getItemId()) {
case R.id.menu_new_note: case R.id.menu_new_note:
// 创建新笔记
createNewNote(); createNewNote();
break; break;
case R.id.menu_delete: case R.id.menu_delete:
// 弹出删除确认对话框
AlertDialog.Builder builder = new AlertDialog.Builder(this); AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.alert_title_delete)); builder.setTitle(getString(R.string.alert_title_delete));
builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setIcon(android.R.drawable.ic_dialog_alert);
@ -678,7 +519,6 @@ public class NoteEditActivity extends Activity implements OnClickListener,
builder.setPositiveButton(android.R.string.ok, builder.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() { new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
// 删除当前笔记并关闭活动
deleteCurrentNote(); deleteCurrentNote();
finish(); finish();
} }
@ -687,30 +527,24 @@ public class NoteEditActivity extends Activity implements OnClickListener,
builder.show(); builder.show();
break; break;
case R.id.menu_font_size: case R.id.menu_font_size:
// 显示字体大小选择器
mFontSizeSelector.setVisibility(View.VISIBLE); mFontSizeSelector.setVisibility(View.VISIBLE);
findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.VISIBLE); findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.VISIBLE);
break; break;
case R.id.menu_list_mode: case R.id.menu_list_mode:
// 切换列表模式
mWorkingNote.setCheckListMode(mWorkingNote.getCheckListMode() == 0 ? mWorkingNote.setCheckListMode(mWorkingNote.getCheckListMode() == 0 ?
TextNote.MODE_CHECK_LIST : 0); TextNote.MODE_CHECK_LIST : 0);
break; break;
case R.id.menu_share: case R.id.menu_share:
// 获取当前笔记内容并分享
getWorkingText(); getWorkingText();
sendTo(this, mWorkingNote.getContent()); sendTo(this, mWorkingNote.getContent());
break; break;
case R.id.menu_send_to_desktop: case R.id.menu_send_to_desktop:
// 发送到桌面
sendToDesktop(); sendToDesktop();
break; break;
case R.id.menu_alert: case R.id.menu_alert:
// 设置提醒
setReminder(); setReminder();
break; break;
case R.id.menu_delete_remind: case R.id.menu_delete_remind:
// 删除提醒
mWorkingNote.setAlertDate(0, false); mWorkingNote.setAlertDate(0, false);
break; break;
default: default:
@ -720,17 +554,12 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
private void setReminder() { private void setReminder() {
// 创建一个DateTimePickerDialog对象参数为当前上下文和当前时间
DateTimePickerDialog d = new DateTimePickerDialog(this, System.currentTimeMillis()); DateTimePickerDialog d = new DateTimePickerDialog(this, System.currentTimeMillis());
// 设置DateTimePickerDialog的监听器
d.setOnDateTimeSetListener(new OnDateTimeSetListener() { d.setOnDateTimeSetListener(new OnDateTimeSetListener() {
// 当日期时间被设置时,调用此方法
public void OnDateTimeSet(AlertDialog dialog, long date) { public void OnDateTimeSet(AlertDialog dialog, long date) {
// 设置工作笔记的提醒日期
mWorkingNote.setAlertDate(date , true); mWorkingNote.setAlertDate(date , true);
} }
}); });
// 显示DateTimePickerDialog
d.show(); d.show();
} }
@ -738,15 +567,10 @@ public class NoteEditActivity extends Activity implements OnClickListener,
* Share note to apps that support {@link Intent#ACTION_SEND} action * Share note to apps that support {@link Intent#ACTION_SEND} action
* and {@text/plain} type * and {@text/plain} type
*/ */
// 向指定上下文发送信息
private void sendTo(Context context, String info) { private void sendTo(Context context, String info) {
// 创建一个发送意图
Intent intent = new Intent(Intent.ACTION_SEND); Intent intent = new Intent(Intent.ACTION_SEND);
// 将信息添加到意图中
intent.putExtra(Intent.EXTRA_TEXT, info); intent.putExtra(Intent.EXTRA_TEXT, info);
// 设置意图的类型为文本
intent.setType("text/plain"); intent.setType("text/plain");
// 启动意图
context.startActivity(intent); context.startActivity(intent);
} }
@ -762,44 +586,29 @@ public class NoteEditActivity extends Activity implements OnClickListener,
startActivity(intent); startActivity(intent);
} }
// 删除当前笔记
private void deleteCurrentNote() { private void deleteCurrentNote() {
// 如果当前笔记存在于数据库中
if (mWorkingNote.existInDatabase()) { if (mWorkingNote.existInDatabase()) {
// 创建一个HashSet来存储要删除的笔记的id
HashSet<Long> ids = new HashSet<Long>(); HashSet<Long> ids = new HashSet<Long>();
// 获取当前笔记的id
long id = mWorkingNote.getNoteId(); long id = mWorkingNote.getNoteId();
// 如果当前笔记的id不是根文件夹的id
if (id != Notes.ID_ROOT_FOLDER) { if (id != Notes.ID_ROOT_FOLDER) {
// 将当前笔记的id添加到HashSet中
ids.add(id); ids.add(id);
} else { } else {
// 如果当前笔记的id是根文件夹的id则打印错误日志
Log.d(TAG, "Wrong note id, should not happen"); Log.d(TAG, "Wrong note id, should not happen");
} }
// 如果当前不是同步模式
if (!isSyncMode()) { if (!isSyncMode()) {
// 批量删除笔记
if (!DataUtils.batchDeleteNotes(getContentResolver(), ids)) { if (!DataUtils.batchDeleteNotes(getContentResolver(), ids)) {
// 如果删除失败,则打印错误日志
Log.e(TAG, "Delete Note error"); Log.e(TAG, "Delete Note error");
} }
} else { } else {
// 如果是同步模式
if (!DataUtils.batchMoveToFolder(getContentResolver(), ids, Notes.ID_TRASH_FOLER)) { if (!DataUtils.batchMoveToFolder(getContentResolver(), ids, Notes.ID_TRASH_FOLER)) {
// 如果移动到垃圾桶文件夹失败,则打印错误日志
Log.e(TAG, "Move notes to trash folder error, should not happens"); Log.e(TAG, "Move notes to trash folder error, should not happens");
} }
} }
} }
// 标记当前笔记为已删除
mWorkingNote.markDeleted(true); mWorkingNote.markDeleted(true);
} }
// 判断是否为同步模式
private boolean isSyncMode() { private boolean isSyncMode() {
// 获取同步账户名称
return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0;
} }
@ -833,29 +642,22 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
} }
// 当小部件发生变化时调用
public void onWidgetChanged() { public void onWidgetChanged() {
// 更新小部件
updateWidget(); updateWidget();
} }
public void onEditTextDelete(int index, String text) { public void onEditTextDelete(int index, String text) {
// 获取EditTextList的子视图数量
int childCount = mEditTextList.getChildCount(); int childCount = mEditTextList.getChildCount();
// 如果子视图数量为1则直接返回
if (childCount == 1) { if (childCount == 1) {
return; return;
} }
// 从被删除的EditText的下一个开始依次将每个EditText的索引减1
for (int i = index + 1; i < childCount; i++) { for (int i = index + 1; i < childCount; i++) {
((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text)) ((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text))
.setIndex(i - 1); .setIndex(i - 1);
} }
// 从EditTextList中移除被删除的EditText
mEditTextList.removeViewAt(index); mEditTextList.removeViewAt(index);
// 获取被删除的EditText的前一个EditText
NoteEditText edit = null; NoteEditText edit = null;
if(index == 0) { if(index == 0) {
edit = (NoteEditText) mEditTextList.getChildAt(0).findViewById( edit = (NoteEditText) mEditTextList.getChildAt(0).findViewById(
@ -864,13 +666,9 @@ public class NoteEditActivity extends Activity implements OnClickListener,
edit = (NoteEditText) mEditTextList.getChildAt(index - 1).findViewById( edit = (NoteEditText) mEditTextList.getChildAt(index - 1).findViewById(
R.id.et_edit_text); R.id.et_edit_text);
} }
// 获取被删除的EditText的长度
int length = edit.length(); int length = edit.length();
// 将被删除的EditText的内容追加到前一个EditText中
edit.append(text); edit.append(text);
// 将焦点设置到前一个EditText中
edit.requestFocus(); edit.requestFocus();
// 将光标设置到前一个EditText的末尾
edit.setSelection(length); edit.setSelection(length);
} }
@ -878,190 +676,119 @@ public class NoteEditActivity extends Activity implements OnClickListener,
/** /**
* Should not happen, check for debug * Should not happen, check for debug
*/ */
// 如果index大于mEditTextList的子元素数量则输出错误日志
if(index > mEditTextList.getChildCount()) { if(index > mEditTextList.getChildCount()) {
Log.e(TAG, "Index out of mEditTextList boundrary, should not happen"); Log.e(TAG, "Index out of mEditTextList boundrary, should not happen");
} }
// 获取列表项
View view = getListItem(text, index); View view = getListItem(text, index);
// 将列表项添加到mEditTextList中
mEditTextList.addView(view, index); mEditTextList.addView(view, index);
// 获取NoteEditText
NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text);
// 设置焦点
edit.requestFocus(); edit.requestFocus();
// 设置光标位置
edit.setSelection(0); edit.setSelection(0);
// 遍历mEditTextList中的子元素从index+1开始
for (int i = index + 1; i < mEditTextList.getChildCount(); i++) { for (int i = index + 1; i < mEditTextList.getChildCount(); i++) {
// 设置NoteEditText的索引
((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text)) ((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text))
.setIndex(i); .setIndex(i);
} }
} }
// 切换到列表模式
private void switchToListMode(String text) { private void switchToListMode(String text) {
// 移除所有视图
mEditTextList.removeAllViews(); mEditTextList.removeAllViews();
// 将文本按行分割
String[] items = text.split("\n"); String[] items = text.split("\n");
// 初始化索引
int index = 0; int index = 0;
// 遍历每一行
for (String item : items) { for (String item : items) {
// 如果行不为空
if(!TextUtils.isEmpty(item)) { if(!TextUtils.isEmpty(item)) {
// 添加列表项
mEditTextList.addView(getListItem(item, index)); mEditTextList.addView(getListItem(item, index));
// 索引自增
index++; index++;
} }
} }
// 添加一个空列表项
mEditTextList.addView(getListItem("", index)); mEditTextList.addView(getListItem("", index));
// 获取最后一个列表项的EditText并请求焦点
mEditTextList.getChildAt(index).findViewById(R.id.et_edit_text).requestFocus(); mEditTextList.getChildAt(index).findViewById(R.id.et_edit_text).requestFocus();
// 隐藏NoteEditor
mNoteEditor.setVisibility(View.GONE); mNoteEditor.setVisibility(View.GONE);
// 显示EditTextList
mEditTextList.setVisibility(View.VISIBLE); mEditTextList.setVisibility(View.VISIBLE);
} }
// 根据用户查询结果高亮显示全文
private Spannable getHighlightQueryResult(String fullText, String userQuery) { private Spannable getHighlightQueryResult(String fullText, String userQuery) {
// 创建一个SpannableString对象用于存储高亮显示的文本
SpannableString spannable = new SpannableString(fullText == null ? "" : fullText); SpannableString spannable = new SpannableString(fullText == null ? "" : fullText);
// 如果用户查询结果不为空
if (!TextUtils.isEmpty(userQuery)) { if (!TextUtils.isEmpty(userQuery)) {
// 创建一个正则表达式对象,用于匹配用户查询结果
mPattern = Pattern.compile(userQuery); mPattern = Pattern.compile(userQuery);
// 创建一个Matcher对象用于匹配全文
Matcher m = mPattern.matcher(fullText); Matcher m = mPattern.matcher(fullText);
// 定义一个起始位置
int start = 0; int start = 0;
// 循环匹配全文
while (m.find(start)) { while (m.find(start)) {
// 设置高亮显示的背景颜色
spannable.setSpan( spannable.setSpan(
new BackgroundColorSpan(this.getResources().getColor( new BackgroundColorSpan(this.getResources().getColor(
R.color.user_query_highlight)), m.start(), m.end(), R.color.user_query_highlight)), m.start(), m.end(),
Spannable.SPAN_INCLUSIVE_EXCLUSIVE); Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
// 更新起始位置
start = m.end(); start = m.end();
} }
} }
// 返回高亮显示的文本
return spannable; return spannable;
} }
// 根据传入的item和index获取一个View
private View getListItem(String item, int index) { private View getListItem(String item, int index) {
// 通过LayoutInflater加载布局文件
View view = LayoutInflater.from(this).inflate(R.layout.note_edit_list_item, null); View view = LayoutInflater.from(this).inflate(R.layout.note_edit_list_item, null);
// 获取EditText
final NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); final NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text);
// 设置EditText的文本样式
edit.setTextAppearance(this, TextAppearanceResources.getTexAppearanceResource(mFontSizeId)); edit.setTextAppearance(this, TextAppearanceResources.getTexAppearanceResource(mFontSizeId));
// 获取CheckBox
CheckBox cb = ((CheckBox) view.findViewById(R.id.cb_edit_item)); CheckBox cb = ((CheckBox) view.findViewById(R.id.cb_edit_item));
// 设置CheckBox的监听器
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() { cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// 如果CheckBox被选中
if (isChecked) { if (isChecked) {
// 设置EditText的画笔标志添加删除线
edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
} else { } else {
// 设置EditText的画笔标志取消删除线
edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG); edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
} }
} }
}); });
// 如果item以TAG_CHECKED开头
if (item.startsWith(TAG_CHECKED)) { if (item.startsWith(TAG_CHECKED)) {
// 设置CheckBox为选中状态
cb.setChecked(true); cb.setChecked(true);
// 设置EditText的画笔标志添加删除线
edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
// 去掉TAG_CHECKED
item = item.substring(TAG_CHECKED.length(), item.length()).trim(); item = item.substring(TAG_CHECKED.length(), item.length()).trim();
// 如果item以TAG_UNCHECKED开头
} else if (item.startsWith(TAG_UNCHECKED)) { } else if (item.startsWith(TAG_UNCHECKED)) {
// 设置CheckBox为未选中状态
cb.setChecked(false); cb.setChecked(false);
// 设置EditText的画笔标志取消删除线
edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG); edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
// 去掉TAG_UNCHECKED
item = item.substring(TAG_UNCHECKED.length(), item.length()).trim(); item = item.substring(TAG_UNCHECKED.length(), item.length()).trim();
} }
// 设置EditText的监听器
edit.setOnTextViewChangeListener(this); edit.setOnTextViewChangeListener(this);
// 设置EditText的索引
edit.setIndex(index); edit.setIndex(index);
// 设置EditText的文本
edit.setText(getHighlightQueryResult(item, mUserQuery)); edit.setText(getHighlightQueryResult(item, mUserQuery));
return view; return view;
} }
// 当EditText的文本发生变化时调用
public void onTextChange(int index, boolean hasText) { public void onTextChange(int index, boolean hasText) {
// 如果索引超出范围
if (index >= mEditTextList.getChildCount()) { if (index >= mEditTextList.getChildCount()) {
Log.e(TAG, "Wrong index, should not happen"); Log.e(TAG, "Wrong index, should not happen");
return; return;
} }
// 如果有文本
if(hasText) { if(hasText) {
// 设置CheckBox为可见
mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.VISIBLE); mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.VISIBLE);
// 如果没有文本
} else { } else {
// 设置CheckBox为不可见
mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.GONE); mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.GONE);
} }
} }
public void onCheckListModeChanged(int oldMode, int newMode) { public void onCheckListModeChanged(int oldMode, int newMode) {
// 如果新模式是检查列表模式
if (newMode == TextNote.MODE_CHECK_LIST) { if (newMode == TextNote.MODE_CHECK_LIST) {
// 切换到列表模式
switchToListMode(mNoteEditor.getText().toString()); switchToListMode(mNoteEditor.getText().toString());
} else { } else {
// 如果没有获取到工作文本
if (!getWorkingText()) { if (!getWorkingText()) {
mWorkingNote.setWorkingText(mWorkingNote.getContent().replace(TAG_UNCHECKED + " ",
// 将工作笔记的内容中的未选中标签替换为空字符串
mWorkingNote.setWorkingText(mWorkingNote.getContent().replace(TAG_UNCHECKED + " ", ""));
"")); ""));
} }
// 设置笔记编辑器的内容为高亮查询结果
mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery)); mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery));
// 隐藏文本编辑器列表
mEditTextList.setVisibility(View.GONE); mEditTextList.setVisibility(View.GONE);
// 显示笔记编辑器
mNoteEditor.setVisibility(View.VISIBLE); mNoteEditor.setVisibility(View.VISIBLE);
} }
} }
// 获取工作文本
private boolean getWorkingText() { private boolean getWorkingText() {
boolean hasChecked = false; boolean hasChecked = false;
// 如果工作笔记的检查列表模式为检查列表模式
if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {
// 创建一个StringBuilder对象
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
// 遍历EditTextList的子视图
for (int i = 0; i < mEditTextList.getChildCount(); i++) { for (int i = 0; i < mEditTextList.getChildCount(); i++) {
// 获取子视图
View view = mEditTextList.getChildAt(i); View view = mEditTextList.getChildAt(i);
// 获取NoteEditText对象
NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text);
// 如果EditText的内容不为空
if (!TextUtils.isEmpty(edit.getText())) { if (!TextUtils.isEmpty(edit.getText())) {
if (((CheckBox) view.findViewById(R.id.cb_edit_item)).isChecked()) { if (((CheckBox) view.findViewById(R.id.cb_edit_item)).isChecked()) {
sb.append(TAG_CHECKED).append(" ").append(edit.getText()).append("\n"); sb.append(TAG_CHECKED).append(" ").append(edit.getText()).append("\n");
@ -1079,11 +806,8 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
private boolean saveNote() { private boolean saveNote() {
// 获取当前工作文本
getWorkingText(); getWorkingText();
// 保存当前笔记
boolean saved = mWorkingNote.saveNote(); boolean saved = mWorkingNote.saveNote();
// 如果保存成功
if (saved) { if (saved) {
/** /**
* There are two modes from List view to edit view, open one note, * There are two modes from List view to edit view, open one note,
@ -1094,7 +818,6 @@ public class NoteEditActivity extends Activity implements OnClickListener,
*/ */
setResult(RESULT_OK); setResult(RESULT_OK);
} }
// 返回保存结果
return saved; return saved;
} }
@ -1133,26 +856,18 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
} }
// 根据传入的content去除TAG_CHECKED和TAG_UNCHECKED标签并返回处理后的字符串
private String makeShortcutIconTitle(String content) { private String makeShortcutIconTitle(String content) {
// 去除TAG_CHECKED标签
content = content.replace(TAG_CHECKED, ""); content = content.replace(TAG_CHECKED, "");
// 去除TAG_UNCHECKED标签
content = content.replace(TAG_UNCHECKED, ""); content = content.replace(TAG_UNCHECKED, "");
// 如果处理后的字符串长度大于SHORTCUT_ICON_TITLE_MAX_LEN则截取前SHORTCUT_ICON_TITLE_MAX_LEN个字符
return content.length() > SHORTCUT_ICON_TITLE_MAX_LEN ? content.substring(0, return content.length() > SHORTCUT_ICON_TITLE_MAX_LEN ? content.substring(0,
SHORTCUT_ICON_TITLE_MAX_LEN) : content; SHORTCUT_ICON_TITLE_MAX_LEN) : content;
} }
// 显示Toast使用默认时长
private void showToast(int resId) { private void showToast(int resId) {
// 调用showToast方法传入resId和默认时长
showToast(resId, Toast.LENGTH_SHORT); showToast(resId, Toast.LENGTH_SHORT);
} }
// 显示Toast使用指定时长
private void showToast(int resId, int duration) { private void showToast(int resId, int duration) {
// 使用Toast.makeText方法创建Toast对象并显示
Toast.makeText(this, resId, duration).show(); Toast.makeText(this, resId, duration).show();
} }
} }

@ -100,30 +100,18 @@ public class NotesListItem extends LinearLayout {
} }
private void setBackground(NoteItemData data) { private void setBackground(NoteItemData data) {
// 获取背景颜色ID
int id = data.getBgColorId(); int id = data.getBgColorId();
// 判断类型
if (data.getType() == Notes.TYPE_NOTE) { if (data.getType() == Notes.TYPE_NOTE) {
// 判断是否为单条笔记
if (data.isSingle() || data.isOneFollowingFolder()) { if (data.isSingle() || data.isOneFollowingFolder()) {
// 设置背景资源为单条笔记背景
setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id)); setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id));
// 判断是否为最后一条笔记
} else if (data.isLast()) { } else if (data.isLast()) {
// 设置背景资源为最后一条笔记背景
setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id)); setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id));
// 判断是否为第一条笔记或多个文件夹
} else if (data.isFirst() || data.isMultiFollowingFolder()) { } else if (data.isFirst() || data.isMultiFollowingFolder()) {
// 设置背景资源为第一条笔记背景
setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id)); setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id));
// 其他情况
} else { } else {
// 设置背景资源为普通笔记背景
setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id)); setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id));
} }
// 如果为文件夹
} else { } else {
// 设置背景资源为文件夹背景
setBackgroundResource(NoteItemBgResources.getFolderBgRes()); setBackgroundResource(NoteItemBgResources.getFolderBgRes());
} }
} }

@ -1,100 +0,0 @@
package net.micode.notes.data; // 定义包名
import android.content.ContentUris; // 用于操作URI如添加ID到URI中
import android.net.Uri; // 用于表示URI的类
// Notes 类定义了与便签应用相关的常量包括URI、类型、ID等
public class Notes {
public static final String AUTHORITY = "micode_notes"; // 内容提供者的权限标识
public static final String TAG = "Notes"; // 日志标签
// 定义笔记、文件夹和系统类型的常量
public static final int TYPE_NOTE = 0; // 笔记类型
public static final int TYPE_FOLDER = 1; // 文件夹类型
public static final int TYPE_SYSTEM = 2; // 系统类型
// 系统文件夹的ID常量
public static final int ID_ROOT_FOLDER = 0; // 根文件夹ID
public static final int ID_TEMPARAY_FOLDER = -1; // 临时文件夹ID
public static final int ID_CALL_RECORD_FOLDER = -2; // 电话记录文件夹ID
public static final int ID_TRASH_FOLER = -3; // 垃圾桶文件夹ID
// 意图Intent中使用的额外数据键
public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date"; // 警告日期
public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id"; // 背景颜色ID
public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id"; // 小部件ID
public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type"; // 小部件类型
public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id"; // 文件夹ID
public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date"; // 电话日期
// 小部件类型的常量
public static final int TYPE_WIDGET_INVALIDE = -1; // 无效的小部件类型
public static final int TYPE_WIDGET_2X = 0; // 2x2小部件
public static final int TYPE_WIDGET_4X = 1; // 4x4小部件
// 数据常量类包含笔记和电话记录的MIME类型
public static class DataConstants {
public static final String NOTE = TextNote.CONTENT_ITEM_TYPE; // 文本笔记MIME类型
public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE; // 电话记录MIME类型
}
// 查询所有笔记和文件夹的URI
public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note");
// 查询数据的URI
public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data");
// NoteColumns接口定义了笔记相关字段
public interface NoteColumns {
public static final String ID = "_id"; // 唯一ID
public static final String PARENT_ID = "parent_id"; // 父ID用于文件夹结构
public static final String CREATED_DATE = "created_date"; // 创建日期
public static final String MODIFIED_DATE = "modified_date"; // 修改日期
public static final String ALERTED_DATE = "alert_date"; // 警告日期
public static final String SNIPPET = "snippet"; // 文件夹名或笔记内容摘要
public static final String WIDGET_ID = "widget_id"; // 小部件ID
public static final String WIDGET_TYPE = "widget_type"; // 小部件类型
public static final String BG_COLOR_ID = "bg_color_id"; // 背景颜色ID
public static final String HAS_ATTACHMENT = "has_attachment"; // 是否有附件
public static final String NOTES_COUNT = "notes_count"; // 文件夹中的笔记数量
public static final String TYPE = "type"; // 类型(笔记或文件夹)
public static final String SYNC_ID = "sync_id"; // 同步ID
public static final String LOCAL_MODIFIED = "local_modified"; // 本地修改标志
public static final String ORIGIN_PARENT_ID = "origin_parent_id"; // 原始父ID
public static final String GTASK_ID = "gtask_id"; // Google任务ID
public static final String VERSION = "version"; // 版本号
}
// DataColumns接口定义了数据表相关字段
public interface DataColumns {
public static final String ID = "_id"; // 唯一ID
public static final String MIME_TYPE = "mime_type"; // MIME类型
public static final String NOTE_ID = "note_id"; // 对应的笔记ID
public static final String CREATED_DATE = "created_date"; // 创建日期
public static final String MODIFIED_DATE = "modified_date"; // 修改日期
public static final String CONTENT = "content"; // 数据内容
public static final String DATA1 = "data1"; // 通用数据列1
public static final String DATA2 = "data2"; // 通用数据列2
public static final String DATA3 = "data3"; // 通用数据列3
public static final String DATA4 = "data4"; // 通用数据列4
public static final String DATA5 = "data5"; // 通用数据列5
}
// TextNote类定义了文本笔记相关的常量
public static final class TextNote implements DataColumns {
public static final String MODE = DATA1; // 模式,检查列表模式或普通模式
public static final int MODE_CHECK_LIST = 1; // 检查列表模式值
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note"; // 目录MIME类型
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note"; // 项目MIME类型
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note"); // 文本笔记URI
}
// CallNote类定义了电话记录相关的常量
public static final class CallNote implements DataColumns {
public static final String CALL_DATE = DATA1; // 电话日期
public static final String PHONE_NUMBER = DATA3; // 电话号码
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note"; // 目录MIME类型
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note"; // 项目MIME类型
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note"); // 电话记录URI
}
}

@ -1,323 +0,0 @@
package net.micode.notes.data; // 定义包名
import android.app.SearchManager; // 搜索管理器,用于处理搜索建议等
import android.content.ContentProvider; // Android内容提供者基类
import android.content.ContentUris; // 用于操作URI如添加ID到URI中
import android.content.ContentValues; // 用于存储数据的键值对,便于数据库操作
import android.content.Intent; // 用于应用程序之间传递数据的意图
import android.content.UriMatcher; // 用于匹配URI
import android.database.Cursor; // 用于数据库查询结果集的迭代
import android.database.sqlite.SQLiteDatabase; // 用于执行SQL语句和进行数据库操作
import android.net.Uri; // 用于表示URI的类
import android.text.TextUtils; // 文本操作工具类
import android.util.Log; // 用于日志输出
import net.micode.notes.R; // 资源类
import net.micode.notes.data.Notes.DataColumns; // 数据表列常量
import net.micode.notes.data.Notes.NoteColumns; // 笔记表列常量
import net.micode.notes.data.NotesDatabaseHelper.TABLE; // 数据表名称常量
// NotesProvider类继承自ContentProvider用于提供数据共享接口
public class NotesProvider extends ContentProvider {
// UriMatcher用于匹配URI
private static final UriMatcher mMatcher;
private NotesDatabaseHelper mHelper; // 数据库帮助类实例
private static final String TAG = "NotesProvider"; // 日志标签
// 定义匹配URI的常量
private static final int URI_NOTE = 1;//用于标识笔记资源
private static final int URI_NOTE_ITEM = 2;//用于标识单个笔记资源
private static final int URI_DATA = 3;//用于标识数据资源
private static final int URI_DATA_ITEM = 4;//用于标识单个数据资源
private static final int URI_SEARCH = 5;//搜索功能
private static final int URI_SEARCH_SUGGEST = 6;//用于标识搜索功能
static {
// 创建UriMatcher时调用UriMatcher(UriMatcher.NO_MATCH)表示不匹配任何路径的返回码
mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
// 把需要匹配URI路径全部给注册上
mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE);//笔记表
mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM);//笔记表中的某条记录
mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA);//数据表
mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM);//数据表中的某条数据
mMatcher.addURI(Notes.AUTHORITY, "search", URI_SEARCH);//搜索
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, URI_SEARCH_SUGGEST);//搜索建议
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST);//搜索建议
}
// 声明搜索结果的投影
private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + ","//笔记ID
+ NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + ","//意图数据
+ "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_1 + ","//笔记摘要
+ "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_2 + ","//
+ R.drawable.search_result + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1 + ","//搜索结构图标
+ "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + ","//意图动作
+ "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA;//意图数据类型
// 声明搜索查询
private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION//查询语句
+ " FROM " + TABLE.NOTE//表名
+ " WHERE " + NoteColumns.SNIPPET + " LIKE ?"//查询条件
+ " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER//排除回收站
+ " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE;//笔记类型
@Override
// Context只有在onCreate()中才被初始化对mHelper进行实例化
public boolean onCreate() {
mHelper = NotesDatabaseHelper.getInstance(getContext());
return true;
}
@Override
// 查询uri在数据库中对应的位置
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
Cursor c = null;
// 获取可读数据库
SQLiteDatabase db = mHelper.getReadableDatabase();
String id = null;
// 匹配查找uri
switch (mMatcher.match(uri)) {
// 对于不同的匹配值,在数据库中查找相应的条目
case URI_NOTE:
c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null,
sortOrder);
break;
case URI_NOTE_ITEM:
id = uri.getPathSegments().get(1);
c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder);
break;
case URI_DATA:
c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null,
sortOrder);
break;
case URI_DATA_ITEM:
id = uri.getPathSegments().get(1);
c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder);
break;
case URI_SEARCH:
case URI_SEARCH_SUGGEST:
if (sortOrder != null || projection != null) {
// 不合法的参数异常
throw new IllegalArgumentException(
"do not specify sortOrder, selection, selectionArgs, or projection" + "with this query");
}
String searchString = null;
if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) {
if (uri.getPathSegments().size() > 1) {
// getPathSegments()方法得到一个String的List
// 在uri.getPathSegments().get(1)为第2个元素
searchString = uri.getPathSegments().get(1);
}
} else {
searchString = uri.getQueryParameter("pattern");
}
if (TextUtils.isEmpty(searchString)) {
return null;
}
try {
searchString = String.format("%%%s%%", searchString);
c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY,
new String[] { searchString });
} catch (IllegalStateException ex) {
Log.e(TAG, "got exception: " + ex.toString());
}
break;
default:
// 抛出异常
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (c != null) {
c.setNotificationUri(getContext().getContentResolver(), uri);
}
return c;
}
@Override
// 插入一个uri
public Uri insert(Uri uri, ContentValues values) {
// 获得可写的数据库
SQLiteDatabase db = mHelper.getWritableDatabase();
long dataId = 0, noteId = 0, insertedId = 0;
switch (mMatcher.match(uri)) {
// 新增一个条目
case URI_NOTE:
insertedId = noteId = db.insert(TABLE.NOTE, null, values);
break;
// 如果存在查找NOTE_ID
case URI_DATA:
if (values.containsKey(DataColumns.NOTE_ID)) {
noteId = values.getAsLong(DataColumns.NOTE_ID);
} else {
Log.d(TAG, "Wrong data format without note id:" + values.toString());
}
insertedId = dataId = db.insert(TABLE.DATA, null, values);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
// Notify the note uri
// notifyChange获得一个ContextResolver对象并且更新里面的内容
if (noteId > 0) {
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null);
}
// Notify the data uri
if (dataId > 0) {
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null);
}
// 返回插入的uri的路径
return ContentUris.withAppendedId(uri, insertedId);
}
@Override
// 删除一个uri
public int delete(Uri uri, String selection, String[] selectionArgs) {
// Uri代表要操作的数据Android上可用的每种资源 -包括 图像、视频片段、音频资源等都可以用Uri来表示。
int count = 0;
String id = null;
// 获得可写的数据库
SQLiteDatabase db = mHelper.getWritableDatabase();
boolean deleteData = false;
switch (mMatcher.match(uri)) {
case URI_NOTE:
selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 ";
count = db.delete(TABLE.NOTE, selection, selectionArgs);
break;
case URI_NOTE_ITEM:
id = uri.getPathSegments().get(1);
/**
* ID that smaller than 0 is system folder which is not allowed to
* trash
*/
long noteId = Long.valueOf(id);
if (noteId <= 0) {
break;
}
count = db.delete(TABLE.NOTE,
NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
break;
case URI_DATA:
count = db.delete(TABLE.DATA, selection, selectionArgs);
deleteData = true;
break;
case URI_DATA_ITEM:
id = uri.getPathSegments().get(1);
count = db.delete(TABLE.DATA,
DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
deleteData = true;
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (count > 0) {
if (deleteData) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
}
getContext().getContentResolver().notifyChange(uri, null);
}
return count;
}
@Override
// 更新一个uri
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int count = 0; // 记录更新的行数
String id = null; // 用于存储URI中的ID部分
SQLiteDatabase db = mHelper.getWritableDatabase(); // 获取可写的数据库实例
boolean updateData = false; // 标记是否需要更新数据表
// 根据URI匹配不同的操作
switch (mMatcher.match(uri)) {
case URI_NOTE:
// 更新笔记表中的多条记录
increaseNoteVersion(-1, selection, selectionArgs); // 增加笔记版本号
count = db.update(TABLE.NOTE, values, selection, selectionArgs); // 执行更新操作
break;
case URI_NOTE_ITEM:
// 更新笔记表中的单条记录
id = uri.getPathSegments().get(1); // 从URI中获取ID
increaseNoteVersion(Long.valueOf(id), selection, selectionArgs); // 增加指定笔记的版本号
count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs); // 执行更新操作
break;
case URI_DATA:
// 更新数据表中的多条记录
count = db.update(TABLE.DATA, values, selection, selectionArgs); // 执行更新操作
updateData = true; // 设置更新数据表的标记为true
break;
case URI_DATA_ITEM:
// 更新数据表中的单条记录
id = uri.getPathSegments().get(1); // 从URI中获取ID
count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs); // 执行更新操作
updateData = true; // 设置更新数据表的标记为true
break;
default:
// 如果URI不匹配任何已知类型则抛出异常
throw new IllegalArgumentException("Unknown URI " + uri);
}
// 如果有行被更新则通知相关URI的监听器
if (count > 0) {
if (updateData) {
// 如果更新了数据表则通知笔记表的URI
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
}
// 通知当前URI的监听器
getContext().getContentResolver().notifyChange(uri, null);
}
return count; // 返回更新的行数
}
/// 将字符串解析成规定格式
private String parseSelection(String selection) {
// 如果传入的选择字符串不为空,则在 selection 前后添加 " AND (" 和 ")",否则返回空字符串
return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
}
// 增加一个noteVersion
private void increaseNoteVersion(long id, String selection, String[] selectionArgs) {
// 创建StringBuilder对象用于构建SQL语句
StringBuilder sql = new StringBuilder(120);
sql.append("UPDATE "); // 添加UPDATE关键字
sql.append(TABLE.NOTE); // 添加表名NOTE
sql.append(" SET "); // 添加SET关键字
sql.append(NoteColumns.VERSION); // 添加版本号列名
sql.append("=" + NoteColumns.VERSION + "+1 "); // 版本号列值加1
// 如果ID大于0或者选择字符串不为空则添加WHERE关键字
if (id > 0 || !TextUtils.isEmpty(selection)) {
sql.append(" WHERE ");
}
// 如果ID大于0则添加ID等于指定值的条件
if (id > 0) {
sql.append(NoteColumns.ID + "=" + String.valueOf(id));
}
// 如果选择字符串不为空,则添加解析后的选择字符串作为条件
if (!TextUtils.isEmpty(selection)) {
String selectString = id > 0 ? parseSelection(selection) : selection;
// 将选择字符串中的占位符替换为实际的参数值
for (String args : selectionArgs) {
selectString = selectString.replaceFirst("\\?", args);
}
sql.append(selectString);
}
// 使用execSQL方法执行构建的SQL语句
mHelper.getWritableDatabase().execSQL(sql.toString());
}
@Override
public String getType(Uri uri) {
// TODO: 需要实现该方法来返回给定URI的MIME类型暂时返回null
return null;
}
Loading…
Cancel
Save