Compare commits

..

No commits in common. '655e5971036426a31b2d242efc4b292d5bf65f89' and 'eb7ac8e7f43d4ea788fac2d963955829f8bea30f' have entirely different histories.

3
.idea/.gitignore vendored

@ -1,3 +0,0 @@
# Default ignored files
/shelf/
/workspace.xml

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/class_16.iml" filepath="$PROJECT_DIR$/class_16.iml" />
</modules>
</component>
</project>

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

Binary file not shown.

@ -1,24 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<config>
<source_groups>
<source_group_cea3fbad-c603-4bb6-903f-3c088d0b778a>
<java_standard>15</java_standard>
<name>Java Source Group</name>
<source_extensions>
<source_extension>.java</source_extension>
</source_extensions>
<source_paths>
<source_path>data</source_path>
<source_path>gtask</source_path>
<source_path>model</source_path>
<source_path>tool</source_path>
<source_path>ui</source_path>
<source_path>widget</source_path>
</source_paths>
<status>enabled</status>
<type>Java Source Group</type>
<use_jre_system_library>1</use_jre_system_library>
</source_group_cea3fbad-c603-4bb6-903f-3c088d0b778a>
</source_groups>
<version>8</version>
</config>

@ -1,21 +1,43 @@
/*
* 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.model; package net.micode.notes.model;
import android.content.ContentProviderOperation;
import android.content.ContentProviderOperation;//批量的更新、插入、删除数据。 import android.content.ContentProviderResult;
import android.content.ContentProviderResult;//操作的结果 import android.content.ContentUris;
import android.content.ContentUris;//用于添加和获取Uri后面的ID import android.content.ContentValues;
import android.content.ContentValues;//一种用来存储基本数据类型数据的存储机制 import android.content.Context;
import android.content.Context;//需要用该类来弄清楚调用者的实例 import android.content.OperationApplicationException;
import android.content.OperationApplicationException;//操作应用程序容错 import android.net.Uri;
import android.net.Uri;//表示待操作的数据 import android.os.RemoteException;
import android.os.RemoteException;//远程容错 import android.util.Log;
import android.util.Log;//输出日志,比如说出错、警告等
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.CallNote;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.Notes.TextNote;
import java.util.ArrayList;
public class Note { public class Note {
// private ContentValues mNoteDiffValues; private ContentValues mNoteDiffValues;
ContentValues mNoteDiffValues;//
private NoteData mNoteData; private NoteData mNoteData;
private static final String TAG = "Note"; private static final String TAG = "Note";
/** /**
* Create a new note id for adding a new note to databases * Create a new note id for adding a new note to databases
*/ */
@ -27,67 +49,66 @@ public class Note {
values.put(NoteColumns.MODIFIED_DATE, createdTime); values.put(NoteColumns.MODIFIED_DATE, createdTime);
values.put(NoteColumns.TYPE, Notes.TYPE_NOTE); values.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
values.put(NoteColumns.LOCAL_MODIFIED, 1); values.put(NoteColumns.LOCAL_MODIFIED, 1);
values.put(NoteColumns.PARENT_ID, folderId);//将数据写入数据库表格 values.put(NoteColumns.PARENT_ID, folderId);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values); Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values);
//ContentResolver()主要是实现外部应用对ContentProvider中的数据
//进行添加、删除、修改和查询操作
long noteId = 0; long noteId = 0;
try { try {
noteId = Long.valueOf(uri.getPathSegments().get(1)); noteId = Long.valueOf(uri.getPathSegments().get(1));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e.toString()); Log.e(TAG, "Get note id error :" + e.toString());
noteId = 0; noteId = 0;
}//try-catch异常处理 }
if (noteId == -1) { if (noteId == -1) {
throw new IllegalStateException("Wrong note id:" + noteId); throw new IllegalStateException("Wrong note id:" + noteId);
} }
return noteId; return noteId;
} }
public Note() { public Note() {
mNoteDiffValues = new ContentValues(); mNoteDiffValues = new ContentValues();
mNoteData = new NoteData(); mNoteData = new NoteData();
}//定义两个变量用来存储便签的数据,一个是存储便签属性、一个是存储便签内容 }
public void setNoteValue(String key, String value) { public void setNoteValue(String key, String value) {
mNoteDiffValues.put(key, value); mNoteDiffValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}//设置数据库表格的标签属性数据 }
public void setTextData(String key, String value) { public void setTextData(String key, String value) {
mNoteData.setTextData(key, value); mNoteData.setTextData(key, value);
}//设置数据库表格的标签文本内容的数据 }
public void setTextDataId(long id) { public void setTextDataId(long id) {
mNoteData.setTextDataId(id); mNoteData.setTextDataId(id);
}//设置文本数据的ID }
public long getTextDataId() { public long getTextDataId() {
return mNoteData.mTextDataId; return mNoteData.mTextDataId;
}//得到文本数据的ID }
public void setCallDataId(long id) { public void setCallDataId(long id) {
mNoteData.setCallDataId(id); mNoteData.setCallDataId(id);
}//设置电话号码数据的ID }
public void setCallData(String key, String value) { public void setCallData(String key, String value) {
mNoteData.setCallData(key, value); mNoteData.setCallData(key, value);
}//得到电话号码数据的ID }
public boolean isLocalModified() { public boolean isLocalModified() {
return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified(); return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified();
}//判断是否是本地修改 }
public boolean syncNote(Context context, long noteId) { public boolean syncNote(Context context, long noteId) {
if (noteId <= 0) { if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId); throw new IllegalArgumentException("Wrong note id:" + noteId);
} }
if (!isLocalModified()) { if (!isLocalModified()) {
return true; return true;
} }
/** /**
* In theory, once data changed, the note should be updated on {@link NoteColumns#LOCAL_MODIFIED} and * In theory, once data changed, the note should be updated on {@link NoteColumns#LOCAL_MODIFIED} and
* {@link NoteColumns#MODIFIED_DATE}. For data safety, though update note fails, we also update the * {@link NoteColumns#MODIFIED_DATE}. For data safety, though update note fails, we also update the
@ -100,74 +121,74 @@ public class Note {
// Do not return, fall through // Do not return, fall through
} }
mNoteDiffValues.clear(); mNoteDiffValues.clear();
if (mNoteData.isLocalModified() if (mNoteData.isLocalModified()
&& (mNoteData.pushIntoContentResolver(context, noteId) == null)) { && (mNoteData.pushIntoContentResolver(context, noteId) == null)) {
return false; return false;
} }
return true; return true;
}//判断数据是否同步 }
private class NoteData {//定义一个基本的便签内容的数据类,主要包含文本数据和电话号码数据 private class NoteData {
private long mTextDataId; private long mTextDataId;
private ContentValues mTextDataValues;//文本数据 private ContentValues mTextDataValues;
private long mCallDataId; private long mCallDataId;
private ContentValues mCallDataValues;//电话号码数据 private ContentValues mCallDataValues;
private static final String TAG = "NoteData"; private static final String TAG = "NoteData";
public NoteData() { public NoteData() {
mTextDataValues = new ContentValues(); mTextDataValues = new ContentValues();
mCallDataValues = new ContentValues(); mCallDataValues = new ContentValues();
mTextDataId = 0; mTextDataId = 0;
mCallDataId = 0; mCallDataId = 0;
} }
//下面是上述几个函数的具体实现
boolean isLocalModified() { boolean isLocalModified() {
return mTextDataValues.size() > 0 || mCallDataValues.size() > 0; return mTextDataValues.size() > 0 || mCallDataValues.size() > 0;
} }
void setTextDataId(long id) { void setTextDataId(long id) {
if(id <= 0) { if(id <= 0) {
throw new IllegalArgumentException("Text data id should larger than 0"); throw new IllegalArgumentException("Text data id should larger than 0");
} }
mTextDataId = id; mTextDataId = id;
} }
void setCallDataId(long id) { void setCallDataId(long id) {
if (id <= 0) { if (id <= 0) {
throw new IllegalArgumentException("Call data id should larger than 0"); throw new IllegalArgumentException("Call data id should larger than 0");
} }
mCallDataId = id; mCallDataId = id;
} }
void setCallData(String key, String value) { void setCallData(String key, String value) {
mCallDataValues.put(key, value); mCallDataValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
} }
void setTextData(String key, String value) { void setTextData(String key, String value) {
mTextDataValues.put(key, value); mTextDataValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
} }
//下面函数的作用是将新的数据通过Uri的操作存储到数据库
Uri pushIntoContentResolver(Context context, long noteId) { Uri pushIntoContentResolver(Context context, long noteId) {
/** /**
* Check for safety * Check for safety
*/ */
if (noteId <= 0) { if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId); throw new IllegalArgumentException("Wrong note id:" + noteId);
}//判断数据是否合法 }
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
ContentProviderOperation.Builder builder = null;//数据库的操作列表 ContentProviderOperation.Builder builder = null;
if(mTextDataValues.size() > 0) { if(mTextDataValues.size() > 0) {
mTextDataValues.put(DataColumns.NOTE_ID, noteId); mTextDataValues.put(DataColumns.NOTE_ID, noteId);
if (mTextDataId == 0) { if (mTextDataId == 0) {
@ -188,8 +209,8 @@ public class Note {
operationList.add(builder.build()); operationList.add(builder.build());
} }
mTextDataValues.clear(); mTextDataValues.clear();
}//把文本数据存入DataColumns }
if(mCallDataValues.size() > 0) { if(mCallDataValues.size() > 0) {
mCallDataValues.put(DataColumns.NOTE_ID, noteId); mCallDataValues.put(DataColumns.NOTE_ID, noteId);
if (mCallDataId == 0) { if (mCallDataId == 0) {
@ -210,8 +231,8 @@ public class Note {
operationList.add(builder.build()); operationList.add(builder.build());
} }
mCallDataValues.clear(); mCallDataValues.clear();
}//把电话号码数据存入DataColumns }
if (operationList.size() > 0) { if (operationList.size() > 0) {
try { try {
ContentProviderResult[] results = context.getContentResolver().applyBatch( ContentProviderResult[] results = context.getContentResolver().applyBatch(
@ -225,8 +246,8 @@ public class Note {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
return null; return null;
} }
}//存储过程中的异常处理 }
return null; return null;
} }
} }
} }

@ -1,5 +1,37 @@
/*
* 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.model; package net.micode.notes.model;
import android.appwidget.AppWidgetManager;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.text.TextUtils;
import android.util.Log;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.CallNote;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.Notes.TextNote;
import net.micode.notes.tool.ResourceParser.NoteBgResources;
public class WorkingNote { public class WorkingNote {
// Note for the working note // Note for the working note
private Note mNote; private Note mNote;
@ -9,22 +41,27 @@ public class WorkingNote {
private String mContent; private String mContent;
// Note mode // Note mode
private int mMode; private int mMode;
private long mAlertDate; private long mAlertDate;
private long mModifiedDate; private long mModifiedDate;
private int mBgColorId; private int mBgColorId;
private int mWidgetId; private int mWidgetId;
private int mWidgetType; private int mWidgetType;
private long mFolderId; private long mFolderId;
private Context mContext; private Context mContext;
private static final String TAG = "WorkingNote"; private static final String TAG = "WorkingNote";
private boolean mIsDeleted; private boolean mIsDeleted;
private NoteSettingChangedListener mNoteSettingStatusListener; private NoteSettingChangedListener mNoteSettingStatusListener;
// 声明 DATA_PROJECTION字符串数组
public static final String[] DATA_PROJECTION = new String[] { public static final String[] DATA_PROJECTION = new String[] {
DataColumns.ID, DataColumns.ID,
DataColumns.CONTENT, DataColumns.CONTENT,
@ -34,8 +71,7 @@ public class WorkingNote {
DataColumns.DATA3, DataColumns.DATA3,
DataColumns.DATA4, DataColumns.DATA4,
}; };
// 声明 NOTE_PROJECTION字符串数组
public static final String[] NOTE_PROJECTION = new String[] { public static final String[] NOTE_PROJECTION = new String[] {
NoteColumns.PARENT_ID, NoteColumns.PARENT_ID,
NoteColumns.ALERTED_DATE, NoteColumns.ALERTED_DATE,
@ -44,20 +80,29 @@ public class WorkingNote {
NoteColumns.WIDGET_TYPE, NoteColumns.WIDGET_TYPE,
NoteColumns.MODIFIED_DATE NoteColumns.MODIFIED_DATE
}; };
private static final int DATA_ID_COLUMN = 0; private static final int DATA_ID_COLUMN = 0;
private static final int DATA_CONTENT_COLUMN = 1; private static final int DATA_CONTENT_COLUMN = 1;
private static final int DATA_MIME_TYPE_COLUMN = 2; private static final int DATA_MIME_TYPE_COLUMN = 2;
private static final int DATA_MODE_COLUMN = 3; private static final int DATA_MODE_COLUMN = 3;
private static final int NOTE_PARENT_ID_COLUMN = 0; private static final int NOTE_PARENT_ID_COLUMN = 0;
private static final int NOTE_ALERTED_DATE_COLUMN = 1; private static final int NOTE_ALERTED_DATE_COLUMN = 1;
private static final int NOTE_BG_COLOR_ID_COLUMN = 2; private static final int NOTE_BG_COLOR_ID_COLUMN = 2;
private static final int NOTE_WIDGET_ID_COLUMN = 3; private static final int NOTE_WIDGET_ID_COLUMN = 3;
private static final int NOTE_WIDGET_TYPE_COLUMN = 4; private static final int NOTE_WIDGET_TYPE_COLUMN = 4;
private static final int NOTE_MODIFIED_DATE_COLUMN = 5; private static final int NOTE_MODIFIED_DATE_COLUMN = 5;
// New note construct // New note construct
public WorkingNote(Context context, long folderId) { private WorkingNote(Context context, long folderId) {
mContext = context; mContext = context;
mAlertDate = 0; mAlertDate = 0;
mModifiedDate = System.currentTimeMillis(); mModifiedDate = System.currentTimeMillis();
@ -68,8 +113,7 @@ public class WorkingNote {
mMode = 0; mMode = 0;
mWidgetType = Notes.TYPE_WIDGET_INVALIDE; mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
} }
// WorkingNote的构造函数
// Existing note construct // Existing note construct
private WorkingNote(Context context, long noteId, long folderId) { private WorkingNote(Context context, long noteId, long folderId) {
mContext = context; mContext = context;
@ -79,15 +123,12 @@ public class WorkingNote {
mNote = new Note(); mNote = new Note();
loadNote(); loadNote();
} }
// 加载Note
// 通过数据库调用query函数找到第一个条目
private void loadNote() { private void loadNote() {
Cursor cursor = mContext.getContentResolver().query( Cursor cursor = mContext.getContentResolver().query(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null, ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null,
null, null); null, null);
// 若存在,储存相应信息
if (cursor != null) { if (cursor != null) {
if (cursor.moveToFirst()) { if (cursor.moveToFirst()) {
mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN); mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN);
@ -98,24 +139,21 @@ public class WorkingNote {
mModifiedDate = cursor.getLong(NOTE_MODIFIED_DATE_COLUMN); mModifiedDate = cursor.getLong(NOTE_MODIFIED_DATE_COLUMN);
} }
cursor.close(); cursor.close();
// 若不存在,报错
} else { } else {
Log.e(TAG, "No note with id:" + mNoteId); Log.e(TAG, "No note with id:" + mNoteId);
throw new IllegalArgumentException("Unable to find note with id " + mNoteId); throw new IllegalArgumentException("Unable to find note with id " + mNoteId);
} }
loadNoteData(); loadNoteData();
} }
// 加载NoteData
private void loadNoteData() { private void loadNoteData() {
Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION, Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION,
DataColumns.NOTE_ID + "=?", new String[] { DataColumns.NOTE_ID + "=?", new String[] {
String.valueOf(mNoteId) String.valueOf(mNoteId)
}, null); }, null);
if (cursor != null) { if (cursor != null) {
// 查到信息不为空 if (cursor.moveToFirst()) {
if (cursor.moveToFirst()) { // 查看第一项是否存在
do { do {
String type = cursor.getString(DATA_MIME_TYPE_COLUMN); String type = cursor.getString(DATA_MIME_TYPE_COLUMN);
if (DataConstants.NOTE.equals(type)) { if (DataConstants.NOTE.equals(type)) {
@ -127,7 +165,7 @@ public class WorkingNote {
} else { } else {
Log.d(TAG, "Wrong note type with type:" + type); Log.d(TAG, "Wrong note type with type:" + type);
} }
} while (cursor.moveToNext());//查阅所有项,直到为空 } while (cursor.moveToNext());
} }
cursor.close(); cursor.close();
} else { } else {
@ -135,35 +173,31 @@ public class WorkingNote {
throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId); throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId);
} }
} }
// 创建空的Note
// 传参context文件夹idwidget背景颜色
public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId, public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId,
int widgetType, int defaultBgColorId) { int widgetType, int defaultBgColorId) {
WorkingNote note = new WorkingNote(context, folderId); WorkingNote note = new WorkingNote(context, folderId);
// 设定相关属性
note.setBgColorId(defaultBgColorId); note.setBgColorId(defaultBgColorId);
note.setWidgetId(widgetId); note.setWidgetId(widgetId);
note.setWidgetType(widgetType); note.setWidgetType(widgetType);
return note; return note;
} }
public static WorkingNote load(Context context, long id) { public static WorkingNote load(Context context, long id) {
return new WorkingNote(context, id, 0); return new WorkingNote(context, id, 0);
} }
// 保存Note
public synchronized boolean saveNote() { public synchronized boolean saveNote() {
if (isWorthSaving()) { //是否值得保存 if (isWorthSaving()) {
if (!existInDatabase()) { // 是否存在数据库中 if (!existInDatabase()) {
if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) { if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) {
Log.e(TAG, "Create new note fail with id:" + mNoteId); Log.e(TAG, "Create new note fail with id:" + mNoteId);
return false; return false;
} }
} }
mNote.syncNote(mContext, mNoteId); mNote.syncNote(mContext, mNoteId);
/** /**
* Update widget content if there exist any widget of this note * Update widget content if there exist any widget of this note
*/ */
@ -177,15 +211,12 @@ public class WorkingNote {
return false; return false;
} }
} }
// 是否在数据库中存在
public boolean existInDatabase() { public boolean existInDatabase() {
return mNoteId > 0; return mNoteId > 0;
} }
// 是否值得保存
private boolean isWorthSaving() { private boolean isWorthSaving() {
// 被删除,或(不在数据库中 内容为空),或 本地已保存过
if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent)) if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent))
|| (existInDatabase() && !mNote.isLocalModified())) { || (existInDatabase() && !mNote.isLocalModified())) {
return false; return false;
@ -193,15 +224,11 @@ public class WorkingNote {
return true; return true;
} }
} }
// 设置mNoteSettingStatusListener
public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) { public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) {
mNoteSettingStatusListener = l; mNoteSettingStatusListener = l;
} }
// 设置AlertDate
// 若 mAlertDate与data不同则更改mAlertDate并设定NoteValue
public void setAlertDate(long date, boolean set) { public void setAlertDate(long date, boolean set) {
if (date != mAlertDate) { if (date != mAlertDate) {
mAlertDate = date; mAlertDate = date;
@ -211,21 +238,17 @@ public class WorkingNote {
mNoteSettingStatusListener.onClockAlertChanged(date, set); mNoteSettingStatusListener.onClockAlertChanged(date, set);
} }
} }
// 设定删除标记
public void markDeleted(boolean mark) { public void markDeleted(boolean mark) {
// 设定标记
mIsDeleted = mark; mIsDeleted = mark;
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) { && mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onWidgetChanged(); mNoteSettingStatusListener.onWidgetChanged();
// 调用mNoteSettingStatusListener的 onWidgetChanged方法
} }
} }
// 设定背景颜色
public void setBgColorId(int id) { public void setBgColorId(int id) {
if (id != mBgColorId) { //设定条件 id != mBgColorId if (id != mBgColorId) {
mBgColorId = id; mBgColorId = id;
if (mNoteSettingStatusListener != null) { if (mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onBackgroundColorChanged(); mNoteSettingStatusListener.onBackgroundColorChanged();
@ -233,11 +256,9 @@ public class WorkingNote {
mNote.setNoteValue(NoteColumns.BG_COLOR_ID, String.valueOf(id)); mNote.setNoteValue(NoteColumns.BG_COLOR_ID, String.valueOf(id));
} }
} }
// 设定检查列表模式
// 参数mode
public void setCheckListMode(int mode) { public void setCheckListMode(int mode) {
if (mMode != mode) { //设定条件 mMode != mode if (mMode != mode) {
if (mNoteSettingStatusListener != null) { if (mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode); mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode);
} }
@ -245,125 +266,98 @@ public class WorkingNote {
mNote.setTextData(TextNote.MODE, String.valueOf(mMode)); mNote.setTextData(TextNote.MODE, String.valueOf(mMode));
} }
} }
// 设定WidgetType
// 参数type
public void setWidgetType(int type) { public void setWidgetType(int type) {
if (type != mWidgetType) {//设定条件 type != mWidgetType if (type != mWidgetType) {
mWidgetType = type; mWidgetType = type;
mNote.setNoteValue(NoteColumns.WIDGET_TYPE, String.valueOf(mWidgetType)); mNote.setNoteValue(NoteColumns.WIDGET_TYPE, String.valueOf(mWidgetType));
// 调用Note的setNoteValue方法更改WidgetType
} }
} }
// 设定WidgetId
// 参数id
public void setWidgetId(int id) { public void setWidgetId(int id) {
if (id != mWidgetId) {//设定条件 id != mWidgetId if (id != mWidgetId) {
mWidgetId = id; mWidgetId = id;
mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId)); mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId));
// 调用Note的setNoteValue方法更改WidgetId
} }
} }
// 设定WorkingTex
// 参数更改的text
public void setWorkingText(String text) { public void setWorkingText(String text) {
if (!TextUtils.equals(mContent, text)) {//设定条件 mContent, text内容不同 if (!TextUtils.equals(mContent, text)) {
mContent = text; mContent = text;
mNote.setTextData(DataColumns.CONTENT, mContent); mNote.setTextData(DataColumns.CONTENT, mContent);
// 调用Note的setTextData方法更改WorkingText
} }
} }
// 转变mNote的CallData及CallNote信息
// 参数String phoneNumber, long callDate
public void convertToCallNote(String phoneNumber, long callDate) { public void convertToCallNote(String phoneNumber, long callDate) {
mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate)); mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate));
mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber); mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber);
mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER)); mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER));
} }
// 判断是否有时钟题型
public boolean hasClockAlert() { public boolean hasClockAlert() {
return (mAlertDate > 0 ? true : false); return (mAlertDate > 0 ? true : false);
} }
// 获取Content
public String getContent() { public String getContent() {
return mContent; return mContent;
} }
// 获取AlertDate
public long getAlertDate() { public long getAlertDate() {
return mAlertDate; return mAlertDate;
} }
// 获取ModifiedDate
public long getModifiedDate() { public long getModifiedDate() {
return mModifiedDate; return mModifiedDate;
} }
// 获取背景颜色来源id
public int getBgColorResId() { public int getBgColorResId() {
return NoteBgResources.getNoteBgResource(mBgColorId); return NoteBgResources.getNoteBgResource(mBgColorId);
} }
// 获取背景颜色id
public int getBgColorId() { public int getBgColorId() {
return mBgColorId; return mBgColorId;
} }
// 获取标题背景颜色id
public int getTitleBgResId() { public int getTitleBgResId() {
return NoteBgResources.getNoteTitleBgResource(mBgColorId); return NoteBgResources.getNoteTitleBgResource(mBgColorId);
} }
// 获取CheckListMode
public int getCheckListMode() { public int getCheckListMode() {
return mMode; return mMode;
} }
// 获取便签id
public long getNoteId() { public long getNoteId() {
return mNoteId; return mNoteId;
} }
// 获取文件夹id
public long getFolderId() { public long getFolderId() {
return mFolderId; return mFolderId;
} }
// 获取WidgetId
public int getWidgetId() { public int getWidgetId() {
return mWidgetId; return mWidgetId;
} }
// 获取WidgetType
public int getWidgetType() { public int getWidgetType() {
return mWidgetType; return mWidgetType;
} }
// 创建接口 NoteSettingChangedListener,便签更新监视 public interface NoteSettingChangedListener {
// 为NoteEditActivity提供接口
// 提供函数有
public interface NoteSettingChangedListener {
/** /**
* Called when the background color of current note has just changed * Called when the background color of current note has just changed
*/ */
void onBackgroundColorChanged(); void onBackgroundColorChanged();
/** /**
* Called when user set clock * Called when user set clock
*/ */
void onClockAlertChanged(long date, boolean set); void onClockAlertChanged(long date, boolean set);
/** /**
* Call when user create note from widget * Call when user create note from widget
*/ */
void onWidgetChanged(); void onWidgetChanged();
/** /**
* Call when switch between check list mode and normal mode * Call when switch between check list mode and normal mode
* @param oldMode is previous mode before change * @param oldMode is previous mode before change
@ -371,4 +365,4 @@ public class WorkingNote {
*/ */
void onCheckListModeChanged(int oldMode, int newMode); void onCheckListModeChanged(int oldMode, int newMode);
} }
} }

@ -14,168 +14,145 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.ui; package net.micode.notes.ui;
import android.app.Activity; import android.app.Activity;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.content.Context; import android.content.Context;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnDismissListener; import android.content.DialogInterface.OnDismissListener;
import android.content.Intent; import android.content.Intent;
import android.media.AudioManager; import android.media.AudioManager;
import android.media.MediaPlayer; import android.media.MediaPlayer;
import android.media.RingtoneManager; import android.media.RingtoneManager;
import android.net.Uri; import android.net.Uri;
import android.os.Bundle; import android.os.Bundle;
import android.os.PowerManager; import android.os.PowerManager;
import android.provider.Settings; import android.provider.Settings;
import android.view.Window; import android.view.Window;
import android.view.WindowManager; import android.view.WindowManager;
import net.micode.notes.R; import net.micode.notes.R;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.tool.DataUtils; import net.micode.notes.tool.DataUtils;
import java.io.IOException; import java.io.IOException;
public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener {
private long mNoteId; //文本在数据库存储中的ID号 public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener {
private String mSnippet; //闹钟提示时出现的文本片段 private long mNoteId;
private static final int SNIPPET_PREW_MAX_LEN = 60; private String mSnippet;
MediaPlayer mPlayer; private static final int SNIPPET_PREW_MAX_LEN = 60;
MediaPlayer mPlayer;
@Override
//当闹钟创建时需要做的初始化 @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
//Bundle类型的数据与Map类型的数据相似都是以key-value的形式存储数据的 requestWindowFeature(Window.FEATURE_NO_TITLE);
//onsaveInstanceState方法是用来保存Activity的状态的
//能从onCreate的参数savedInsanceState中获得状态数据 final Window win = getWindow();
requestWindowFeature(Window.FEATURE_NO_TITLE); win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
//界面显示——无标题
if (!isScreenOn()) {
final Window win = getWindow(); win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
| WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
if (!isScreenOn()) { //在手机锁屏后如果到了闹钟提示时间,点亮屏幕 | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR);
win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON }
//保持窗体点亮
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON Intent intent = getIntent();
//将窗体点亮
| WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON try {
//允许窗体点亮时锁屏 mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1));
| WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR); mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId);
} mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0,
SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info)
Intent intent = getIntent(); : mSnippet;
} catch (IllegalArgumentException e) {
try { e.printStackTrace();
mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1)); //获得所有的ID return;
mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId); }
//根据ID从数据库中获取标签的内容
//getContentResolver是实现数据共享实例存储 mPlayer = new MediaPlayer();
mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0, if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) {
SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info) showActionDialog();
: mSnippet; playAlarmSound();
//判断标签片段是否达到符合长度 } else {
} catch (IllegalArgumentException e) { finish();
e.printStackTrace(); //e.printStackTrace()函数功能是抛出异常, 还将显示出更深的调用信息 }
return; }
}
private boolean isScreenOn() {
mPlayer = new MediaPlayer(); //媒体控制模块 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) { //如果ID和type_note在数据库中可见 return pm.isScreenOn();
showActionDialog(); }
//调用内部函数弹出对话框
playAlarmSound(); private void playAlarmSound() {
//调用内部函数函数闹钟音乐 Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);
} else {
finish(); int silentModeStreams = Settings.System.getInt(getContentResolver(),
//完成闹钟动作 Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);
}
} if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) {
mPlayer.setAudioStreamType(silentModeStreams);
private boolean isScreenOn() { } else {
//判断屏幕是否锁屏,调用系统函数判断 mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); }
return pm.isScreenOn(); try {
} mPlayer.setDataSource(this, url);
mPlayer.prepare();
private void playAlarmSound() { mPlayer.setLooping(true);
//播放闹钟音乐 mPlayer.start();
Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM); } catch (IllegalArgumentException e) {
//调用系统的铃声管理URI得到闹钟提示音 // TODO Auto-generated catch block
int silentModeStreams = Settings.System.getInt(getContentResolver(), e.printStackTrace();
Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0); //系统中设置音频流格式的值 } catch (SecurityException e) {
// TODO Auto-generated catch block
if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) { e.printStackTrace();
//铃声模式是否影响闹钟音量,是则音频流模式设置跟随系统设置,不是则设为默认 } catch (IllegalStateException e) {
mPlayer.setAudioStreamType(silentModeStreams); // TODO Auto-generated catch block
} else { e.printStackTrace();
mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); } catch (IOException e) {
} // TODO Auto-generated catch block
try { e.printStackTrace();
mPlayer.setDataSource(this, url); }
//设置多媒体数据来源 根据 Uri }
mPlayer.prepare();
//准备同步 private void showActionDialog() {
mPlayer.setLooping(true); AlertDialog.Builder dialog = new AlertDialog.Builder(this);
//设置是否循环播放 dialog.setTitle(R.string.app_name);
mPlayer.start(); dialog.setMessage(mSnippet);
//开始 dialog.setPositiveButton(R.string.notealert_ok, this);
} catch (IllegalArgumentException e) { if (isScreenOn()) {
e.printStackTrace(); dialog.setNegativeButton(R.string.notealert_enter, this);
} catch (SecurityException e) { }
e.printStackTrace(); dialog.show().setOnDismissListener(this);
} catch (IllegalStateException e) { }
e.printStackTrace();
} catch (IOException e) { public void onClick(DialogInterface dialog, int which) {
e.printStackTrace(); switch (which) {
} case DialogInterface.BUTTON_NEGATIVE:
} Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_VIEW);
private void showActionDialog() { intent.putExtra(Intent.EXTRA_UID, mNoteId);
AlertDialog.Builder dialog = new AlertDialog.Builder(this); startActivity(intent);
//新建一个dialog break;
//注意AlertDialog的构造方法全部是Protected的所以不能直接通过new一个AlertDialog来创建出一个AlertDialog default:
//要调用AlertDialog.Builder中的create() break;
dialog.setTitle(R.string.app_name); }
dialog.setMessage(mSnippet); }
//初始化标题,内容
dialog.setPositiveButton(R.string.notealert_ok, this); public void onDismiss(DialogInterface dialog) {
//给对话框添加"Yes"按钮 stopAlarmSound();
if (isScreenOn()) { //如果亮屏,则对话框添加"No"按钮 finish();
dialog.setNegativeButton(R.string.notealert_enter, this); }
}
dialog.show().setOnDismissListener(this); private void stopAlarmSound() {
} if (mPlayer != null) {
mPlayer.stop();
public void onClick(DialogInterface dialog, int which) { mPlayer.release();
switch (which) { mPlayer = null;
//用which来选择click后下一步的操作 }
case DialogInterface.BUTTON_NEGATIVE: //如果是“取消” }
Intent intent = new Intent(this, NoteEditActivity.class); //实现两个类间的数据传输 }
intent.setAction(Intent.ACTION_VIEW); //设置动作属性
intent.putExtra(Intent.EXTRA_UID, mNoteId); //实现key-value对 XTRA_UID为keymNoteId为键
startActivity(intent); //开始动作
break;
default: //如果是“确定”
break;
}
}
public void onDismiss(DialogInterface dialog) {
stopAlarmSound();
//停止闹钟声音
finish();
}
private void stopAlarmSound() {
if (mPlayer != null) { //存在媒体对象
mPlayer.stop(); //停止播放
mPlayer.release(); //释放MediaPlayer对象
mPlayer = null;
}
}
}

@ -14,57 +14,52 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.ui; package net.micode.notes.ui;
import android.app.AlarmManager; import android.app.AlarmManager;
import android.app.PendingIntent; import android.app.PendingIntent;
import android.content.BroadcastReceiver; import android.content.BroadcastReceiver;
import android.content.ContentUris; import android.content.ContentUris;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.database.Cursor; import android.database.Cursor;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
public class AlarmInitReceiver extends BroadcastReceiver { public class AlarmInitReceiver extends BroadcastReceiver {
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和闹钟时间
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);
//将long变量currentDate转化为字符串
null); if (c != null) {
//通过查找数据库中的标签内容,找到晚于当前时间的标签 if (c.moveToFirst()) {
do {
if (c != null) { long alertDate = c.getLong(COLUMN_ALERTED_DATE);
if (c.moveToFirst()) { Intent sender = new Intent(context, AlarmReceiver.class);
do { sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID)));
long alertDate = c.getLong(COLUMN_ALERTED_DATE); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0);
Intent sender = new Intent(context, AlarmReceiver.class); AlarmManager alermManager = (AlarmManager) context
sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID))); .getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0); //获得一个可广播的intent对象 alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);
AlarmManager alermManager = (AlarmManager) context //设置闹钟 } while (c.moveToNext());
.getSystemService(Context.ALARM_SERVICE); }
alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent); c.close();
} while (c.moveToNext()); }
} }
c.close(); }
}
//查询结果不为空,就遍历结果集并为每个标签创建一个闹钟
//这里就是根据数据库里的闹钟时间创建一个闹钟机制
}
}

@ -14,24 +14,17 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.ui; package net.micode.notes.ui;
import android.content.BroadcastReceiver; import android.content.BroadcastReceiver;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
public class AlarmReceiver extends BroadcastReceiver { public class AlarmReceiver extends BroadcastReceiver {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
intent.setClass(context, AlarmAlertActivity.class); intent.setClass(context, AlarmAlertActivity.class);
//启动AlarmAlertActivity intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent);
//确保新启动的Activity存在于一个新的任务栈中而不是当前的Activity栈内 }
//activity要存在于activity的栈中而非activity的途径启动activity时必然不存在一个activity的栈 }
//所以要新起一个栈装入启动的activity
context.startActivity(intent);
}
}
//用于捕获闹钟触发的事件并在接收到广播时启动相应的Activity来处理闹钟提醒
//作用还需要深究但是对于setClass和addFlags的

@ -14,473 +14,472 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.ui; package net.micode.notes.ui;
import java.text.DateFormatSymbols; import java.text.DateFormatSymbols;
import java.util.Calendar; import java.util.Calendar;
import net.micode.notes.R; import net.micode.notes.R;
import android.content.Context; import android.content.Context;
import android.text.format.DateFormat; import android.text.format.DateFormat;
import android.view.View; import android.view.View;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import android.widget.NumberPicker; import android.widget.NumberPicker;
public class DateTimePicker extends FrameLayout { public class DateTimePicker extends FrameLayout {
private static final boolean DEFAULT_ENABLE_STATE = true;
private static final boolean DEFAULT_ENABLE_STATE = true;
private static final int HOURS_IN_HALF_DAY = 12;
private static final int HOURS_IN_ALL_DAY = 24; private static final int HOURS_IN_HALF_DAY = 12;
private static final int DAYS_IN_ALL_WEEK = 7; private static final int HOURS_IN_ALL_DAY = 24;
private static final int DATE_SPINNER_MIN_VAL = 0; private static final int DAYS_IN_ALL_WEEK = 7;
private static final int DATE_SPINNER_MAX_VAL = DAYS_IN_ALL_WEEK - 1; private static final int DATE_SPINNER_MIN_VAL = 0;
private static final int HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW = 0; private static final int DATE_SPINNER_MAX_VAL = DAYS_IN_ALL_WEEK - 1;
private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23; private static final int HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW = 0;
private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1; private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23;
private static final int HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW = 12; private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1;
private static final int MINUT_SPINNER_MIN_VAL = 0; private static final int HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW = 12;
private static final int MINUT_SPINNER_MAX_VAL = 59; private static final int MINUT_SPINNER_MIN_VAL = 0;
private static final int AMPM_SPINNER_MIN_VAL = 0; private static final int MINUT_SPINNER_MAX_VAL = 59;
private static final int AMPM_SPINNER_MAX_VAL = 1; private static final int AMPM_SPINNER_MIN_VAL = 0;
private static final int AMPM_SPINNER_MAX_VAL = 1;
private final NumberPicker mDateSpinner;
private final NumberPicker mHourSpinner; private final NumberPicker mDateSpinner;
private final NumberPicker mMinuteSpinner; private final NumberPicker mHourSpinner;
private final NumberPicker mAmPmSpinner; private final NumberPicker mMinuteSpinner;
private final NumberPicker mAmPmSpinner;
private Calendar mDate; private Calendar mDate;
private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK]; private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK];
private boolean mIsAm; private boolean mIsAm;
private boolean mIs24HourView; private boolean mIs24HourView;
private boolean mIsEnabled = DEFAULT_ENABLE_STATE; private boolean mIsEnabled = DEFAULT_ENABLE_STATE;
private boolean mInitialising; private boolean mInitialising;
private OnDateTimeChangedListener mOnDateTimeChangedListener; private OnDateTimeChangedListener mOnDateTimeChangedListener;
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();
} }
}; };
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();
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) {
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) {
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;
} }
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) {
mIsAm = !mIsAm; mIsAm = !mIsAm;
updateAmPmControl(); updateAmPmControl();
} }
} else { } else {
if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) { if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) {
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) {
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));
setCurrentDay(cal.get(Calendar.DAY_OF_MONTH)); setCurrentDay(cal.get(Calendar.DAY_OF_MONTH));
} }
} }
}; };
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;
if (oldVal == maxValue && newVal == minValue) {
if (oldVal == maxValue && newVal == minValue) { offset += 1;
offset += 1; } else if (oldVal == minValue && newVal == maxValue) {
} else if (oldVal == minValue && newVal == maxValue) { offset -= 1;
offset -= 1; }
} if (offset != 0) {
mDate.add(Calendar.HOUR_OF_DAY, offset);
if (offset != 0) { mHourSpinner.setValue(getCurrentHour());
mDate.add(Calendar.HOUR_OF_DAY, offset); updateDateControl();
mHourSpinner.setValue(getCurrentHour()); int newHour = getCurrentHourOfDay();
updateDateControl(); if (newHour >= HOURS_IN_HALF_DAY) {
int newHour = getCurrentHourOfDay(); mIsAm = false;
if (newHour >= HOURS_IN_HALF_DAY) { updateAmPmControl();
mIsAm = false; } else {
updateAmPmControl(); mIsAm = true;
} else { updateAmPmControl();
mIsAm = true; }
updateAmPmControl(); }
} mDate.set(Calendar.MINUTE, newVal);
} onDateTimeChanged();
mDate.set(Calendar.MINUTE, newVal); }
onDateTimeChanged(); };
}
}; private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() { public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
mIsAm = !mIsAm;
@Override if (mIsAm) {
public void onValueChange(NumberPicker picker, int oldVal, int newVal) { mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY);
mIsAm = !mIsAm; } else {
if (mIsAm) { mDate.add(Calendar.HOUR_OF_DAY, HOURS_IN_HALF_DAY);
mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY); }
} else { updateAmPmControl();
mDate.add(Calendar.HOUR_OF_DAY, HOURS_IN_HALF_DAY); onDateTimeChanged();
} }
updateAmPmControl(); };
onDateTimeChanged();
} public interface OnDateTimeChangedListener {
}; void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute);
public interface OnDateTimeChangedListener { }
void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute); public DateTimePicker(Context context) {
} this(context, System.currentTimeMillis());
}
public DateTimePicker(Context context) {
this(context, System.currentTimeMillis()); public DateTimePicker(Context context, long date) {
} this(context, date, DateFormat.is24HourFormat(context));
}
public DateTimePicker(Context context, long date) {
this(context, date, DateFormat.is24HourFormat(context)); public DateTimePicker(Context context, long date, boolean is24HourView) {
} super(context);
public DateTimePicker(Context context, long date, boolean is24HourView) { mDate = Calendar.getInstance();
super(context); mInitialising = true;
mDate = Calendar.getInstance(); mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY;
mInitialising = true; inflate(context, R.layout.datetime_picker, this);
mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY;
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
updateDateControl();
updateDateControl(); updateHourControl();
updateHourControl(); updateAmPmControl();
updateAmPmControl();
set24HourView(is24HourView);
set24HourView(is24HourView);
// set to current time
setCurrentDate(date);
setCurrentDate(date);
setEnabled(isEnabled());
setEnabled(isEnabled());
// set the content descriptions
mInitialising = false;
mInitialising = false; }
}
@Override
@Override public void setEnabled(boolean enabled) {
public void setEnabled(boolean enabled) { if (mIsEnabled == enabled) {
if (mIsEnabled == enabled) { return;
return; }
} 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() { return mIsEnabled;
return mIsEnabled; }
}
/**
/** * Get the current date in millis
* Get the current date in millis *
* * @return the current date in millis
* @return the current date in millis */
*/ public long getCurrentDateInTimeMillis() {
public long getCurrentDateInTimeMillis() { return mDate.getTimeInMillis();
return mDate.getTimeInMillis(); }
}
/**
/** * Set the current date
* Set the current date *
* * @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)); }
}
/**
/** * Set the current date
* Set the current date *
* * @param year The current year
* @param year The current year * @param month The current month
* @param month The current month * @param dayOfMonth The current dayOfMonth
* @param dayOfMonth The current dayOfMonth * @param hourOfDay The current hourOfDay
* @param hourOfDay The current hourOfDay * @param minute The current minute
* @param minute The current minute */
*/ 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); }
}
/**
/** * Get current year
* Get current year *
* * @return The current year
* @return The current year */
*/ public int getCurrentYear() {
public int getCurrentYear() { return mDate.get(Calendar.YEAR);
return mDate.get(Calendar.YEAR); }
}
/**
/** * Set current year
* Set current year *
* * @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(); }
}
/**
/** * Get current month in the year
* Get current month in the year *
* * @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); }
}
/**
/** * Set current month in the year
* Set current month in the year *
* * @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(); }
}
/**
/** * Get current day of the month
* Get current day of the month *
* * @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); }
}
/**
/** * Set current day of the month
* Set current day of the month *
* * @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(); }
}
/**
/** * 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() { if (mIs24HourView){
if (mIs24HourView){ return getCurrentHourOfDay();
return getCurrentHourOfDay(); } else {
} else { int hour = getCurrentHourOfDay();
int hour = getCurrentHourOfDay(); if (hour > HOURS_IN_HALF_DAY) {
if (hour > HOURS_IN_HALF_DAY) { return hour - HOURS_IN_HALF_DAY;
return hour - HOURS_IN_HALF_DAY; } else {
} else { return hour == 0 ? HOURS_IN_HALF_DAY : hour;
return hour == 0 ? HOURS_IN_HALF_DAY : hour; }
} }
} }
}
/**
/** * Set current hour in 24 hour mode, in the range (0~23)
* Set current hour in 24 hour mode, in the range (0~23) *
* * @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); if (!mIs24HourView) {
if (!mIs24HourView) { if (hourOfDay >= HOURS_IN_HALF_DAY) {
if (hourOfDay >= HOURS_IN_HALF_DAY) { mIsAm = false;
mIsAm = false; if (hourOfDay > HOURS_IN_HALF_DAY) {
if (hourOfDay > HOURS_IN_HALF_DAY) { hourOfDay -= HOURS_IN_HALF_DAY;
hourOfDay -= HOURS_IN_HALF_DAY; }
} } else {
} else { mIsAm = true;
mIsAm = true; if (hourOfDay == 0) {
if (hourOfDay == 0) { hourOfDay = HOURS_IN_HALF_DAY;
hourOfDay = HOURS_IN_HALF_DAY; }
} }
} updateAmPmControl();
updateAmPmControl(); }
} mHourSpinner.setValue(hourOfDay);
mHourSpinner.setValue(hourOfDay); onDateTimeChanged();
onDateTimeChanged(); }
}
/**
/** * Get currentMinute
* Get currentMinute *
* * @return The Current Minute
* @return The Current Minute */
*/ public int getCurrentMinute() {
public int getCurrentMinute() { return mDate.get(Calendar.MINUTE);
return mDate.get(Calendar.MINUTE); }
}
/**
/** * Set current minute
* Set current minute */
*/ public void setCurrentMinute(int minute) {
public void setCurrentMinute(int minute) { if (!mInitialising && minute == getCurrentMinute()) {
if (!mInitialising && minute == getCurrentMinute()) { return;
return; }
} mMinuteSpinner.setValue(minute);
mMinuteSpinner.setValue(minute); mDate.set(Calendar.MINUTE, minute);
mDate.set(Calendar.MINUTE, minute); onDateTimeChanged();
onDateTimeChanged(); }
}
/**
/** * @return true if this is in 24 hour view else false.
* @return true if this is in 24 hour view else false. */
*/ public boolean is24HourView () {
public boolean is24HourView () { return mIs24HourView;
return mIs24HourView; }
}
/**
/** * Set whether in 24 hour or AM/PM mode.
* Set whether in 24 hour or AM/PM mode. *
* * @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; 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(); cal.setTimeInMillis(mDate.getTimeInMillis());
cal.setTimeInMillis(mDate.getTimeInMillis()); 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.setDisplayedValues(null);
mDateSpinner.setDisplayedValues(null); for (int i = 0; i < DAYS_IN_ALL_WEEK; ++i) {
for (int i = 0; i < DAYS_IN_ALL_WEEK; ++i) { cal.add(Calendar.DAY_OF_YEAR, 1);
cal.add(Calendar.DAY_OF_YEAR, 1); mDateDisplayValues[i] = (String) DateFormat.format("MM.dd EEEE", cal);
mDateDisplayValues[i] = (String) DateFormat.format("MM.dd EEEE", cal); }
} mDateSpinner.setDisplayedValues(mDateDisplayValues);
mDateSpinner.setDisplayedValues(mDateDisplayValues); mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2);
mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2); mDateSpinner.invalidate();
mDateSpinner.invalidate(); }
}
private void updateAmPmControl() {
private void updateAmPmControl() { 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() { if (mIs24HourView) {
if (mIs24HourView) { mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW);
mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW); mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW);
mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW); } else {
} else { mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW);
mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW); mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW);
mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW); }
} }
}
/**
/** * 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) { mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(),
mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(), getCurrentMonth(), getCurrentDay(), getCurrentHourOfDay(), getCurrentMinute());
getCurrentMonth(), getCurrentDay(), getCurrentHourOfDay(), getCurrentMinute()); }
} }
} }
}

@ -14,77 +14,77 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.ui; package net.micode.notes.ui;
import java.util.Calendar; import java.util.Calendar;
import net.micode.notes.R; import net.micode.notes.R;
import net.micode.notes.ui.DateTimePicker; import net.micode.notes.ui.DateTimePicker;
import net.micode.notes.ui.DateTimePicker.OnDateTimeChangedListener; import net.micode.notes.ui.DateTimePicker.OnDateTimeChangedListener;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.content.Context; import android.content.Context;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnClickListener;
import android.text.format.DateFormat; import android.text.format.DateFormat;
import android.text.format.DateUtils; import android.text.format.DateUtils;
public class DateTimePickerDialog extends AlertDialog implements OnClickListener { public class DateTimePickerDialog extends AlertDialog implements OnClickListener {
private Calendar mDate = Calendar.getInstance(); private Calendar mDate = Calendar.getInstance();
private boolean mIs24HourView; private boolean mIs24HourView;
private OnDateTimeSetListener mOnDateTimeSetListener; private OnDateTimeSetListener mOnDateTimeSetListener;
private DateTimePicker mDateTimePicker; private DateTimePicker mDateTimePicker;
public interface OnDateTimeSetListener { public interface OnDateTimeSetListener {
void OnDateTimeSet(AlertDialog dialog, long date); void OnDateTimeSet(AlertDialog dialog, long date);
} }
public DateTimePickerDialog(Context context, long date) { public DateTimePickerDialog(Context context, long date) {
super(context); super(context);
mDateTimePicker = new DateTimePicker(context); mDateTimePicker = new DateTimePicker(context);
setView(mDateTimePicker); setView(mDateTimePicker);
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);
set24HourView(DateFormat.is24HourFormat(this.getContext())); set24HourView(DateFormat.is24HourFormat(this.getContext()));
updateTitle(mDate.getTimeInMillis()); updateTitle(mDate.getTimeInMillis());
} }
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;
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) {
if (mOnDateTimeSetListener != null) { if (mOnDateTimeSetListener != null) {
mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis()); mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis());
} }
} }
} }

@ -14,48 +14,48 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.ui; package net.micode.notes.ui;
import android.content.Context; import android.content.Context;
import android.view.Menu; import android.view.Menu;
import android.view.MenuItem; import android.view.MenuItem;
import android.view.View; import android.view.View;
import android.view.View.OnClickListener; import android.view.View.OnClickListener;
import android.widget.Button; import android.widget.Button;
import android.widget.PopupMenu; import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener; import android.widget.PopupMenu.OnMenuItemClickListener;
import net.micode.notes.R; import net.micode.notes.R;
public class DropdownMenu { public class DropdownMenu {
private Button mButton; private Button mButton;
private PopupMenu mPopupMenu; private PopupMenu mPopupMenu;
private Menu mMenu; private Menu mMenu;
public DropdownMenu(Context context, Button button, int menuId) { public DropdownMenu(Context context, Button button, int menuId) {
mButton = button; mButton = button;
mButton.setBackgroundResource(R.drawable.dropdown_icon); mButton.setBackgroundResource(R.drawable.dropdown_icon);
mPopupMenu = new PopupMenu(context, mButton); mPopupMenu = new PopupMenu(context, mButton);
mMenu = mPopupMenu.getMenu(); mMenu = mPopupMenu.getMenu();
mPopupMenu.getMenuInflater().inflate(menuId, mMenu); mPopupMenu.getMenuInflater().inflate(menuId, mMenu);
mButton.setOnClickListener(new OnClickListener() { mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) { public void onClick(View v) {
mPopupMenu.show(); mPopupMenu.show();
} }
}); });
} }
public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) { public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) {
if (mPopupMenu != null) { if (mPopupMenu != null) {
mPopupMenu.setOnMenuItemClickListener(listener); mPopupMenu.setOnMenuItemClickListener(listener);
} }
} }
public MenuItem findItem(int id) { public MenuItem findItem(int id) {
return mMenu.findItem(id); return mMenu.findItem(id);
} }
public void setTitle(CharSequence title) { public void setTitle(CharSequence title) {
mButton.setText(title); mButton.setText(title);
} }
} }

@ -14,66 +14,67 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.ui; package net.micode.notes.ui;
import android.content.Context; import android.content.Context;
import android.database.Cursor; import android.database.Cursor;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.CursorAdapter; import android.widget.CursorAdapter;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.TextView; import android.widget.TextView;
import net.micode.notes.R; import net.micode.notes.R;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns; 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, NoteColumns.ID,
NoteColumns.SNIPPET NoteColumns.SNIPPET
}; };
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;
public FoldersListAdapter(Context context, Cursor c) { public FoldersListAdapter(Context context, Cursor c) {
super(context, c); super(context, c);
} // TODO Auto-generated constructor stub
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) { @Override
return new FolderListItem(context); public View newView(Context context, Cursor cursor, ViewGroup parent) {
} return new FolderListItem(context);
}
@Override
public void bindView(View view, Context context, Cursor cursor) { @Override
if (view instanceof FolderListItem) { public void bindView(View view, Context context, Cursor cursor) {
String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context if (view instanceof FolderListItem) {
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
((FolderListItem) view).bind(folderName); .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
} ((FolderListItem) view).bind(folderName);
} }
}
public String getFolderName(Context context, int position) {
Cursor cursor = (Cursor) getItem(position); public String getFolderName(Context context, int position) {
return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context Cursor cursor = (Cursor) getItem(position);
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
} .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
}
private class FolderListItem extends LinearLayout {
private TextView mName; private class FolderListItem extends LinearLayout {
private TextView mName;
public FolderListItem(Context context) {
super(context); public FolderListItem(Context context) {
inflate(context, R.layout.folder_list_item, this); super(context);
mName = (TextView) findViewById(R.id.tv_folder_name); inflate(context, R.layout.folder_list_item, this);
} mName = (TextView) findViewById(R.id.tv_folder_name);
}
public void bind(String name) {
mName.setText(name); public void bind(String name) {
} mName.setText(name);
} }
}
}
}

File diff suppressed because it is too large Load Diff

@ -14,202 +14,204 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.ui; package net.micode.notes.ui;
import android.content.Context; import android.content.Context;
import android.graphics.Rect; import android.graphics.Rect;
import android.text.Layout; import android.text.Layout;
import android.text.Selection; import android.text.Selection;
import android.text.Spanned; import android.text.Spanned;
import android.text.TextUtils; import android.text.TextUtils;
import android.text.style.URLSpan; import android.text.style.URLSpan;
import android.util.AttributeSet; import android.util.AttributeSet;
import android.util.Log; import android.util.Log;
import android.view.ContextMenu; import android.view.ContextMenu;
import android.view.KeyEvent; import android.view.KeyEvent;
import android.view.MenuItem; import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener; import android.view.MenuItem.OnMenuItemClickListener;
import android.view.MotionEvent; import android.view.MotionEvent;
import android.widget.EditText; import android.widget.EditText;
import net.micode.notes.R; import net.micode.notes.R;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
public class NoteEditText extends EditText { public class NoteEditText extends EditText {
private static final String TAG = "NoteEditText"; private static final String TAG = "NoteEditText";
private int mIndex; private int mIndex;
private int mSelectionStartBeforeDelete; private int mSelectionStartBeforeDelete;
private static final String SCHEME_TEL = "tel:" ; private static final String SCHEME_TEL = "tel:" ;
private static final String SCHEME_HTTP = "http:" ; private static final String SCHEME_HTTP = "http:" ;
private static final String SCHEME_EMAIL = "mailto:" ; private static final String SCHEME_EMAIL = "mailto:" ;
private static final Map<String, Integer> sSchemaActionResMap = new HashMap<String, Integer>(); private static final Map<String, Integer> sSchemaActionResMap = new HashMap<String, Integer>();
static { static {
sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel); sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel);
sSchemaActionResMap.put(SCHEME_HTTP, R.string.note_link_web); sSchemaActionResMap.put(SCHEME_HTTP, R.string.note_link_web);
sSchemaActionResMap.put(SCHEME_EMAIL, R.string.note_link_email); sSchemaActionResMap.put(SCHEME_EMAIL, R.string.note_link_email);
} }
public interface OnTextViewChangeListener { /**
/** * Call by the {@link NoteEditActivity} to delete or add edit text
* Delete current edit text when {@link KeyEvent#KEYCODE_DEL} happens */
* and the text is null public interface OnTextViewChangeListener {
*/ /**
void onEditTextDelete(int index, String text); * Delete current edit text when {@link KeyEvent#KEYCODE_DEL} happens
* and the text is null
/** */
* Add edit text after current edit text when {@link KeyEvent#KEYCODE_ENTER} void onEditTextDelete(int index, String text);
* happen
*/ /**
void onEditTextEnter(int index, String text); * Add edit text after current edit text when {@link KeyEvent#KEYCODE_ENTER}
* happen
/** */
* Hide or show item option when text change void onEditTextEnter(int index, String text);
*/
void onTextChange(int index, boolean hasText); /**
} * Hide or show item option when text change
*/
private OnTextViewChangeListener mOnTextViewChangeListener; void onTextChange(int index, boolean hasText);
}
public NoteEditText(Context context) {
super(context, null); private OnTextViewChangeListener mOnTextViewChangeListener;
mIndex = 0;
} public NoteEditText(Context context) {
super(context, null);
public void setIndex(int index) { mIndex = 0;
mIndex = index; }
}
public void setIndex(int index) {
mIndex = index;
public void setOnTextViewChangeListener(OnTextViewChangeListener listener) { }
mOnTextViewChangeListener = listener;
} public void setOnTextViewChangeListener(OnTextViewChangeListener listener) {
mOnTextViewChangeListener = listener;
public NoteEditText(Context context, AttributeSet attrs) { }
super(context, attrs, android.R.attr.editTextStyle);
} public NoteEditText(Context context, AttributeSet attrs) {
super(context, attrs, android.R.attr.editTextStyle);
public NoteEditText(Context context, AttributeSet attrs, int defStyle) { }
super(context, attrs, defStyle);
// TODO Auto-generated construct or stub public NoteEditText(Context context, AttributeSet attrs, int defStyle) {
} super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
public boolean onTouchEvent(MotionEvent event) { }
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: @Override
int x = (int) event.getX(); public boolean onTouchEvent(MotionEvent event) {
int y = (int) event.getY(); switch (event.getAction()) {
x -= getTotalPaddingLeft(); case MotionEvent.ACTION_DOWN:
y -= getTotalPaddingTop();
x += getScrollX(); int x = (int) event.getX();
y += getScrollY(); int y = (int) event.getY();
x -= getTotalPaddingLeft();
Layout layout = getLayout(); y -= getTotalPaddingTop();
int line = layout.getLineForVertical(y); x += getScrollX();
int off = layout.getOffsetForHorizontal(line, x); y += getScrollY();
Selection.setSelection(getText(), off); Layout layout = getLayout();
break; int line = layout.getLineForVertical(y);
} int off = layout.getOffsetForHorizontal(line, x);
Selection.setSelection(getText(), off);
return super.onTouchEvent(event); break;
} }
@Override return super.onTouchEvent(event);
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) { @Override
case KeyEvent.KEYCODE_ENTER: public boolean onKeyDown(int keyCode, KeyEvent event) {
if (mOnTextViewChangeListener != null) { switch (keyCode) {
return false; case KeyEvent.KEYCODE_ENTER:
} if (mOnTextViewChangeListener != null) {
break; return false;
case KeyEvent.KEYCODE_DEL: }
mSelectionStartBeforeDelete = getSelectionStart(); break;
break; case KeyEvent.KEYCODE_DEL:
default: mSelectionStartBeforeDelete = getSelectionStart();
break; break;
} default:
return super.onKeyDown(keyCode, event); break;
} }
return super.onKeyDown(keyCode, event);
@Override }
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch(keyCode) { @Override
case KeyEvent.KEYCODE_DEL: public boolean onKeyUp(int keyCode, KeyEvent event) {
if (mOnTextViewChangeListener != null) { switch(keyCode) {
if (0 == mSelectionStartBeforeDelete && mIndex != 0) { case KeyEvent.KEYCODE_DEL:
mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString()); if (mOnTextViewChangeListener != null) {
return true; if (0 == mSelectionStartBeforeDelete && mIndex != 0) {
} mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString());
} else { return true;
Log.d(TAG, "OnTextViewChangeListener was not seted"); }
} } else {
break; Log.d(TAG, "OnTextViewChangeListener was not seted");
case KeyEvent.KEYCODE_ENTER: }
if (mOnTextViewChangeListener != null) { break;
int selectionStart = getSelectionStart(); case KeyEvent.KEYCODE_ENTER:
String text = getText().subSequence(selectionStart, length()).toString(); if (mOnTextViewChangeListener != null) {
setText(getText().subSequence(0, selectionStart)); int selectionStart = getSelectionStart();
mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text); String text = getText().subSequence(selectionStart, length()).toString();
} else { setText(getText().subSequence(0, selectionStart));
Log.d(TAG, "OnTextViewChangeListener was not seted"); mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text);
} } else {
break; Log.d(TAG, "OnTextViewChangeListener was not seted");
default: }
break; break;
} default:
return super.onKeyUp(keyCode, event); break;
} }
return super.onKeyUp(keyCode, event);
@Override }
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
if (mOnTextViewChangeListener != null) { @Override
if (!focused && TextUtils.isEmpty(getText())) { protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
mOnTextViewChangeListener.onTextChange(mIndex, false); if (mOnTextViewChangeListener != null) {
} else { if (!focused && TextUtils.isEmpty(getText())) {
mOnTextViewChangeListener.onTextChange(mIndex, true); mOnTextViewChangeListener.onTextChange(mIndex, false);
} } else {
} mOnTextViewChangeListener.onTextChange(mIndex, true);
super.onFocusChanged(focused, direction, previouslyFocusedRect); }
} }
super.onFocusChanged(focused, direction, previouslyFocusedRect);
@Override }
protected void onCreateContextMenu(ContextMenu menu) {
if (getText() instanceof Spanned) { @Override
int selStart = getSelectionStart(); protected void onCreateContextMenu(ContextMenu menu) {
int selEnd = getSelectionEnd(); if (getText() instanceof Spanned) {
int selStart = getSelectionStart();
int min = Math.min(selStart, selEnd); int selEnd = getSelectionEnd();
int max = Math.max(selStart, selEnd);
int min = Math.min(selStart, selEnd);
final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class); int max = Math.max(selStart, selEnd);
if (urls.length == 1) {
int defaultResId = 0; final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class);
for(String schema: sSchemaActionResMap.keySet()) { if (urls.length == 1) {
if(urls[0].getURL().indexOf(schema) >= 0) { int defaultResId = 0;
defaultResId = sSchemaActionResMap.get(schema); for(String schema: sSchemaActionResMap.keySet()) {
break; if(urls[0].getURL().indexOf(schema) >= 0) {
} defaultResId = sSchemaActionResMap.get(schema);
} break;
}
if (defaultResId == 0) { }
defaultResId = R.string.note_link_other;
} if (defaultResId == 0) {
defaultResId = R.string.note_link_other;
menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener( }
new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) { menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener(
// goto a new intent new OnMenuItemClickListener() {
urls[0].onClick(NoteEditText.this); public boolean onMenuItemClick(MenuItem item) {
return true; // goto a new intent
} urls[0].onClick(NoteEditText.this);
}); return true;
} }
} });
super.onCreateContextMenu(menu); }
} }
} super.onCreateContextMenu(menu);
}
}

@ -14,214 +14,211 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.ui; package net.micode.notes.ui;
import android.content.Context; import android.content.Context;
import android.database.Cursor; import android.database.Cursor;
import android.text.TextUtils; import android.text.TextUtils;
import net.micode.notes.data.Contact; import net.micode.notes.data.Contact;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.tool.DataUtils; import net.micode.notes.tool.DataUtils;
public class NoteItemData { public class NoteItemData {
static final String [] PROJECTION = new String [] { static final String [] PROJECTION = new String [] {
NoteColumns.ID, NoteColumns.ID,
NoteColumns.ALERTED_DATE, NoteColumns.ALERTED_DATE,
NoteColumns.BG_COLOR_ID, NoteColumns.BG_COLOR_ID,
NoteColumns.CREATED_DATE, NoteColumns.CREATED_DATE,
NoteColumns.HAS_ATTACHMENT, NoteColumns.HAS_ATTACHMENT,
NoteColumns.MODIFIED_DATE, NoteColumns.MODIFIED_DATE,
NoteColumns.NOTES_COUNT, NoteColumns.NOTES_COUNT,
NoteColumns.PARENT_ID, NoteColumns.PARENT_ID,
NoteColumns.SNIPPET, NoteColumns.SNIPPET,
NoteColumns.TYPE, NoteColumns.TYPE,
NoteColumns.WIDGET_ID, NoteColumns.WIDGET_ID,
NoteColumns.WIDGET_TYPE, NoteColumns.WIDGET_TYPE,
}; };
private static final int ID_COLUMN = 0; private static final int ID_COLUMN = 0;
private static final int ALERTED_DATE_COLUMN = 1; private static final int ALERTED_DATE_COLUMN = 1;
private static final int BG_COLOR_ID_COLUMN = 2; private static final int BG_COLOR_ID_COLUMN = 2;
private static final int CREATED_DATE_COLUMN = 3; private static final int CREATED_DATE_COLUMN = 3;
private static final int HAS_ATTACHMENT_COLUMN = 4; private static final int HAS_ATTACHMENT_COLUMN = 4;
private static final int MODIFIED_DATE_COLUMN = 5; private static final int MODIFIED_DATE_COLUMN = 5;
private static final int NOTES_COUNT_COLUMN = 6; private static final int NOTES_COUNT_COLUMN = 6;
private static final int PARENT_ID_COLUMN = 7; private static final int PARENT_ID_COLUMN = 7;
private static final int SNIPPET_COLUMN = 8; private static final int SNIPPET_COLUMN = 8;
private static final int TYPE_COLUMN = 9; private static final int TYPE_COLUMN = 9;
private static final int WIDGET_ID_COLUMN = 10; private static final int WIDGET_ID_COLUMN = 10;
private static final int WIDGET_TYPE_COLUMN = 11; private static final int WIDGET_TYPE_COLUMN = 11;
private long mId; private long mId;
private long mAlertDate; private long mAlertDate;
private int mBgColorId; private int mBgColorId;
private long mCreatedDate; private long mCreatedDate;
private boolean mHasAttachment; private boolean mHasAttachment;
private long mModifiedDate; private long mModifiedDate;
private int mNotesCount; private int mNotesCount;
private long mParentId; private long mParentId;
private String mSnippet; private String mSnippet;
private int mType; private int mType;
private int mWidgetId; private int mWidgetId;
private int mWidgetType; private int mWidgetType;
private String mName; private String mName;
private String mPhoneNumber; private String mPhoneNumber;
private boolean mIsLastItem; private boolean mIsLastItem;
private boolean mIsFirstItem; private boolean mIsFirstItem;
private boolean mIsOnlyOneItem; private boolean mIsOnlyOneItem;
private boolean mIsOneNoteFollowingFolder; private boolean mIsOneNoteFollowingFolder;
private boolean mIsMultiNotesFollowingFolder; private boolean mIsMultiNotesFollowingFolder;
public NoteItemData(Context context, Cursor cursor) {
public NoteItemData(Context context, Cursor cursor) {
mId = cursor.getLong(ID_COLUMN); mId = cursor.getLong(ID_COLUMN);
mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN); mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN);
mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN); mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN);
mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN); mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN);
mHasAttachment = (cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0) ? true : false; mHasAttachment = (cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0) ? true : false;
mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN); mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN);
mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN); mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN);
mParentId = cursor.getLong(PARENT_ID_COLUMN); mParentId = cursor.getLong(PARENT_ID_COLUMN);
mSnippet = cursor.getString(SNIPPET_COLUMN); mSnippet = cursor.getString(SNIPPET_COLUMN);
mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace( mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace(
NoteEditActivity.TAG_UNCHECKED, ""); NoteEditActivity.TAG_UNCHECKED, "");
mType = cursor.getInt(TYPE_COLUMN); mType = cursor.getInt(TYPE_COLUMN);
mWidgetId = cursor.getInt(WIDGET_ID_COLUMN); mWidgetId = cursor.getInt(WIDGET_ID_COLUMN);
mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN); mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN);
mPhoneNumber = "";
mPhoneNumber = ""; if (mParentId == Notes.ID_CALL_RECORD_FOLDER) {
if (mParentId == Notes.ID_CALL_RECORD_FOLDER) { mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId);
mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId); if (!TextUtils.isEmpty(mPhoneNumber)) {
if (!TextUtils.isEmpty(mPhoneNumber)) { mName = Contact.getContact(context, mPhoneNumber);
mName = Contact.getContact(context, mPhoneNumber); if (mName == null) {
if (mName == null) { mName = mPhoneNumber;
mName = mPhoneNumber; }
} }
} }
}
if (mName == null) {
if (mName == null) { mName = "";
mName = ""; }
} checkPostion(cursor);
checkPostion(cursor); }
}
private void checkPostion(Cursor cursor) {
private void checkPostion(Cursor cursor) { mIsLastItem = cursor.isLast() ? true : false;
mIsFirstItem = cursor.isFirst() ? true : false;
mIsLastItem = cursor.isLast() ? true : false; mIsOnlyOneItem = (cursor.getCount() == 1);
mIsFirstItem = cursor.isFirst() ? true : false; mIsMultiNotesFollowingFolder = false;
mIsOnlyOneItem = (cursor.getCount() == 1); mIsOneNoteFollowingFolder = false;
mIsMultiNotesFollowingFolder = false; if (mType == Notes.TYPE_NOTE && !mIsFirstItem) {
mIsOneNoteFollowingFolder = false; int position = cursor.getPosition();
if (cursor.moveToPrevious()) {
if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER
if (mType == Notes.TYPE_NOTE && !mIsFirstItem) { || cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) {
int position = cursor.getPosition(); if (cursor.getCount() > (position + 1)) {
if (cursor.moveToPrevious()) { mIsMultiNotesFollowingFolder = true;
if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER } else {
|| cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) { mIsOneNoteFollowingFolder = true;
if (cursor.getCount() > (position + 1)) { }
mIsMultiNotesFollowingFolder = true; }
} else { if (!cursor.moveToNext()) {
mIsOneNoteFollowingFolder = true; throw new IllegalStateException("cursor move to previous but can't move back");
} }
} }
if (!cursor.moveToNext()) { }
throw new IllegalStateException("cursor move to previous but can't move back"); }
}
} public boolean isOneFollowingFolder() {
} return mIsOneNoteFollowingFolder;
} }
public boolean isOneFollowingFolder() {
return mIsOneNoteFollowingFolder; public boolean isMultiFollowingFolder() {
} return mIsMultiNotesFollowingFolder;
}
public boolean isMultiFollowingFolder() {
return mIsMultiNotesFollowingFolder; public boolean isLast() {
} return mIsLastItem;
}
public boolean isLast() {
return mIsLastItem; public String getCallName() {
} return mName;
}
public String getCallName() {
return mName; public boolean isFirst() {
} return mIsFirstItem;
}
public boolean isFirst() {
return mIsFirstItem; public boolean isSingle() {
} return mIsOnlyOneItem;
}
public boolean isSingle() {
return mIsOnlyOneItem; public long getId() {
} return mId;
}
public long getId() {
return mId; public long getAlertDate() {
} return mAlertDate;
}
public long getAlertDate() {
return mAlertDate; public long getCreatedDate() {
} return mCreatedDate;
}
public long getCreatedDate() {
return mCreatedDate; public boolean hasAttachment() {
} return mHasAttachment;
}
public boolean hasAttachment() {
return mHasAttachment; public long getModifiedDate() {
} return mModifiedDate;
}
public long getModifiedDate() {
return mModifiedDate; public int getBgColorId() {
} return mBgColorId;
}
public int getBgColorId() {
return mBgColorId; public long getParentId() {
} return mParentId;
}
public long getParentId() {
return mParentId; public int getNotesCount() {
} return mNotesCount;
}
public int getNotesCount() {
return mNotesCount; public long getFolderId () {
} return mParentId;
}
public long getFolderId () {
return mParentId; public int getType() {
} return mType;
}
public int getType() {
return mType; public int getWidgetType() {
} return mWidgetType;
}
public int getWidgetType() {
return mWidgetType; public int getWidgetId() {
} return mWidgetId;
}
public int getWidgetId() {
return mWidgetId; public String getSnippet() {
} return mSnippet;
}
public String getSnippet() {
return mSnippet; public boolean hasAlert() {
} return (mAlertDate > 0);
}
public boolean hasAlert() {
return (mAlertDate > 0); public boolean isCallRecord() {
} return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber));
}
public boolean isCallRecord() {
return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber)); public static int getNoteType(Cursor cursor) {
} return cursor.getInt(TYPE_COLUMN);
}
public static int getNoteType(Cursor cursor) { }
return cursor.getInt(TYPE_COLUMN);
}
}

File diff suppressed because it is too large Load Diff

@ -14,189 +14,171 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.ui; package net.micode.notes.ui;
import android.content.Context; import android.content.Context;
import android.database.Cursor; import android.database.Cursor;
import android.util.Log; import android.util.Log;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.CursorAdapter; import android.widget.CursorAdapter;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes;
import java.util.Collection;
import java.util.Collection; import java.util.HashMap;
import java.util.HashMap; import java.util.HashSet;
import java.util.HashSet; import java.util.Iterator;
import java.util.Iterator;
public class NotesListAdapter extends CursorAdapter {
public class NotesListAdapter extends CursorAdapter { private static final String TAG = "NotesListAdapter";
private static final String TAG = "NotesListAdapter"; private Context mContext;
private Context mContext; private HashMap<Integer, Boolean> mSelectedIndex;
private HashMap<Integer, Boolean> mSelectedIndex; private int mNotesCount;
private int mNotesCount; private boolean mChoiceMode;
private boolean mChoiceMode;
public static class AppWidgetAttribute {
public static class AppWidgetAttribute { public int widgetId;
public int widgetId; public int widgetType;
public int widgetType; };
};
public NotesListAdapter(Context context) {
super(context, null);
public NotesListAdapter(Context context) { mSelectedIndex = new HashMap<Integer, Boolean>();
super(context, null); mContext = context;
mSelectedIndex = new HashMap<Integer, Boolean>(); mNotesCount = 0;
mContext = context; }
mNotesCount = 0;
} @Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
@Override return new NotesListItem(context);
}
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new NotesListItem(context); @Override
} public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof NotesListItem) {
NoteItemData itemData = new NoteItemData(context, cursor);
@Override ((NotesListItem) view).bind(context, itemData, mChoiceMode,
public void bindView(View view, Context context, Cursor cursor) { isSelectedItem(cursor.getPosition()));
if (view instanceof NotesListItem) { }
}
NoteItemData itemData = new NoteItemData(context, cursor);
((NotesListItem) view).bind(context, itemData, mChoiceMode, public void setCheckedItem(final int position, final boolean checked) {
isSelectedItem(cursor.getPosition())); mSelectedIndex.put(position, checked);
notifyDataSetChanged();
} }
}
public boolean isInChoiceMode() {
return mChoiceMode;
public void setCheckedItem(final int position, final boolean checked) { }
mSelectedIndex.put(position, checked);
public void setChoiceMode(boolean mode) {
notifyDataSetChanged(); mSelectedIndex.clear();
mChoiceMode = mode;
} }
public void selectAll(boolean checked) {
public boolean isInChoiceMode() { Cursor cursor = getCursor();
return mChoiceMode; for (int i = 0; i < getCount(); i++) {
} if (cursor.moveToPosition(i)) {
if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) {
setCheckedItem(i, checked);
public void setChoiceMode(boolean mode) { }
mSelectedIndex.clear(); }
mChoiceMode = mode; }
} }
public HashSet<Long> getSelectedItemIds() {
public void selectAll(boolean checked) { HashSet<Long> itemSet = new HashSet<Long>();
Cursor cursor = getCursor(); for (Integer position : mSelectedIndex.keySet()) {
for (int i = 0; i < getCount(); i++) { if (mSelectedIndex.get(position) == true) {
if (cursor.moveToPosition(i)) { Long id = getItemId(position);
if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) { if (id == Notes.ID_ROOT_FOLDER) {
setCheckedItem(i, checked); Log.d(TAG, "Wrong item id, should not happen");
} } else {
} itemSet.add(id);
} }
} }
}
public HashSet<Long> getSelectedItemIds() { return itemSet;
HashSet<Long> itemSet = new HashSet<Long>(); }
for (Integer position : mSelectedIndex.keySet()) { public HashSet<AppWidgetAttribute> getSelectedWidget() {
if (mSelectedIndex.get(position) == true) { HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>();
Long id = getItemId(position); for (Integer position : mSelectedIndex.keySet()) {
if (id == Notes.ID_ROOT_FOLDER) { if (mSelectedIndex.get(position) == true) {
Log.d(TAG, "Wrong item id, should not happen"); Cursor c = (Cursor) getItem(position);
} else { if (c != null) {
itemSet.add(id); AppWidgetAttribute widget = new AppWidgetAttribute();
} NoteItemData item = new NoteItemData(mContext, c);
} widget.widgetId = item.getWidgetId();
} widget.widgetType = item.getWidgetType();
itemSet.add(widget);
return itemSet; /**
} * Don't close cursor here, only the adapter could close it
*/
} else {
public HashSet<AppWidgetAttribute> getSelectedWidget() { Log.e(TAG, "Invalid cursor");
HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>(); return null;
for (Integer position : mSelectedIndex.keySet()) { }
if (mSelectedIndex.get(position) == true) { }
Cursor c = (Cursor) getItem(position); }
if (c != null) { return itemSet;
AppWidgetAttribute widget = new AppWidgetAttribute(); }
NoteItemData item = new NoteItemData(mContext, c);
widget.widgetId = item.getWidgetId(); public int getSelectedCount() {
widget.widgetType = item.getWidgetType(); Collection<Boolean> values = mSelectedIndex.values();
itemSet.add(widget); if (null == values) {
} else { return 0;
Log.e(TAG, "Invalid cursor"); }
return null; Iterator<Boolean> iter = values.iterator();
} int count = 0;
} while (iter.hasNext()) {
} if (true == iter.next()) {
return itemSet; count++;
} }
}
public int getSelectedCount() { return count;
Collection<Boolean> values = mSelectedIndex.values(); }
if (null == values) {
return 0; public boolean isAllSelected() {
} int checkedCount = getSelectedCount();
Iterator<Boolean> iter = values.iterator(); return (checkedCount != 0 && checkedCount == mNotesCount);
int count = 0; }
while (iter.hasNext()) {
if (true == iter.next()) { public boolean isSelectedItem(final int position) {
count++; if (null == mSelectedIndex.get(position)) {
} return false;
} }
return count; return mSelectedIndex.get(position);
} }
@Override
public boolean isAllSelected() { protected void onContentChanged() {
int checkedCount = getSelectedCount(); super.onContentChanged();
return (checkedCount != 0 && checkedCount == mNotesCount); calcNotesCount();
} }
@Override
public boolean isSelectedItem(final int position) { public void changeCursor(Cursor cursor) {
if (null == mSelectedIndex.get(position)) { super.changeCursor(cursor);
return false; calcNotesCount();
} }
return mSelectedIndex.get(position);
} private void calcNotesCount() {
mNotesCount = 0;
@Override for (int i = 0; i < getCount(); i++) {
Cursor c = (Cursor) getItem(i);
if (c != null) {
protected void onContentChanged() { if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) {
super.onContentChanged(); mNotesCount++;
}
calcNotesCount(); } else {
} Log.e(TAG, "Invalid cursor");
return;
@Override }
public void changeCursor(Cursor cursor) { }
super.changeCursor(cursor); }
calcNotesCount(); }
}
private void calcNotesCount() {
mNotesCount = 0;
for (int i = 0; i < getCount(); i++) {
Cursor c = (Cursor) getItem(i);
if (c != null) {
if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) {
mNotesCount++;
}
} else {
Log.e(TAG, "Invalid cursor");
return;
}
}
}
}

@ -14,118 +14,109 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.ui; package net.micode.notes.ui;
import android.content.Context;
import android.text.format.DateUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.ResourceParser.NoteItemBgResources;
public class NotesListItem extends LinearLayout { import android.content.Context;
private ImageView mAlert; import android.text.format.DateUtils;
private TextView mTitle; import android.view.View;
private TextView mTime; import android.widget.CheckBox;
private TextView mCallName; import android.widget.ImageView;
private NoteItemData mItemData; import android.widget.LinearLayout;
private CheckBox mCheckBox; import android.widget.TextView;
public NotesListItem(Context context) { import net.micode.notes.R;
super(context); import net.micode.notes.data.Notes;
inflate(context, R.layout.note_item, this); import net.micode.notes.tool.DataUtils;
mAlert = (ImageView) findViewById(R.id.iv_alert_icon); import net.micode.notes.tool.ResourceParser.NoteItemBgResources;
mTitle = (TextView) findViewById(R.id.tv_title);
mTime = (TextView) findViewById(R.id.tv_time);
mCallName = (TextView) findViewById(R.id.tv_name);
mCheckBox = (CheckBox) findViewById(android.R.id.checkbox);
}
public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) {
if (choiceMode && data.getType() == Notes.TYPE_NOTE) {
mCheckBox.setVisibility(View.VISIBLE);
mCheckBox.setChecked(checked);
} else {
mCheckBox.setVisibility(View.GONE);
}
mItemData = data;
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { public class NotesListItem extends LinearLayout {
mCallName.setVisibility(View.GONE); private ImageView mAlert;
mAlert.setVisibility(View.VISIBLE); private TextView mTitle;
private TextView mTime;
private TextView mCallName;
private NoteItemData mItemData;
private CheckBox mCheckBox;
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); public NotesListItem(Context context) {
super(context);
inflate(context, R.layout.note_item, this);
mAlert = (ImageView) findViewById(R.id.iv_alert_icon);
mTitle = (TextView) findViewById(R.id.tv_title);
mTime = (TextView) findViewById(R.id.tv_time);
mCallName = (TextView) findViewById(R.id.tv_name);
mCheckBox = (CheckBox) findViewById(android.R.id.checkbox);
}
mTitle.setText(context.getString(R.string.call_record_folder_name) public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) {
+ context.getString(R.string.format_folder_files_count, data.getNotesCount())); if (choiceMode && data.getType() == Notes.TYPE_NOTE) {
mAlert.setImageResource(R.drawable.call_record); mCheckBox.setVisibility(View.VISIBLE);
} else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) { mCheckBox.setChecked(checked);
mCallName.setVisibility(View.VISIBLE); } else {
mCallName.setText(data.getCallName()); mCheckBox.setVisibility(View.GONE);
mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem); }
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
if (data.hasAlert()) { mItemData = data;
mAlert.setImageResource(R.drawable.clock); if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
mAlert.setVisibility(View.VISIBLE); mCallName.setVisibility(View.GONE);
} else { mAlert.setVisibility(View.VISIBLE);
mAlert.setVisibility(View.GONE); mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
} mTitle.setText(context.getString(R.string.call_record_folder_name)
} else { + context.getString(R.string.format_folder_files_count, data.getNotesCount()));
mCallName.setVisibility(View.GONE); mAlert.setImageResource(R.drawable.call_record);
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); } else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) {
mCallName.setVisibility(View.VISIBLE);
mCallName.setText(data.getCallName());
mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem);
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock);
mAlert.setVisibility(View.VISIBLE);
} else {
mAlert.setVisibility(View.GONE);
}
} else {
mCallName.setVisibility(View.GONE);
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
if (data.getType() == Notes.TYPE_FOLDER) { if (data.getType() == Notes.TYPE_FOLDER) {
mTitle.setText(data.getSnippet() mTitle.setText(data.getSnippet()
+ context.getString(R.string.format_folder_files_count, + context.getString(R.string.format_folder_files_count,
data.getNotesCount())); data.getNotesCount()));
mAlert.setVisibility(View.GONE); mAlert.setVisibility(View.GONE);
} else { } else {
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
if (data.hasAlert()) { if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock); mAlert.setImageResource(R.drawable.clock);
mAlert.setVisibility(View.VISIBLE); mAlert.setVisibility(View.VISIBLE);
} else { } else {
mAlert.setVisibility(View.GONE); mAlert.setVisibility(View.GONE);
} }
} }
} }
mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate()));
mTime. setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate())); setBackground(data);
}
setBackground(data);
}
private void setBackground(NoteItemData data) { private void setBackground(NoteItemData data) {
int id = data.getBgColorId(); int id = data.getBgColorId();
if (data.getType() == Notes.TYPE_NOTE) {
if (data.isSingle() || data.isOneFollowingFolder()) {
setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id));
} else if (data.isLast()) {
setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id));
} else if (data.isFirst() || data.isMultiFollowingFolder()) {
setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id));
} else {
setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id));
}
} else {
setBackgroundResource(NoteItemBgResources.getFolderBgRes());
}
}
if (data.getType() == Notes.TYPE_NOTE) { public NoteItemData getItemData() {
return mItemData;
if (data.isSingle() || data.isOneFollowingFolder()) { }
setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id)); }
} else if (data.isLast()) {
setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id));
} else if (data.isFirst() || data.isMultiFollowingFolder()) {
setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id));
} else {
setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id));
}
} else {
setBackgroundResource(NoteItemBgResources.getFolderBgRes());
}
}
public NoteItemData getItemData() {
return mItemData;
}
}

@ -14,409 +14,375 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.ui; package net.micode.notes.ui;
import android.accounts.Account; import android.accounts.Account;
import android.accounts.AccountManager; import android.accounts.AccountManager;
import android.app.ActionBar; import android.app.ActionBar;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.content.BroadcastReceiver; import android.content.BroadcastReceiver;
import android.content.ContentValues; import android.content.ContentValues;
import android.content.Context; import android.content.Context;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.Intent; import android.content.Intent;
import android.content.IntentFilter; import android.content.IntentFilter;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.os.Bundle; import android.os.Bundle;
import android.preference.Preference; import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener; import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity; import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory; import android.preference.PreferenceCategory;
import android.text.TextUtils; import android.text.TextUtils;
import android.text.format.DateFormat; import android.text.format.DateFormat;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.Menu; import android.view.Menu;
import android.view.MenuItem; import android.view.MenuItem;
import android.view.View; import android.view.View;
import android.widget.Button; import android.widget.Button;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import net.micode.notes.R; import net.micode.notes.R;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.remote.GTaskSyncService; import net.micode.notes.gtask.remote.GTaskSyncService;
public class NotesPreferenceActivity extends PreferenceActivity { public class NotesPreferenceActivity extends PreferenceActivity {
public static final String PREFERENCE_NAME = "notes_preferences"; public static final String PREFERENCE_NAME = "notes_preferences";
public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name"; public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name";
public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time"; public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time";
public static final String PREFERENCE_SET_BG_COLOR_KEY = "pref_key_bg_random_appear"; public static final String PREFERENCE_SET_BG_COLOR_KEY = "pref_key_bg_random_appear";
private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key"; private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key";
private static final String AUTHORITIES_FILTER_KEY = "authorities"; private static final String AUTHORITIES_FILTER_KEY = "authorities";
private PreferenceCategory mAccountCategory; private PreferenceCategory mAccountCategory;
private GTaskReceiver mReceiver; private GTaskReceiver mReceiver;
private Account[] mOriAccounts; private Account[] mOriAccounts;
private boolean mHasAddedAccount; private boolean mHasAddedAccount;
@Override
@Override protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
protected void onCreate(Bundle icicle) {
/* using the app icon for navigation */
super.onCreate(icicle); getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true); addPreferencesFromResource(R.xml.preferences);
mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY);
addPreferencesFromResource(R.xml.preferences); mReceiver = new GTaskReceiver();
IntentFilter filter = new IntentFilter();
mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY); filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME);
mReceiver = new GTaskReceiver(); registerReceiver(mReceiver, filter);
IntentFilter filter = new IntentFilter();
filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME); mOriAccounts = null;
registerReceiver(mReceiver, filter); View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null);
getListView().addHeaderView(header, null, true);
mOriAccounts = null; }
View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null);
getListView().addHeaderView(header, null, true); @Override
} protected void onResume() {
super.onResume();
@Override
// need to set sync account automatically if user has added a new
protected void onResume() { // account
if (mHasAddedAccount) {
super.onResume(); Account[] accounts = getGoogleAccounts();
if (mOriAccounts != null && accounts.length > mOriAccounts.length) {
if (mHasAddedAccount) { for (Account accountNew : accounts) {
boolean found = false;
Account[] accounts = getGoogleAccounts(); for (Account accountOld : mOriAccounts) {
if (TextUtils.equals(accountOld.name, accountNew.name)) {
if (mOriAccounts != null && accounts.length > mOriAccounts.length) { found = true;
for (Account accountNew : accounts) { break;
boolean found = false; }
for (Account accountOld : mOriAccounts) { }
if (TextUtils.equals(accountOld.name, accountNew.name)) { if (!found) {
found = true; setSyncAccount(accountNew.name);
break; break;
} }
} }
if (!found) { }
setSyncAccount(accountNew.name); }
break;
} refreshUI();
} }
}
} @Override
protected void onDestroy() {
refreshUI(); if (mReceiver != null) {
unregisterReceiver(mReceiver);
} }
super.onDestroy();
@Override }
protected void onDestroy() { private void loadAccountPreference() {
if (mReceiver != null) { mAccountCategory.removeAll();
unregisterReceiver(mReceiver);
} Preference accountPref = new Preference(this);
super.onDestroy(); final String defaultAccount = getSyncAccountName(this);
accountPref.setTitle(getString(R.string.preferences_account_title));
} accountPref.setSummary(getString(R.string.preferences_account_summary));
accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
private void loadAccountPreference() { public boolean onPreferenceClick(Preference preference) {
mAccountCategory.removeAll(); if (!GTaskSyncService.isSyncing()) {
if (TextUtils.isEmpty(defaultAccount)) {
Preference accountPref = new Preference(this); // the first time to set account
showSelectAccountAlertDialog();
final String defaultAccount = getSyncAccountName(this); } else {
accountPref.setTitle(getString(R.string.preferences_account_title)); // if the account has already been set, we need to promp
accountPref.setSummary(getString(R.string.preferences_account_summary)); // user about the risk
showChangeAccountConfirmAlertDialog();
accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() { }
public boolean onPreferenceClick(Preference preference) { } else {
Toast.makeText(NotesPreferenceActivity.this,
if (!GTaskSyncService.isSyncing()) { R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT)
if (TextUtils.isEmpty(defaultAccount)) { .show();
showSelectAccountAlertDialog(); }
} else { return true;
showChangeAccountConfirmAlertDialog(); }
} });
} else {
Toast.makeText(NotesPreferenceActivity.this, mAccountCategory.addPreference(accountPref);
R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT) }
.show();
} private void loadSyncButton() {
return true; Button syncButton = (Button) findViewById(R.id.preference_sync_button);
} TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
});
// set button state
mAccountCategory.addPreference(accountPref); if (GTaskSyncService.isSyncing()) {
} syncButton.setText(getString(R.string.preferences_button_sync_cancel));
syncButton.setOnClickListener(new View.OnClickListener() {
private void loadSyncButton() { public void onClick(View v) {
Button syncButton = (Button) findViewById(R.id.preference_sync_button); GTaskSyncService.cancelSync(NotesPreferenceActivity.this);
TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview); }
if (GTaskSyncService.isSyncing()) { });
} else {
syncButton.setText(getString(R.string.preferences_button_sync_cancel)); syncButton.setText(getString(R.string.preferences_button_sync_immediately));
syncButton.setOnClickListener(new View.OnClickListener() { syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { public void onClick(View v) {
GTaskSyncService.cancelSync(NotesPreferenceActivity.this); GTaskSyncService.startSync(NotesPreferenceActivity.this);
} }
}); });
}
} else { syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this)));
syncButton.setText(getString(R.string.preferences_button_sync_immediately));
syncButton.setOnClickListener(new View.OnClickListener() { // set last sync time
public void onClick(View v) { if (GTaskSyncService.isSyncing()) {
GTaskSyncService.startSync(NotesPreferenceActivity.this); lastSyncTimeView.setText(GTaskSyncService.getProgressString());
} lastSyncTimeView.setVisibility(View.VISIBLE);
}); } else {
long lastSyncTime = getLastSyncTime(this);
} if (lastSyncTime != 0) {
syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this))); lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time,
DateFormat.format(getString(R.string.preferences_last_sync_time_format),
if (GTaskSyncService.isSyncing()) { lastSyncTime)));
lastSyncTimeView.setText(GTaskSyncService.getProgressString()); lastSyncTimeView.setVisibility(View.VISIBLE);
lastSyncTimeView.setVisibility(View.VISIBLE); } else {
lastSyncTimeView.setVisibility(View.GONE);
} else { }
}
long lastSyncTime = getLastSyncTime(this); }
if (lastSyncTime != 0) {
lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time, private void refreshUI() {
DateFormat.format(getString(R.string.preferences_last_sync_time_format), loadAccountPreference();
lastSyncTime))); loadSyncButton();
lastSyncTimeView.setVisibility(View.VISIBLE); }
} else { private void showSelectAccountAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
lastSyncTimeView.setVisibility(View.GONE);
} View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
} TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
} titleTextView.setText(getString(R.string.preferences_dialog_select_account_title));
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
private void refreshUI() { subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips));
loadAccountPreference();
loadSyncButton(); dialogBuilder.setCustomTitle(titleView);
} dialogBuilder.setPositiveButton(null, null);
private void showSelectAccountAlertDialog() { Account[] accounts = getGoogleAccounts();
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); String defAccount = getSyncAccountName(this);
mOriAccounts = accounts;
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); mHasAddedAccount = false;
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_select_account_title)); if (accounts.length > 0) {
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle); CharSequence[] items = new CharSequence[accounts.length];
subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips)); final CharSequence[] itemMapping = items;
int checkedItem = -1;
dialogBuilder.setCustomTitle(titleView); int index = 0;
dialogBuilder.setPositiveButton(null, null); for (Account account : accounts) {
if (TextUtils.equals(account.name, defAccount)) {
Account[] accounts = getGoogleAccounts(); checkedItem = index;
String defAccount = getSyncAccountName(this); }
items[index++] = account.name;
mOriAccounts = accounts; }
mHasAddedAccount = false; dialogBuilder.setSingleChoiceItems(items, checkedItem,
new DialogInterface.OnClickListener() {
if (accounts.length > 0) { public void onClick(DialogInterface dialog, int which) {
CharSequence[] items = new CharSequence[accounts.length]; setSyncAccount(itemMapping[which].toString());
final CharSequence[] itemMapping = items; dialog.dismiss();
int checkedItem = -1; refreshUI();
int index = 0; }
for (Account account : accounts) { });
if (TextUtils.equals(account.name, defAccount)) { }
checkedItem = index;
} View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null);
items[index++] = account.name; dialogBuilder.setView(addAccountView);
}
dialogBuilder.setSingleChoiceItems(items, checkedItem, final AlertDialog dialog = dialogBuilder.show();
new DialogInterface.OnClickListener() { addAccountView.setOnClickListener(new View.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { public void onClick(View v) {
setSyncAccount(itemMapping[which].toString()); mHasAddedAccount = true;
dialog.dismiss(); Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
refreshUI(); intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] {
} "gmail-ls"
}); });
} startActivityForResult(intent, -1);
dialog.dismiss();
View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null); }
dialogBuilder.setView(addAccountView); });
}
final AlertDialog dialog = dialogBuilder.show();
addAccountView.setOnClickListener(new View.OnClickListener() { private void showChangeAccountConfirmAlertDialog() {
public void onClick(View v) { AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
mHasAddedAccount = true;
Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS"); View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] { TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
"gmail-ls" titleTextView.setText(getString(R.string.preferences_dialog_change_account_title,
}); getSyncAccountName(this)));
startActivityForResult(intent, -1); TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg));
dialog.dismiss(); dialogBuilder.setCustomTitle(titleView);
}
}); CharSequence[] menuItemArray = new CharSequence[] {
getString(R.string.preferences_menu_change_account),
} getString(R.string.preferences_menu_remove_account),
getString(R.string.preferences_menu_cancel)
private void showChangeAccountConfirmAlertDialog() { };
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); if (which == 0) {
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title); showSelectAccountAlertDialog();
titleTextView.setText(getString(R.string.preferences_dialog_change_account_title, } else if (which == 1) {
getSyncAccountName(this))); removeSyncAccount();
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle); refreshUI();
subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg)); }
}
dialogBuilder.setCustomTitle(titleView); });
dialogBuilder.show();
CharSequence[] menuItemArray = new CharSequence[] { }
getString(R.string.preferences_menu_change_account),
getString(R.string.preferences_menu_remove_account), private Account[] getGoogleAccounts() {
getString(R.string.preferences_menu_cancel) AccountManager accountManager = AccountManager.get(this);
}; return accountManager.getAccountsByType("com.google");
}
dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { private void setSyncAccount(String account) {
if (!getSyncAccountName(this).equals(account)) {
if (which == 0) { SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
showSelectAccountAlertDialog(); SharedPreferences.Editor editor = settings.edit();
} else if (which == 1) { if (account != null) {
removeSyncAccount(); editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account);
refreshUI(); } else {
} editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
} }
}); editor.commit();
dialogBuilder.show();
// clean up last sync time
} setLastSyncTime(this, 0);
// clean up local gtask related info
private Account[] getGoogleAccounts() { new Thread(new Runnable() {
AccountManager accountManager = AccountManager.get(this); public void run() {
return accountManager.getAccountsByType("com.google"); ContentValues values = new ContentValues();
} values.put(NoteColumns.GTASK_ID, "");
values.put(NoteColumns.SYNC_ID, 0);
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
private void setSyncAccount(String account) { }
if (!getSyncAccountName(this).equals(account)) { }).start();
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit(); Toast.makeText(NotesPreferenceActivity.this,
getString(R.string.preferences_toast_success_set_accout, account),
if (account != null) { Toast.LENGTH_SHORT).show();
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account); }
} else { }
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
} private void removeSyncAccount() {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.commit(); if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) {
editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME);
setLastSyncTime(this, 0); }
if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) {
new Thread(new Runnable() { editor.remove(PREFERENCE_LAST_SYNC_TIME);
public void run() { }
ContentValues values = new ContentValues(); editor.commit();
values.put(NoteColumns.GTASK_ID, "");
values.put(NoteColumns.SYNC_ID, 0); // clean up local gtask related info
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null); new Thread(new Runnable() {
} public void run() {
}).start(); ContentValues values = new ContentValues();
values.put(NoteColumns.GTASK_ID, "");
values.put(NoteColumns.SYNC_ID, 0);
Toast.makeText(NotesPreferenceActivity.this, getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
getString(R.string.preferences_toast_success_set_accout, account), }
Toast.LENGTH_SHORT).show(); }).start();
}
}
} public static String getSyncAccountName(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
private void removeSyncAccount() { Context.MODE_PRIVATE);
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
SharedPreferences.Editor editor = settings.edit(); }
if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) { public static void setLastSyncTime(Context context, long time) {
editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME); SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
} Context.MODE_PRIVATE);
if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) { SharedPreferences.Editor editor = settings.edit();
editor.remove(PREFERENCE_LAST_SYNC_TIME); editor.putLong(PREFERENCE_LAST_SYNC_TIME, time);
} editor.commit();
editor.commit(); }
public static long getLastSyncTime(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
new Thread(new Runnable() { Context.MODE_PRIVATE);
public void run() { return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0);
ContentValues values = new ContentValues(); }
values.put(NoteColumns.GTASK_ID, "");
values.put(NoteColumns.SYNC_ID, 0); private class GTaskReceiver extends BroadcastReceiver {
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
} @Override
}).start(); public void onReceive(Context context, Intent intent) {
refreshUI();
} if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) {
TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
syncStatus.setText(intent
public static String getSyncAccountName(Context context) { .getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG));
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, }
Context.MODE_PRIVATE);
return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); }
} }
public boolean onOptionsItemSelected(MenuItem item) {
public static void setLastSyncTime(Context context, long time) { switch (item.getItemId()) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, case android.R.id.home:
Context.MODE_PRIVATE); Intent intent = new Intent(this, NotesListActivity.class);
SharedPreferences.Editor editor = settings.edit(); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
editor.putLong(PREFERENCE_LAST_SYNC_TIME, time); return true;
editor.commit(); default:
return false;
} }
}
public static long getLastSyncTime(Context context) { }
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0);
}
private class GTaskReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
refreshUI();
if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) {
TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
syncStatus.setText(intent
.getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG));
}
}
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(this, NotesListActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
default:
return false;
}
}
}

@ -46,7 +46,6 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider {
private static final String TAG = "NoteWidgetProvider"; private static final String TAG = "NoteWidgetProvider";
@Override @Override
//小组件被删除时被调用
public void onDeleted(Context context, int[] appWidgetIds) { public void onDeleted(Context context, int[] appWidgetIds) {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
@ -58,8 +57,6 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider {
} }
} }
//用于查询与给定小组件ID相关的笔记信息并返回一个Cursor对象
private Cursor getNoteWidgetInfo(Context context, int widgetId) { private Cursor getNoteWidgetInfo(Context context, int widgetId) {
return context.getContentResolver().query(Notes.CONTENT_NOTE_URI, return context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
PROJECTION, PROJECTION,
@ -72,8 +69,6 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider {
update(context, appWidgetManager, appWidgetIds, false); update(context, appWidgetManager, appWidgetIds, false);
} }
//根据查询结果设置小组件的背景资源、文本内容和点击意图并通过AppWidgetManager的updateAppWidget方法更新小组件的视图
private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds, private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds,
boolean privacyMode) { boolean privacyMode) {
for (int i = 0; i < appWidgetIds.length; i++) { for (int i = 0; i < appWidgetIds.length; i++) {
@ -111,7 +106,6 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider {
/** /**
* Generate the pending intent to start host for the widget * Generate the pending intent to start host for the widget
*/ */
//根据小组件ID查询对应的笔记信息并根据查询结果设置相应的视图内容。如果查询结果为空则显示默认的提示文本和插入/编辑操作的意图
PendingIntent pendingIntent = null; PendingIntent pendingIntent = null;
if (privacyMode) { if (privacyMode) {
rv.setTextViewText(R.id.widget_text, rv.setTextViewText(R.id.widget_text,

@ -23,10 +23,9 @@ import net.micode.notes.R;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.tool.ResourceParser; import net.micode.notes.tool.ResourceParser;
//NoteWidgetProvider_2x类继承自NoteWidgetProvider并覆盖了其中的一些方法
public class NoteWidgetProvider_2x extends NoteWidgetProvider { public class NoteWidgetProvider_2x extends NoteWidgetProvider {
@Override @Override
//小组件需要更新时被调用。它调用父类的update方法并传入相应的参数。
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.update(context, appWidgetManager, appWidgetIds); super.update(context, appWidgetManager, appWidgetIds);
} }
@ -37,13 +36,11 @@ public class NoteWidgetProvider_2x extends NoteWidgetProvider {
} }
@Override @Override
//根据给定的背景ID返回相应的背景资源ID。这里调用了ResourceParser类的静态方法getWidget2xBgResource来获取2x小组件的背景资源ID。
protected int getBgResourceId(int bgId) { protected int getBgResourceId(int bgId) {
return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId); return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId);
} }
@Override @Override
//返回小组件的类型
protected int getWidgetType() { protected int getWidgetType() {
return Notes.TYPE_WIDGET_2X; return Notes.TYPE_WIDGET_2X;
} }

@ -23,7 +23,7 @@ import net.micode.notes.R;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.tool.ResourceParser; import net.micode.notes.tool.ResourceParser;
//跟Provider_2x一模一样类名字不同
public class NoteWidgetProvider_4x extends NoteWidgetProvider { public class NoteWidgetProvider_4x extends NoteWidgetProvider {
@Override @Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

Loading…
Cancel
Save