Compare commits

..

2 Commits
yyt ... master

Author SHA1 Message Date
LIUYANG 5a94d9ca40 2024/12/29 上传泛读报告
1 year ago
LIUYANG d338efde66 2024/12/29 添加泛读报告
1 year ago

@ -14,138 +14,145 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.ui; // 定义了该类的包路径 package net.micode.notes.ui;
import android.app.Activity; // 导入Activity类用于创建Android活动 import android.app.Activity;
import android.app.AlertDialog; // 导入AlertDialog类用于创建对话框 import android.app.AlertDialog;
import android.content.Context; // 导入Context类用于获取应用程序环境 import android.content.Context;
import android.content.DialogInterface; // 导入DialogInterface类用于处理对话框事件 import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener; // 导入OnClickListener接口用于处理对话框按钮点击事件 import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnDismissListener; // 导入OnDismissListener接口用于处理对话框关闭事件 import android.content.DialogInterface.OnDismissListener;
import android.content.Intent; // 导入Intent类用于启动活动和传递数据 import android.content.Intent;
import android.media.AudioManager; // 导入AudioManager类用于管理音频设置 import android.media.AudioManager;
import android.media.MediaPlayer; // 导入MediaPlayer类用于播放音频 import android.media.MediaPlayer;
import android.media.RingtoneManager; // 导入RingtoneManager类用于获取铃声 import android.media.RingtoneManager;
import android.net.Uri; // 导入Uri类用于表示资源路径 import android.net.Uri;
import android.os.Bundle; // 导入Bundle类用于保存活动状态 import android.os.Bundle;
import android.os.PowerManager; // 导入PowerManager类用于管理电源设置 import android.os.PowerManager;
import android.provider.Settings; // 导入Settings类用于获取系统设置 import android.provider.Settings;
import android.view.Window; // 导入Window类用于管理窗口 import android.view.Window;
import android.view.WindowManager; // 导入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; // 导入IOException类用于处理输入输出异常 import java.io.IOException;
public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener { // 定义AlarmAlertActivity类继承自Activity并实现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;
private MediaPlayer mPlayer; // 定义用于播放提醒声音的MediaPlayer对象 private static final int SNIPPET_PREW_MAX_LEN = 60;
MediaPlayer mPlayer;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { // 重写onCreate方法在活动创建时调用 protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // 调用父类的onCreate方法 super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); // 请求无标题的窗口 requestWindowFeature(Window.FEATURE_NO_TITLE);
final Window win = getWindow(); // 获取当前窗口 final Window win = getWindow();
win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); // 设置窗口在锁屏时显示 win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
if (!isScreenOn()) { // 检查屏幕是否处于打开状态
win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON // 保持屏幕唤醒 if (!isScreenOn()) {
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON // 打开屏幕 win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON // 允许在屏幕打开时锁定 | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
| WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR); // 布局插入装饰 | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
| WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR);
} }
Intent intent = getIntent(); // 获取启动该活动的意图 Intent intent = getIntent();
try { try {
mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1)); // 从意图中获取笔记ID mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1));
mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId); // 获取笔记内容的简短预览 mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId);
mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0, // 如果预览文本长度超过最大长度,则截取 mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0,
SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info) SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info)
: mSnippet; // 否则使用原始预览文本 : mSnippet;
} catch (IllegalArgumentException e) { // 捕获非法参数异常 } catch (IllegalArgumentException e) {
e.printStackTrace(); // 打印异常信息 e.printStackTrace();
return; // 返回 return;
} }
mPlayer = new MediaPlayer(); // 创建MediaPlayer对象 mPlayer = new MediaPlayer();
if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) { // 检查笔记在数据库中是否可见 if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) {
showActionDialog(); // 显示动作对话框 showActionDialog();
playAlarmSound(); // 播放提醒声音 playAlarmSound();
} else { } else {
finish(); // 结束活动 finish();
} }
} }
private boolean isScreenOn() { // 定义检查屏幕是否处于打开状态的方法 private boolean isScreenOn() {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); // 获取电源管理服务 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
return pm.isScreenOn(); // 返回屏幕是否处于打开状态 return pm.isScreenOn();
} }
private void playAlarmSound() { // 定义播放提醒声音的方法 private void playAlarmSound() {
Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM); // 获取默认的闹钟铃声URI Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);
int silentModeStreams = Settings.System.getInt(getContentResolver(), // 获取静音模式下影响的音频流 int silentModeStreams = Settings.System.getInt(getContentResolver(),
Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0); Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);
if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) { // 检查闹钟音频流是否受静音模式影响 if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) {
mPlayer.setAudioStreamType(silentModeStreams); // 设置音频流类型 mPlayer.setAudioStreamType(silentModeStreams);
} else { } else {
mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); // 设置音频流类型为闹钟 mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
} }
try { try {
mPlayer.setDataSource(this, url); // 设置数据源 mPlayer.setDataSource(this, url);
mPlayer.prepare(); // 准备播放 mPlayer.prepare();
mPlayer.setLooping(true); // 设置循环播放 mPlayer.setLooping(true);
mPlayer.start(); // 开始播放 mPlayer.start();
} catch (IllegalArgumentException e) { // 捕获非法参数异常 } catch (IllegalArgumentException e) {
e.printStackTrace(); // 打印异常信息 // TODO Auto-generated catch block
} catch (SecurityException e) { // 捕获安全异常 e.printStackTrace();
e.printStackTrace(); // 打印异常信息 } catch (SecurityException e) {
} catch (IllegalStateException e) { // 捕获非法状态异常 // TODO Auto-generated catch block
e.printStackTrace(); // 打印异常信息 e.printStackTrace();
} catch (IOException e) { // 捕获输入输出异常 } catch (IllegalStateException e) {
e.printStackTrace(); // 打印异常信息 // TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
} }
private void showActionDialog() { // 定义显示动作对话框的方法 private void showActionDialog() {
AlertDialog.Builder dialog = new AlertDialog.Builder(this); // 创建对话框构建器 AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle(R.string.app_name); // 设置对话框标题 dialog.setTitle(R.string.app_name);
dialog.setMessage(mSnippet); // 设置对话框消息 dialog.setMessage(mSnippet);
dialog.setPositiveButton(R.string.notealert_ok, this); // 设置正面按钮 dialog.setPositiveButton(R.string.notealert_ok, this);
if (isScreenOn()) { // 检查屏幕是否处于打开状态 if (isScreenOn()) {
dialog.setNegativeButton(R.string.notealert_enter, this); // 设置负面按钮 dialog.setNegativeButton(R.string.notealert_enter, this);
} }
dialog.show().setOnDismissListener(this); // 显示对话框并设置关闭监听器 dialog.show().setOnDismissListener(this);
} }
public void onClick(DialogInterface dialog, int which) { // 实现OnClickListener接口的onClick方法处理对话框按钮点击事件 public void onClick(DialogInterface dialog, int which) {
switch (which) { // 根据按钮类型进行处理 switch (which) {
case DialogInterface.BUTTON_NEGATIVE: // 如果是负面按钮 case DialogInterface.BUTTON_NEGATIVE:
Intent intent = new Intent(this, NoteEditActivity.class); // 创建启动笔记编辑活动的意图 Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_VIEW); // 设置动作 intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(Intent.EXTRA_UID, mNoteId); // 传递笔记ID intent.putExtra(Intent.EXTRA_UID, mNoteId);
startActivity(intent); // 启动活动 startActivity(intent);
break; // 结束处理 break;
default: // 默认情况 default:
break; // 结束处理 break;
} }
} }
public void onDismiss(DialogInterface dialog) { // 实现OnDismissListener接口的onDismiss方法处理对话框关闭事件 public void onDismiss(DialogInterface dialog) {
stopAlarmSound(); // 停止播放提醒声音 stopAlarmSound();
finish(); // 结束活动 finish();
} }
private void stopAlarmSound() { // 定义停止播放提醒声音的方法 private void stopAlarmSound() {
if (mPlayer != null) { // 检查MediaPlayer对象是否为空 if (mPlayer != null) {
mPlayer.stop(); // 停止播放 mPlayer.stop();
mPlayer.release(); // 释放资源 mPlayer.release();
mPlayer = null; // 将MediaPlayer对象设置为空 mPlayer = null;
} }
} }
} }

@ -14,72 +14,52 @@
* limitations under the License. * limitations under the License.
*/ */
/* package net.micode.notes.ui;
* 广
* import android.app.AlarmManager;
*/ import android.app.PendingIntent;
package net.micode.notes.ui; // 定义该类的包路径 import android.content.BroadcastReceiver;
import android.content.ContentUris;
import android.app.AlarmManager; // 导入AlarmManager类用于设置提醒 import android.content.Context;
import android.app.PendingIntent; // 导入PendingIntent类用于延迟执行意图 import android.content.Intent;
import android.content.BroadcastReceiver; // 导入BroadcastReceiver类用于接收广播 import android.database.Cursor;
import android.content.ContentUris; // 导入ContentUris类用于处理URI
import android.content.Context; // 导入Context类用于获取应用环境 import net.micode.notes.data.Notes;
import android.content.Intent; // 导入Intent类用于启动活动和传递数据 import net.micode.notes.data.Notes.NoteColumns;
import android.database.Cursor; // 导入Cursor类用于查询数据库
import net.micode.notes.data.Notes; // 导入应用内部定义的笔记数据类 public class AlarmInitReceiver extends BroadcastReceiver {
import net.micode.notes.data.Notes.NoteColumns; // 导入笔记数据类的列定义
private static final String [] PROJECTION = new String [] {
public class AlarmInitReceiver extends BroadcastReceiver { // 定义AlarmInitReceiver类继承自BroadcastReceiver NoteColumns.ID,
NoteColumns.ALERTED_DATE
// 查询笔记时需要的列
private static final String[] PROJECTION = new String[]{
NoteColumns.ID, // 笔记ID
NoteColumns.ALERTED_DATE // 提醒日期
}; };
// 列的索引 private static final int COLUMN_ID = 0;
private static final int COLUMN_ID = 0; // ID列的索引 private static final int COLUMN_ALERTED_DATE = 1;
private static final int COLUMN_ALERTED_DATE = 1; // 提醒日期列的索引
/**
* 广
*
* @param context 访
* @param intent 广
*/
@Override @Override
public void onReceive(Context context, Intent intent) { // 重写onReceive方法当接收到广播时执行 public void onReceive(Context context, Intent intent) {
// 获取当前日期和时间 long currentDate = System.currentTimeMillis();
long currentDate = System.currentTimeMillis(); // 获取当前时间戳 Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
// 查询数据库中所有需要提醒的笔记 PROJECTION,
Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI, // 查询笔记内容的URI NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE,
PROJECTION, // 查询的列 new String[] { String.valueOf(currentDate) },
NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE, // 查询条件 null);
new String[]{String.valueOf(currentDate)}, // 查询参数
null); // 排序方式 if (c != null) {
if (c.moveToFirst()) {
if (c != null) { // 检查Cursor是否为空
// 遍历查询结果,为每个需要提醒的笔记设置提醒
if (c.moveToFirst()) { // 移动到第一行
do { do {
// 获取提醒日期 long alertDate = c.getLong(COLUMN_ALERTED_DATE);
long alertDate = c.getLong(COLUMN_ALERTED_DATE); // 获取提醒日期 Intent sender = new Intent(context, AlarmReceiver.class);
// 创建Intent用于在提醒时间触发AlarmReceiver sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID)));
Intent sender = new Intent(context, AlarmReceiver.class); // 创建启动AlarmReceiver的意图 PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0);
sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID))); // 设置意图的数据URI
// 创建PendingIntent它是一个延迟的意图可以在特定时间由系统触发
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0); // 创建PendingIntent
// 获取AlarmManager服务用于设置提醒
AlarmManager alermManager = (AlarmManager) context AlarmManager alermManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE); // 获取AlarmManager服务 .getSystemService(Context.ALARM_SERVICE);
// 设置提醒 alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);
alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent); // 设置提醒时间 } while (c.moveToNext());
} while (c.moveToNext()); // 移动到下一行
} }
// 关闭Cursor释放资源 c.close();
c.close(); // 关闭Cursor
} }
} }
} }

@ -14,33 +14,17 @@
* limitations under the License. * limitations under the License.
*/ */
/* package net.micode.notes.ui;
* AlarmReceiver - 广
* 广Activity import android.content.BroadcastReceiver;
* import android.content.Context;
* extends BroadcastReceiver: AndroidBroadcastReceiver import android.content.Intent;
*/
package net.micode.notes.ui; // 定义该类的包路径 public class AlarmReceiver extends BroadcastReceiver {
import android.content.BroadcastReceiver; // 导入BroadcastReceiver类用于接收广播
import android.content.Context; // 导入Context类用于获取应用环境
import android.content.Intent; // 导入Intent类用于启动活动和传递数据
public class AlarmReceiver extends BroadcastReceiver { // 定义AlarmReceiver类继承自BroadcastReceiver
/*
* onReceive - 广
* 广AlarmAlertActivity
*
* @param context
* @param intent 广
*/
@Override @Override
public void onReceive(Context context, Intent intent) { // 重写onReceive方法当接收到广播时执行 public void onReceive(Context context, Intent intent) {
// 设置Intent的类以便启动AlarmAlertActivity intent.setClass(context, AlarmAlertActivity.class);
intent.setClass(context, AlarmAlertActivity.class); // 设置Intent的目标Activity为AlarmAlertActivity intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// 添加标志表示在一个新的任务中启动Activity context.startActivity(intent);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // 添加标志确保Activity在一个新的任务中启动
// 根据设置的Intent启动Activity
context.startActivity(intent); // 启动AlarmAlertActivity
} }
} }

@ -14,103 +14,71 @@
* 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_HALF_DAY = 12;
// 一整天的小时数
private static final int HOURS_IN_ALL_DAY = 24; private static final int HOURS_IN_ALL_DAY = 24;
// 一周的天数
private static final int DAYS_IN_ALL_WEEK = 7; private static final int DAYS_IN_ALL_WEEK = 7;
// 日期选择器的最小值
private static final int DATE_SPINNER_MIN_VAL = 0; private static final int DATE_SPINNER_MIN_VAL = 0;
// 日期选择器的最大值
private static final int DATE_SPINNER_MAX_VAL = DAYS_IN_ALL_WEEK - 1; private static final int DATE_SPINNER_MAX_VAL = DAYS_IN_ALL_WEEK - 1;
// 24小时制小时选择器的最小值
private static final int HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW = 0; private static final int HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW = 0;
// 24小时制小时选择器的最大值
private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23; private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23;
// 12小时制小时选择器的最小值
private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1; private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1;
// 12小时制小时选择器的最大值
private static final int HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW = 12; private static final int HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW = 12;
// 分钟选择器的最小值
private static final int MINUT_SPINNER_MIN_VAL = 0; private static final int MINUT_SPINNER_MIN_VAL = 0;
// 分钟选择器的最大值
private static final int MINUT_SPINNER_MAX_VAL = 59; private static final int MINUT_SPINNER_MAX_VAL = 59;
// 上下午选择器的最小值
private static final int AMPM_SPINNER_MIN_VAL = 0; private static final int AMPM_SPINNER_MIN_VAL = 0;
// 上下午选择器的最大值
private static final int AMPM_SPINNER_MAX_VAL = 1; private static final int AMPM_SPINNER_MAX_VAL = 1;
// 日期选择器
private final NumberPicker mDateSpinner; private final NumberPicker mDateSpinner;
// 小时选择器
private final NumberPicker mHourSpinner; private final NumberPicker mHourSpinner;
// 分钟选择器
private final NumberPicker mMinuteSpinner; private final NumberPicker mMinuteSpinner;
// 上下午选择器
private final NumberPicker mAmPmSpinner; 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;
// 当前是否为24小时制视图
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) {
// 处理12小时制下的日期变化和上下午切换
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);
@ -126,7 +94,6 @@ public class DateTimePicker extends FrameLayout {
updateAmPmControl(); updateAmPmControl();
} }
} else { } else {
// 处理24小时制下的日期变化
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);
@ -137,11 +104,9 @@ public class DateTimePicker extends FrameLayout {
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));
@ -149,13 +114,10 @@ public class DateTimePicker extends FrameLayout {
} }
} }
}; };
// 分别为分钟和AM/PM选择器监听器设置匿名内部类实现数值变化时的处理逻辑。
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;
@ -164,7 +126,6 @@ public class DateTimePicker extends FrameLayout {
} else if (oldVal == minValue && newVal == maxValue) { } else if (oldVal == minValue && newVal == maxValue) {
offset -= 1; offset -= 1;
} }
// 根据偏移量更新日期和小时选择器并检查是否需要切换AM/PM
if (offset != 0) { if (offset != 0) {
mDate.add(Calendar.HOUR_OF_DAY, offset); mDate.add(Calendar.HOUR_OF_DAY, offset);
mHourSpinner.setValue(getCurrentHour()); mHourSpinner.setValue(getCurrentHour());
@ -178,16 +139,14 @@ public class DateTimePicker extends FrameLayout {
updateAmPmControl(); updateAmPmControl();
} }
} }
// 更新分钟值并触发日期变化的回调
mDate.set(Calendar.MINUTE, newVal); mDate.set(Calendar.MINUTE, newVal);
onDateTimeChanged(); onDateTimeChanged();
} }
}; };
private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() { private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() {
@Override @Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) { public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// 切换AM/PM状态并更新日期和AM/PM选择器
mIsAm = !mIsAm; mIsAm = !mIsAm;
if (mIsAm) { if (mIsAm) {
mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY); mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY);
@ -198,238 +157,202 @@ public class DateTimePicker extends FrameLayout {
onDateTimeChanged(); onDateTimeChanged();
} }
}; };
// 定义日期时间变化的回调接口
public interface OnDateTimeChangedListener { public interface OnDateTimeChangedListener {
void onDateTimeChanged(DateTimePicker view, int year, int month, void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute); int dayOfMonth, int hourOfDay, int minute);
} }
// 构造函数:初始化日期时间选择器
public DateTimePicker(Context context) { public DateTimePicker(Context context) {
this(context, System.currentTimeMillis()); this(context, System.currentTimeMillis());
} }
// 构造函数:指定初始日期时间
public DateTimePicker(Context context, long date) { public DateTimePicker(Context context, long date) {
this(context, date, DateFormat.is24HourFormat(context)); this(context, date, DateFormat.is24HourFormat(context));
} }
// 构造函数指定是否使用24小时制视图
public DateTimePicker(Context context, long date, boolean is24HourView) { public DateTimePicker(Context context, long date, boolean is24HourView) {
super(context); super(context);
mDate = Calendar.getInstance(); mDate = Calendar.getInstance();
mInitialising = true; mInitialising = true;
mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY; mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY;
inflate(context, R.layout.datetime_picker, this); inflate(context, R.layout.datetime_picker, this);
// 初始化日期、小时、分钟和AM/PM选择器并设置相应的监听器
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;
} }
/**
*
*
*
*
* @param enabled
*/
@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;
} }
/**
*
*
* @return
*/
@Override @Override
public boolean isEnabled() { public boolean isEnabled() {
return mIsEnabled; return mIsEnabled;
} }
/** /**
* * Get the current date in millis
* *
* @return * @return the current date in millis
*/ */
public long getCurrentDateInTimeMillis() { public long getCurrentDateInTimeMillis() {
return mDate.getTimeInMillis(); return mDate.getTimeInMillis();
} }
/** /**
* * 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
*
* *
* @param year * @param year The current year
* @param month * @param month The current month
* @param dayOfMonth * @param dayOfMonth The current dayOfMonth
* @param hourOfDay * @param hourOfDay The current hourOfDay
* @param 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
* *
* @return * @return The current year
*/ */
public int getCurrentYear() { public int getCurrentYear() {
return mDate.get(Calendar.YEAR); return mDate.get(Calendar.YEAR);
} }
/** /**
* * Set current year
* *
* @param 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
* *
* @return 0 * @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
* *
* @param month 0 * @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
* *
* @return * @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
* *
* @param dayOfMonth * @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();
} }
/** /**
* 24(0~23) * Get current hour in 24 hour mode, in the range (0~23)
* * @return The current hour in 24 hour mode
* @return 24
*/ */
public int getCurrentHourOfDay() { public int getCurrentHourOfDay() {
return mDate.get(Calendar.HOUR_OF_DAY); return mDate.get(Calendar.HOUR_OF_DAY);
} }
/**
* 24
* 24{@link #getCurrentHourOfDay()}
* 12/
*
* @return 12
*/
private int getCurrentHour() { private int getCurrentHour() {
if (mIs24HourView) { if (mIs24HourView){
return getCurrentHourOfDay(); return getCurrentHourOfDay();
} else { } else {
int hour = getCurrentHourOfDay(); int hour = getCurrentHourOfDay();
// 转换为12小时制
if (hour > HOURS_IN_HALF_DAY) { if (hour > HOURS_IN_HALF_DAY) {
return hour - HOURS_IN_HALF_DAY; return hour - HOURS_IN_HALF_DAY;
} else { } else {
@ -437,20 +360,17 @@ public class DateTimePicker extends FrameLayout {
} }
} }
} }
/** /**
* 24(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);
// 如果不是24小时视图则调整小时数并更新AM/PM控制
if (!mIs24HourView) { if (!mIs24HourView) {
if (hourOfDay >= HOURS_IN_HALF_DAY) { if (hourOfDay >= HOURS_IN_HALF_DAY) {
mIsAm = false; mIsAm = false;
@ -468,23 +388,20 @@ public class DateTimePicker extends FrameLayout {
mHourSpinner.setValue(hourOfDay); mHourSpinner.setValue(hourOfDay);
onDateTimeChanged(); onDateTimeChanged();
} }
/** /**
* * Get currentMinute
* *
* @return * @return The Current Minute
*/ */
public int getCurrentMinute() { public int getCurrentMinute() {
return mDate.get(Calendar.MINUTE); return mDate.get(Calendar.MINUTE);
} }
/** /**
* * Set current minute
*
* @param minute
*/ */
public void setCurrentMinute(int minute) { public void setCurrentMinute(int minute) {
// 如果在初始化中或者分钟数未改变,则直接返回
if (!mInitialising && minute == getCurrentMinute()) { if (!mInitialising && minute == getCurrentMinute()) {
return; return;
} }
@ -492,23 +409,20 @@ public class DateTimePicker extends FrameLayout {
mDate.set(Calendar.MINUTE, minute); mDate.set(Calendar.MINUTE, minute);
onDateTimeChanged(); onDateTimeChanged();
} }
/** /**
* 24 * @return true if this is in 24 hour view else false.
*
* @return 24truefalse
*/ */
public boolean is24HourView() { public boolean is24HourView () {
return mIs24HourView; return mIs24HourView;
} }
/** /**
* 24AM/PM * Set whether in 24 hour or AM/PM mode.
* *
* @param is24HourView true24falseAM/PM * @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;
} }
@ -519,16 +433,12 @@ public class DateTimePicker extends FrameLayout {
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);
@ -537,10 +447,7 @@ public class DateTimePicker extends FrameLayout {
mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2); mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2);
mDateSpinner.invalidate(); mDateSpinner.invalidate();
} }
/**
* 24AM/PM
*/
private void updateAmPmControl() { private void updateAmPmControl() {
if (mIs24HourView) { if (mIs24HourView) {
mAmPmSpinner.setVisibility(View.GONE); mAmPmSpinner.setVisibility(View.GONE);
@ -550,10 +457,7 @@ public class DateTimePicker extends FrameLayout {
mAmPmSpinner.setVisibility(View.VISIBLE); mAmPmSpinner.setVisibility(View.VISIBLE);
} }
} }
/**
* 24
*/
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);
@ -563,19 +467,15 @@ public class DateTimePicker extends FrameLayout {
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.
* * @param callback the callback, if null will do nothing
* @param callback null
*/ */
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(),

@ -14,124 +14,77 @@
* limitations under the License. * limitations under the License.
*/ */
/* package net.micode.notes.ui;
* DateTimePickerDialog
* import java.util.Calendar;
*/
package net.micode.notes.ui; // 定义包名 import net.micode.notes.R;
import net.micode.notes.ui.DateTimePicker;
import java.util.Calendar; // 导入Calendar类用于处理日期和时间 import net.micode.notes.ui.DateTimePicker.OnDateTimeChangedListener;
import net.micode.notes.R; // 导入资源类,用于访问资源 import android.app.AlertDialog;
import net.micode.notes.ui.DateTimePicker; // 导入DateTimePicker类用于日期时间选择器视图 import android.content.Context;
import net.micode.notes.ui.DateTimePicker.OnDateTimeChangedListener; // 导入日期时间改变监听器接口 import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.app.AlertDialog; // 导入AlertDialog类用于创建对话框 import android.text.format.DateFormat;
import android.content.Context; // 导入Context类用于获取上下文 import android.text.format.DateUtils;
import android.content.DialogInterface; // 导入DialogInterface类用于处理对话框事件
import android.content.DialogInterface.OnClickListener; // 导入OnClickListener接口用于处理按钮点击事件 public class DateTimePickerDialog extends AlertDialog implements OnClickListener {
import android.text.format.DateFormat; // 导入DateFormat类用于日期时间格式化
import android.text.format.DateUtils; // 导入DateUtils类用于日期时间格式化
public class DateTimePickerDialog extends AlertDialog implements OnClickListener { // 定义DateTimePickerDialog类继承自AlertDialog并实现OnClickListener接口
// 当前选择的日期和时间
private Calendar mDate = Calendar.getInstance(); private Calendar mDate = Calendar.getInstance();
// 用于指示日期时间选择器是否使用24小时制
private boolean mIs24HourView; private boolean mIs24HourView;
// 日期时间设置监听器,用于处理日期时间选择后的回调
private OnDateTimeSetListener mOnDateTimeSetListener; private OnDateTimeSetListener mOnDateTimeSetListener;
// 日期时间选择器视图
private DateTimePicker mDateTimePicker; private DateTimePicker mDateTimePicker;
/**
*
* OnDateTimeSet
*/
public interface OnDateTimeSetListener { public interface OnDateTimeSetListener {
void OnDateTimeSet(AlertDialog dialog, long date); void OnDateTimeSet(AlertDialog dialog, long date);
} }
/**
*
*
* @param context Activity
* @param date
*/
public DateTimePickerDialog(Context context, long date) { public DateTimePickerDialog(Context context, long date) {
super(context); // 调用父类构造函数 super(context);
mDateTimePicker = new DateTimePicker(context); // 创建DateTimePicker实例 mDateTimePicker = new DateTimePicker(context);
setView(mDateTimePicker); // 设置对话框视图为DateTimePicker 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); // 设置秒数为0 mDate.set(Calendar.SECOND, 0);
mDateTimePicker.setCurrentDate(mDate.getTimeInMillis()); // 设置DateTimePicker的当前日期时间 mDateTimePicker.setCurrentDate(mDate.getTimeInMillis());
// 设置对话框的确认和取消按钮
setButton(context.getString(R.string.datetime_dialog_ok), this); setButton(context.getString(R.string.datetime_dialog_ok), this);
setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener) null); setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null);
// 根据系统设置决定是否使用24小时制
set24HourView(DateFormat.is24HourFormat(this.getContext())); set24HourView(DateFormat.is24HourFormat(this.getContext()));
// 更新标题以显示当前选择的日期和时间
updateTitle(mDate.getTimeInMillis()); updateTitle(mDate.getTimeInMillis());
} }
/**
* 使24
*
* @param is24HourView 使24
*/
public void set24HourView(boolean is24HourView) { public void set24HourView(boolean is24HourView) {
mIs24HourView = is24HourView; mIs24HourView = is24HourView;
} }
/**
*
*
* @param callBack
*/
public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) { public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) {
mOnDateTimeSetListener = callBack; mOnDateTimeSetListener = callBack;
} }
/**
*
*
* @param date
*/
private void updateTitle(long date) { private void updateTitle(long date) {
// 根据是否使用24小时制来格式化日期时间显示
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));
} }
/**
*
* OnDateTimeSet
*
* @param arg0
* @param arg1
*/
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,76 +14,48 @@
* limitations under the License. * limitations under the License.
*/ */
/* package net.micode.notes.ui;
* DropdownMenu
* ButtonPopupMenuButton import android.content.Context;
*/ import android.view.Menu;
package net.micode.notes.ui; // 定义包名 import android.view.MenuItem;
import android.view.View;
import android.content.Context; // 导入Context类用于获取上下文 import android.view.View.OnClickListener;
import android.view.Menu; // 导入Menu类用于管理菜单项 import android.widget.Button;
import android.view.MenuItem; // 导入MenuItem类用于表示菜单项 import android.widget.PopupMenu;
import android.view.View; // 导入View类用于处理视图 import android.widget.PopupMenu.OnMenuItemClickListener;
import android.view.View.OnClickListener; // 导入OnClickListener接口用于处理点击事件
import android.widget.Button; // 导入Button类用于创建按钮 import net.micode.notes.R;
import android.widget.PopupMenu; // 导入PopupMenu类用于创建弹出菜单
import android.widget.PopupMenu.OnMenuItemClickListener; // 导入OnMenuItemClickListener接口用于处理菜单项点击事件 public class DropdownMenu {
private Button mButton;
import net.micode.notes.R; // 导入资源类,用于访问资源 private PopupMenu mPopupMenu;
private Menu mMenu;
public class DropdownMenu { // 定义DropdownMenu类
private Button mButton; // 弹出下拉菜单的按钮
private PopupMenu mPopupMenu; // 弹出的下拉菜单
private Menu mMenu; // 下拉菜单的项目集合
/**
* DropdownMenu
*
* @param context Activity
* @param button
* @param menuId ID
*/
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); // 创建PopupMenu实例锚点为按钮 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();
} }
}); });
} }
/**
*
*
* @param listener PopupMenuOnMenuItemClickListener
*/
public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) { public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) {
if (mPopupMenu != null) { if (mPopupMenu != null) {
mPopupMenu.setOnMenuItemClickListener(listener); // 设置菜单项点击监听器 mPopupMenu.setOnMenuItemClickListener(listener);
} }
} }
/**
* ID
*
* @param id ID
* @return MenuItemnull
*/
public MenuItem findItem(int id) { public MenuItem findItem(int id) {
return mMenu.findItem(id); // 根据ID查找菜单项 return mMenu.findItem(id);
} }
/**
*
*
* @param title
*/
public void setTitle(CharSequence title) { public void setTitle(CharSequence title) {
mButton.setText(title); // 设置按钮显示的文本 mButton.setText(title);
} }
} }

@ -14,111 +14,67 @@
* limitations under the License. * limitations under the License.
*/ */
/* package net.micode.notes.ui;
* FoldersListAdapter
* CursorAdapter import android.content.Context;
*/ import android.database.Cursor;
import android.view.View;
package net.micode.notes.ui; // 定义包名 import android.view.ViewGroup;
import android.widget.CursorAdapter;
// 导入相关类 import android.widget.LinearLayout;
import android.content.Context; // 导入Context类用于获取上下文 import android.widget.TextView;
import android.database.Cursor; // 导入Cursor类用于数据源游标
import android.view.View; // 导入View类用于视图 import net.micode.notes.R;
import android.view.ViewGroup; // 导入ViewGroup类用于视图的父容器 import net.micode.notes.data.Notes;
import android.widget.CursorAdapter; // 导入CursorAdapter类用于适配器 import net.micode.notes.data.Notes.NoteColumns;
import android.widget.LinearLayout; // 导入LinearLayout类用于布局
import android.widget.TextView; // 导入TextView类用于文本显示
public class FoldersListAdapter extends CursorAdapter {
import net.micode.notes.R; // 导入资源类,用于访问资源 public static final String [] PROJECTION = {
import net.micode.notes.data.Notes; // 导入Notes类用于数据操作 NoteColumns.ID,
import net.micode.notes.data.Notes.NoteColumns; // 导入NoteColumns类用于数据列名 NoteColumns.SNIPPET
public class FoldersListAdapter extends CursorAdapter { // 定义FoldersListAdapter类继承自CursorAdapter
// 查询时使用的列名数组
public static final String[] PROJECTION = {
NoteColumns.ID, // 文件夹ID列
NoteColumns.SNIPPET // 文件夹名称列
}; };
// 列名数组中的索引常量 public static final int ID_COLUMN = 0;
public static final int ID_COLUMN = 0; // ID列索引 public static final int NAME_COLUMN = 1;
public static final int NAME_COLUMN = 1; // 名称列索引
/*
*
* @param context ActivityApplication
* @param c Cursor
*/
public FoldersListAdapter(Context context, Cursor c) { public FoldersListAdapter(Context context, Cursor c) {
super(context, c); // 调用父类构造函数 super(context, c);
// TODO Auto-generated constructor stub
} }
/*
* View
* @param context
* @param cursor
* @param parent
* @return View
*/
@Override @Override
public View newView(Context context, Cursor cursor, ViewGroup parent) { public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new FolderListItem(context); // 返回新的FolderListItem实例 return new FolderListItem(context);
} }
/*
* View
* @param view
* @param context
* @param cursor
*/
@Override @Override
public void bindView(View view, Context context, Cursor cursor) { public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof FolderListItem) { // 判断视图是否为FolderListItem类型 if (view instanceof FolderListItem) {
// 根据文件夹ID判断是根文件夹还是普通文件夹并设置文件夹名称
String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
((FolderListItem) view).bind(folderName); // 绑定文件夹名称到视图 ((FolderListItem) view).bind(folderName);
} }
} }
/*
*
* @param context
* @param position
* @return
*/
public String getFolderName(Context context, int position) { public String getFolderName(Context context, int position) {
Cursor cursor = (Cursor) getItem(position); // 获取指定位置的游标 Cursor cursor = (Cursor) getItem(position);
return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); // 返回文件夹名称 .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
} }
/* private class FolderListItem extends LinearLayout {
* FolderListItem private TextView mName;
*
*/
private class FolderListItem extends LinearLayout { // 定义FolderListItem内部类继承自LinearLayout
private TextView mName; // 文件夹名称的文本视图
/*
*
* @param context
*/
public FolderListItem(Context context) { public FolderListItem(Context context) {
super(context); // 调用父类构造函数 super(context);
// 加载布局文件,并将自己作为根视图
inflate(context, R.layout.folder_list_item, this); inflate(context, R.layout.folder_list_item, this);
mName = (TextView) findViewById(R.id.tv_folder_name); // 获取文件夹名称的视图 mName = (TextView) findViewById(R.id.tv_folder_name);
} }
/*
*
* @param name
*/
public void bind(String name) { public void bind(String name) {
mName.setText(name); // 设置文件夹名称 mName.setText(name);
} }
} }
} }

File diff suppressed because it is too large Load Diff

@ -14,24 +14,8 @@
* limitations under the License. * limitations under the License.
*/ */
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui; 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;
@ -47,143 +31,105 @@ 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:" ;
// URL方案与对应操作资源ID的映射
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);
} }
/** /**
* * Call by the {@link NoteEditActivity} to delete or add edit text
*/ */
public interface OnTextViewChangeListener { public interface OnTextViewChangeListener {
/** /**
* * Delete current edit text when {@link KeyEvent#KEYCODE_DEL} happens
* and the text is null
*/ */
void onEditTextDelete(int index, String text); void onEditTextDelete(int index, String text);
/** /**
* * Add edit text after current edit text when {@link KeyEvent#KEYCODE_ENTER}
* happen
*/ */
void onEditTextEnter(int index, String text); void onEditTextEnter(int index, String text);
/** /**
* * Hide or show item option when text change
*/ */
void onTextChange(int index, boolean hasText); void onTextChange(int index, boolean hasText);
} }
private OnTextViewChangeListener mOnTextViewChangeListener; private OnTextViewChangeListener mOnTextViewChangeListener;
/**
*
*
* @param context
*/
public NoteEditText(Context context) { public NoteEditText(Context context) {
super(context, null); super(context, null);
mIndex = 0; mIndex = 0;
} }
/**
*
*
* @param index
*/
public void setIndex(int index) { public void setIndex(int index) {
mIndex = index; mIndex = index;
} }
/**
*
*
* @param listener
*/
public void setOnTextViewChangeListener(OnTextViewChangeListener listener) { public void setOnTextViewChangeListener(OnTextViewChangeListener listener) {
mOnTextViewChangeListener = listener; mOnTextViewChangeListener = listener;
} }
/**
*
*
* @param context
* @param attrs
*/
public NoteEditText(Context context, AttributeSet attrs) { public NoteEditText(Context context, AttributeSet attrs) {
super(context, attrs, android.R.attr.editTextStyle); super(context, attrs, android.R.attr.editTextStyle);
} }
/**
*
*
* @param context
* @param attrs
* @param defStyle
*/
public NoteEditText(Context context, AttributeSet attrs, int defStyle) { public NoteEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle); super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
} }
/**
*
*/
@Override @Override
public boolean onTouchEvent(MotionEvent event) { public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) { switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_DOWN:
// 计算触摸位置相对于文本的偏移量,并调整光标位置
int x = (int) event.getX(); int x = (int) event.getX();
int y = (int) event.getY(); int y = (int) event.getY();
x -= getTotalPaddingLeft(); x -= getTotalPaddingLeft();
y -= getTotalPaddingTop(); y -= getTotalPaddingTop();
x += getScrollX(); x += getScrollX();
y += getScrollY(); y += getScrollY();
Layout layout = getLayout(); Layout layout = getLayout();
int line = layout.getLineForVertical(y); int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x); int off = layout.getOffsetForHorizontal(line, x);
Selection.setSelection(getText(), off); Selection.setSelection(getText(), off);
break; break;
} }
return super.onTouchEvent(event); return super.onTouchEvent(event);
} }
/**
*
*/
@Override @Override
public boolean onKeyDown(int keyCode, KeyEvent event) { public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) { switch (keyCode) {
case KeyEvent.KEYCODE_ENTER: case KeyEvent.KEYCODE_ENTER:
// 处理回车键事件,准备新增文本视图
if (mOnTextViewChangeListener != null) { if (mOnTextViewChangeListener != null) {
return false; return false;
} }
break; break;
case KeyEvent.KEYCODE_DEL: case KeyEvent.KEYCODE_DEL:
// 记录删除操作前的选择位置
mSelectionStartBeforeDelete = getSelectionStart(); mSelectionStartBeforeDelete = getSelectionStart();
break; break;
default: default:
@ -191,15 +137,11 @@ public class NoteEditText extends EditText {
} }
return super.onKeyDown(keyCode, event); return super.onKeyDown(keyCode, event);
} }
/**
*
*/
@Override @Override
public boolean onKeyUp(int keyCode, KeyEvent event) { public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) { switch(keyCode) {
case KeyEvent.KEYCODE_DEL: case KeyEvent.KEYCODE_DEL:
// 处理删除键事件,若为首个文本且非空,则删除当前文本
if (mOnTextViewChangeListener != null) { if (mOnTextViewChangeListener != null) {
if (0 == mSelectionStartBeforeDelete && mIndex != 0) { if (0 == mSelectionStartBeforeDelete && mIndex != 0) {
mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString()); mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString());
@ -210,7 +152,6 @@ public class NoteEditText extends EditText {
} }
break; break;
case KeyEvent.KEYCODE_ENTER: case KeyEvent.KEYCODE_ENTER:
// 处理回车键事件,新增文本视图
if (mOnTextViewChangeListener != null) { if (mOnTextViewChangeListener != null) {
int selectionStart = getSelectionStart(); int selectionStart = getSelectionStart();
String text = getText().subSequence(selectionStart, length()).toString(); String text = getText().subSequence(selectionStart, length()).toString();
@ -225,10 +166,7 @@ public class NoteEditText extends EditText {
} }
return super.onKeyUp(keyCode, event); return super.onKeyUp(keyCode, event);
} }
/**
*
*/
@Override @Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
if (mOnTextViewChangeListener != null) { if (mOnTextViewChangeListener != null) {
@ -240,37 +178,34 @@ public class NoteEditText extends EditText {
} }
super.onFocusChanged(focused, direction, previouslyFocusedRect); super.onFocusChanged(focused, direction, previouslyFocusedRect);
} }
/**
* URL
*/
@Override @Override
protected void onCreateContextMenu(ContextMenu menu) { protected void onCreateContextMenu(ContextMenu menu) {
if (getText() instanceof Spanned) { if (getText() instanceof Spanned) {
int selStart = getSelectionStart(); int selStart = getSelectionStart();
int selEnd = getSelectionEnd(); int selEnd = getSelectionEnd();
int min = Math.min(selStart, selEnd); int min = Math.min(selStart, selEnd);
int max = Math.max(selStart, selEnd); int max = Math.max(selStart, selEnd);
final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class); final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class);
if (urls.length == 1) { if (urls.length == 1) {
int defaultResId = 0; int defaultResId = 0;
for (String schema : sSchemaActionResMap.keySet()) { for(String schema: sSchemaActionResMap.keySet()) {
if (urls[0].getURL().indexOf(schema) >= 0) { if(urls[0].getURL().indexOf(schema) >= 0) {
defaultResId = sSchemaActionResMap.get(schema); defaultResId = sSchemaActionResMap.get(schema);
break; break;
} }
} }
if (defaultResId == 0) { if (defaultResId == 0) {
defaultResId = R.string.note_link_other; defaultResId = R.string.note_link_other;
} }
menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener( menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener(
new OnMenuItemClickListener() { new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) { public boolean onMenuItemClick(MenuItem item) {
// 跳转到URL指向的页面 // goto a new intent
urls[0].onClick(NoteEditText.this); urls[0].onClick(NoteEditText.this);
return true; return true;
} }
@ -280,4 +215,3 @@ public class NoteEditText extends EditText {
super.onCreateContextMenu(menu); super.onCreateContextMenu(menu);
} }
} }

@ -14,242 +14,211 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.ui; // 定义包名 package net.micode.notes.ui;
import android.content.Context; // 导入Context类用于获取上下文 import android.content.Context;
import android.database.Cursor; // 导入Cursor类用于数据源游标 import android.database.Cursor;
import android.text.TextUtils; // 导入TextUtils类用于字符串操作 import android.text.TextUtils;
import net.micode.notes.data.Contact; // 导入Contact类用于联系人数据操作 import net.micode.notes.data.Contact;
import net.micode.notes.data.Notes; // 导入Notes类用于笔记数据操作 import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns; // 导入NoteColumns类用于笔记数据列名 import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.tool.DataUtils; // 导入DataUtils类用于数据工具操作 import net.micode.notes.tool.DataUtils;
/**
* public class NoteItemData {
*/ static final String [] PROJECTION = new String [] {
public class NoteItemData { // 定义NoteItemData类 NoteColumns.ID,
// 定义查询时要投影的列 NoteColumns.ALERTED_DATE,
static final String[] PROJECTION = new String[]{ NoteColumns.BG_COLOR_ID,
NoteColumns.ID, // 笔记ID NoteColumns.CREATED_DATE,
NoteColumns.ALERTED_DATE, // 提醒日期 NoteColumns.HAS_ATTACHMENT,
NoteColumns.BG_COLOR_ID, // 背景颜色ID NoteColumns.MODIFIED_DATE,
NoteColumns.CREATED_DATE, // 创建日期 NoteColumns.NOTES_COUNT,
NoteColumns.HAS_ATTACHMENT, // 是否有附件 NoteColumns.PARENT_ID,
NoteColumns.MODIFIED_DATE, // 修改日期 NoteColumns.SNIPPET,
NoteColumns.NOTES_COUNT, // 笔记数量 NoteColumns.TYPE,
NoteColumns.PARENT_ID, // 父ID NoteColumns.WIDGET_ID,
NoteColumns.SNIPPET, // 摘要 NoteColumns.WIDGET_TYPE,
NoteColumns.TYPE, // 类型
NoteColumns.WIDGET_ID, // 小部件ID
NoteColumns.WIDGET_TYPE, // 小部件类型
}; };
// 各列数据的索引 private static final int ID_COLUMN = 0;
private static final int ID_COLUMN = 0; // ID列索引 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; // 背景颜色ID列索引 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; // 父ID列索引 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; // 小部件ID列索引 private static final int WIDGET_TYPE_COLUMN = 11;
private static final int WIDGET_TYPE_COLUMN = 11; // 小部件类型列索引
private long mId;
// 笔记的各项数据 private long mAlertDate;
private long mId; // 笔记ID private int mBgColorId;
private long mAlertDate; // 提醒日期 private long mCreatedDate;
private int mBgColorId; // 背景颜色ID private boolean mHasAttachment;
private long mCreatedDate; // 创建日期 private long mModifiedDate;
private boolean mHasAttachment; // 是否有附件 private int mNotesCount;
private long mModifiedDate; // 修改日期 private long mParentId;
private int mNotesCount; // 笔记数量 private String mSnippet;
private long mParentId; // 父ID private int mType;
private String mSnippet; // 摘要 private int mWidgetId;
private int mType; // 类型 private int mWidgetType;
private int mWidgetId; // 小部件ID private String mName;
private int mWidgetType; // 小部件类型 private String mPhoneNumber;
private String mName; // 联系人名称
private String mPhoneNumber; // 电话号码 private boolean mIsLastItem;
private boolean mIsFirstItem;
// 用于标识笔记在列表中的位置状态 private boolean mIsOnlyOneItem;
private boolean mIsLastItem; // 是否为最后一个项目 private boolean mIsOneNoteFollowingFolder;
private boolean mIsFirstItem; // 是否为第一个项目 private boolean mIsMultiNotesFollowingFolder;
private boolean mIsOnlyOneItem; // 是否为唯一一个项目
private boolean mIsOneNoteFollowingFolder; // 是否为一个笔记跟随文件夹
private boolean mIsMultiNotesFollowingFolder; // 是否为多个笔记跟随文件夹
/**
* CursorNoteItemData
*
* @param context 访
* @param cursor Cursor
*/
public NoteItemData(Context context, Cursor cursor) { public NoteItemData(Context context, Cursor cursor) {
// 从Cursor中提取各项数据并赋值 mId = cursor.getLong(ID_COLUMN);
mId = cursor.getLong(ID_COLUMN); // 获取笔记ID 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); // 获取背景颜色ID 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); // 获取父ID 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); // 获取小部件ID 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);
} }
/**
* CursorNoteItemData
*
* @param cursor Cursor
*/
private void checkPostion(Cursor cursor) { private void checkPostion(Cursor cursor) {
// 更新位置状态信息 mIsLastItem = cursor.isLast() ? true : false;
mIsLastItem = cursor.isLast(); // 判断是否为最后一个项目 mIsFirstItem = cursor.isFirst() ? true : false;
mIsFirstItem = cursor.isFirst(); // 判断是否为第一个项目 mIsOnlyOneItem = (cursor.getCount() == 1);
mIsOnlyOneItem = (cursor.getCount() == 1); // 判断是否为唯一一个项目 mIsMultiNotesFollowingFolder = false;
mIsMultiNotesFollowingFolder = false; // 初始化多个笔记跟随文件夹状态 mIsOneNoteFollowingFolder = false;
mIsOneNoteFollowingFolder = false; // 初始化一个笔记跟随文件夹状态
if (mType == Notes.TYPE_NOTE && !mIsFirstItem) {
// 检查当前笔记是否跟随文件夹,并更新相应状态 int position = cursor.getPosition();
if (mType == Notes.TYPE_NOTE && !mIsFirstItem) { // 判断是否为笔记且不是第一个项目 if (cursor.moveToPrevious()) {
int position = cursor.getPosition(); // 获取当前位置
if (cursor.moveToPrevious()) { // 移动到前一个位置
if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER
|| cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) { // 判断前一个项目是否为文件夹或系统类型 || cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) {
if (cursor.getCount() > (position + 1)) { // 判断是否有多于一个项目 if (cursor.getCount() > (position + 1)) {
mIsMultiNotesFollowingFolder = true; // 设置多个笔记跟随文件夹状态 mIsMultiNotesFollowingFolder = true;
} else { } else {
mIsOneNoteFollowingFolder = true; // 设置一个笔记跟随文件夹状态 mIsOneNoteFollowingFolder = true;
} }
} }
// 确保Cursor能够回到原来的位置 if (!cursor.moveToNext()) {
if (!cursor.moveToNext()) { // 移动回原来的位置 throw new IllegalStateException("cursor move to previous but can't move back");
throw new IllegalStateException("cursor move to previous but can't move back"); // 抛出异常
} }
} }
} }
} }
// 以下为获取NoteItemData各项属性的方法
public boolean isOneFollowingFolder() { public boolean isOneFollowingFolder() {
return mIsOneNoteFollowingFolder; // 返回一个笔记跟随文件夹状态 return mIsOneNoteFollowingFolder;
} }
public boolean isMultiFollowingFolder() { public boolean isMultiFollowingFolder() {
return mIsMultiNotesFollowingFolder; // 返回多个笔记跟随文件夹状态 return mIsMultiNotesFollowingFolder;
} }
public boolean isLast() { public boolean isLast() {
return mIsLastItem; // 返回是否为最后一个项目 return mIsLastItem;
} }
public String getCallName() { public String getCallName() {
return mName; // 返回联系人名称 return mName;
} }
public boolean isFirst() { public boolean isFirst() {
return mIsFirstItem; // 返回是否为第一个项目 return mIsFirstItem;
} }
public boolean isSingle() { public boolean isSingle() {
return mIsOnlyOneItem; // 返回是否为唯一一个项目 return mIsOnlyOneItem;
} }
public long getId() { public long getId() {
return mId; // 返回笔记ID return mId;
} }
public long getAlertDate() { public long getAlertDate() {
return mAlertDate; // 返回提醒日期 return mAlertDate;
} }
public long getCreatedDate() { public long getCreatedDate() {
return mCreatedDate; // 返回创建日期 return mCreatedDate;
} }
public boolean hasAttachment() { public boolean hasAttachment() {
return mHasAttachment; // 返回是否有附件 return mHasAttachment;
} }
public long getModifiedDate() { public long getModifiedDate() {
return mModifiedDate; // 返回修改日期 return mModifiedDate;
} }
public int getBgColorId() { public int getBgColorId() {
return mBgColorId; // 返回背景颜色ID return mBgColorId;
} }
public long getParentId() { public long getParentId() {
return mParentId; // 返回父ID return mParentId;
} }
public int getNotesCount() { public int getNotesCount() {
return mNotesCount; // 返回笔记数量 return mNotesCount;
} }
public long getFolderId() { public long getFolderId () {
return mParentId; // 返回文件夹ID return mParentId;
} }
public int getType() { public int getType() {
return mType; // 返回类型 return mType;
} }
public int getWidgetType() { public int getWidgetType() {
return mWidgetType; // 返回小部件类型 return mWidgetType;
} }
public int getWidgetId() { public int getWidgetId() {
return mWidgetId; // 返回小部件ID return mWidgetId;
} }
public String getSnippet() { public String getSnippet() {
return mSnippet; // 返回摘要 return mSnippet;
} }
public boolean hasAlert() { public boolean hasAlert() {
return (mAlertDate > 0); // 返回是否有提醒 return (mAlertDate > 0);
} }
public boolean isCallRecord() { public boolean isCallRecord() {
return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber)); // 返回是否为通话记录笔记 return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber));
} }
/**
* Cursor
*
* @param cursor Cursor
* @return
*/
public static int getNoteType(Cursor cursor) { public static int getNoteType(Cursor cursor) {
return cursor.getInt(TYPE_COLUMN); // 返回笔记类型 return cursor.getInt(TYPE_COLUMN);
} }
} }

File diff suppressed because it is too large Load Diff

@ -14,253 +14,170 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.ui;
package net.micode.notes.ui; // 定义包名 import android.content.Context;
import android.database.Cursor;
import android.content.Context; // 导入Context类用于获取上下文 import android.util.Log;
import android.database.Cursor; // 导入Cursor类用于数据源游标 import android.view.View;
import android.util.Log; // 导入Log类用于日志输出 import android.view.ViewGroup;
import android.view.View; // 导入View类用于视图操作 import android.widget.CursorAdapter;
import android.view.ViewGroup; // 导入ViewGroup类用于视图组操作
import android.widget.CursorAdapter; // 导入CursorAdapter类用于游标适配器 import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes; // 导入Notes类用于笔记数据操作 import java.util.Collection;
import java.util.HashMap;
import java.util.Collection; // 导入Collection类用于集合操作 import java.util.HashSet;
import java.util.HashMap; // 导入HashMap类用于哈希映射 import java.util.Iterator;
import java.util.HashSet; // 导入HashSet类用于哈希集合
import java.util.Iterator; // 导入Iterator类用于迭代器
public class NotesListAdapter extends CursorAdapter {
/** private static final String TAG = "NotesListAdapter";
* CursorAdapter private Context mContext;
*/ private HashMap<Integer, Boolean> mSelectedIndex;
public class NotesListAdapter extends CursorAdapter { // 定义NotesListAdapter类继承自CursorAdapter private int mNotesCount;
private static final String TAG = "NotesListAdapter"; // 定义日志标签 private boolean mChoiceMode;
private Context mContext; // 上下文对象
// 用于存储选中项的索引和状态 public static class AppWidgetAttribute {
private HashMap<Integer, Boolean> mSelectedIndex; // 选中项索引和状态的哈希映射 public int widgetId;
private int mNotesCount; // 笔记总数 public int widgetType;
private boolean mChoiceMode; // 选择模式标志 };
/** public NotesListAdapter(Context context) {
* AppWidget super(context, null);
*/ mSelectedIndex = new HashMap<Integer, Boolean>();
public static class AppWidgetAttribute { // 定义AppWidgetAttribute类 mContext = context;
public int widgetId; // 小部件ID mNotesCount = 0;
public int widgetType; // 小部件类型
}
/**
*
*
* @param context
*/
public NotesListAdapter(Context context) { // 构造函数
super(context, null); // 调用父类构造函数
mSelectedIndex = new HashMap<Integer, Boolean>(); // 初始化选中项索引和状态的哈希映射
mContext = context; // 赋值上下文对象
mNotesCount = 0; // 初始化笔记总数
} }
/**
*
*
* @param context
* @param cursor
* @param parent
* @return
*/
@Override @Override
public View newView(Context context, Cursor cursor, ViewGroup parent) { // 重写newView方法 public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new NotesListItem(context); // 返回新的列表项视图 return new NotesListItem(context);
} }
/**
*
*
* @param view
* @param context
* @param cursor
*/
@Override @Override
public void bindView(View view, Context context, Cursor cursor) { // 重写bindView方法 public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof NotesListItem) { // 判断视图是否为NotesListItem类型 if (view instanceof NotesListItem) {
NoteItemData itemData = new NoteItemData(context, cursor); // 创建NoteItemData对象 NoteItemData itemData = new NoteItemData(context, cursor);
((NotesListItem) view).bind(context, itemData, mChoiceMode, ((NotesListItem) view).bind(context, itemData, mChoiceMode,
isSelectedItem(cursor.getPosition())); // 绑定数据到视图 isSelectedItem(cursor.getPosition()));
} }
} }
/** public void setCheckedItem(final int position, final boolean checked) {
* mSelectedIndex.put(position, checked);
* notifyDataSetChanged();
* @param position
* @param checked
*/
public void setCheckedItem(final int position, final boolean checked) { // 设置选中项方法
mSelectedIndex.put(position, checked); // 更新选中项索引和状态
notifyDataSetChanged(); // 通知数据集改变
} }
/** public boolean isInChoiceMode() {
* return mChoiceMode;
*
* @return
*/
public boolean isInChoiceMode() { // 获取选择模式方法
return mChoiceMode; // 返回选择模式状态
} }
/** public void setChoiceMode(boolean mode) {
* mSelectedIndex.clear();
* mChoiceMode = mode;
* @param mode
*/
public void setChoiceMode(boolean mode) { // 设置选择模式方法
mSelectedIndex.clear(); // 清空选中项索引和状态
mChoiceMode = mode; // 更新选择模式状态
} }
/** public void selectAll(boolean checked) {
* Cursor cursor = getCursor();
* for (int i = 0; i < getCount(); i++) {
* @param checked if (cursor.moveToPosition(i)) {
*/ if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) {
public void selectAll(boolean checked) { // 全选或全不选方法 setCheckedItem(i, checked);
Cursor cursor = getCursor(); // 获取游标
for (int i = 0; i < getCount(); i++) { // 遍历所有项
if (cursor.moveToPosition(i)) { // 移动到指定位置
if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) { // 判断是否为笔记类型
setCheckedItem(i, checked); // 设置选中状态
} }
} }
} }
} }
/** public HashSet<Long> getSelectedItemIds() {
* ID HashSet<Long> itemSet = new HashSet<Long>();
* for (Integer position : mSelectedIndex.keySet()) {
* @return IDHashSet if (mSelectedIndex.get(position) == true) {
*/ Long id = getItemId(position);
public HashSet<Long> getSelectedItemIds() { // 获取选中项ID集合方法 if (id == Notes.ID_ROOT_FOLDER) {
HashSet<Long> itemSet = new HashSet<Long>(); // 创建哈希集合 Log.d(TAG, "Wrong item id, should not happen");
for (Integer position : mSelectedIndex.keySet()) { // 遍历选中项索引
if (mSelectedIndex.get(position) == true) { // 判断是否为选中状态
Long id = getItemId(position); // 获取项ID
if (id == Notes.ID_ROOT_FOLDER) { // 判断是否为根文件夹
Log.d(TAG, "Wrong item id, should not happen"); // 输出日志
} else { } else {
itemSet.add(id); // 添加到哈希集合 itemSet.add(id);
} }
} }
} }
return itemSet; // 返回哈希集合 return itemSet;
} }
/** public HashSet<AppWidgetAttribute> getSelectedWidget() {
* HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>();
* for (Integer position : mSelectedIndex.keySet()) {
* @return HashSet if (mSelectedIndex.get(position) == true) {
*/ Cursor c = (Cursor) getItem(position);
public HashSet<AppWidgetAttribute> getSelectedWidget() { // 获取选中小部件属性集合方法 if (c != null) {
HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>(); // 创建哈希集合 AppWidgetAttribute widget = new AppWidgetAttribute();
for (Integer position : mSelectedIndex.keySet()) { // 遍历选中项索引 NoteItemData item = new NoteItemData(mContext, c);
if (mSelectedIndex.get(position) == true) { // 判断是否为选中状态 widget.widgetId = item.getWidgetId();
Cursor c = (Cursor) getItem(position); // 获取游标 widget.widgetType = item.getWidgetType();
if (c != null) { // 判断游标是否为空 itemSet.add(widget);
AppWidgetAttribute widget = new AppWidgetAttribute(); // 创建AppWidgetAttribute对象 /**
NoteItemData item = new NoteItemData(mContext, c); // 创建NoteItemData对象 * Don't close cursor here, only the adapter could close it
widget.widgetId = item.getWidgetId(); // 获取小部件ID */
widget.widgetType = item.getWidgetType(); // 获取小部件类型
itemSet.add(widget); // 添加到哈希集合
} else { } else {
Log.e(TAG, "Invalid cursor"); // 输出日志 Log.e(TAG, "Invalid cursor");
return null; // 返回空 return null;
} }
} }
} }
return itemSet; // 返回哈希集合 return itemSet;
} }
/** public int getSelectedCount() {
* Collection<Boolean> values = mSelectedIndex.values();
* if (null == values) {
* @return return 0;
*/
public int getSelectedCount() { // 获取选中项数量方法
Collection<Boolean> values = mSelectedIndex.values(); // 获取选中项状态集合
if (null == values) { // 判断集合是否为空
return 0; // 返回0
} }
Iterator<Boolean> iter = values.iterator(); // 获取迭代器 Iterator<Boolean> iter = values.iterator();
int count = 0; // 初始化计数器 int count = 0;
while (iter.hasNext()) { // 遍历集合 while (iter.hasNext()) {
if (true == iter.next()) { // 判断是否为选中状态 if (true == iter.next()) {
count++; // 计数器加1 count++;
} }
} }
return count; // 返回计数器 return count;
} }
/** public boolean isAllSelected() {
* int checkedCount = getSelectedCount();
* return (checkedCount != 0 && checkedCount == mNotesCount);
* @return
*/
public boolean isAllSelected() { // 判断是否全部选中方法
int checkedCount = getSelectedCount(); // 获取选中项数量
return (checkedCount != 0 && checkedCount == mNotesCount); // 判断是否全部选中
} }
/** public boolean isSelectedItem(final int position) {
* if (null == mSelectedIndex.get(position)) {
* return false;
* @param position
* @return
*/
public boolean isSelectedItem(final int position) { // 检查选中项方法
if (null == mSelectedIndex.get(position)) { // 判断是否为空
return false; // 返回未选中状态
} }
return mSelectedIndex.get(position); // 返回选中状态 return mSelectedIndex.get(position);
} }
/**
*
*/
@Override @Override
protected void onContentChanged() { // 重写onContentChanged方法 protected void onContentChanged() {
super.onContentChanged(); // 调用父类方法 super.onContentChanged();
calcNotesCount(); // 计算笔记数量 calcNotesCount();
} }
/**
*
*
* @param cursor
*/
@Override @Override
public void changeCursor(Cursor cursor) { // 重写changeCursor方法 public void changeCursor(Cursor cursor) {
super.changeCursor(cursor); // 调用父类方法 super.changeCursor(cursor);
calcNotesCount(); // 计算笔记数量 calcNotesCount();
} }
/** private void calcNotesCount() {
* mNotesCount = 0;
*/ for (int i = 0; i < getCount(); i++) {
private void calcNotesCount() { // 计算笔记数量方法 Cursor c = (Cursor) getItem(i);
mNotesCount = 0; // 初始化笔记总数 if (c != null) {
for (int i = 0; i < getCount(); i++) { // 遍历所有项 if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) {
Cursor c = (Cursor) getItem(i); // 获取游标 mNotesCount++;
if (c != null) { // 判断游标是否为空
if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) { // 判断是否为笔记类型
mNotesCount++; // 笔记总数加1
} }
} else { } else {
Log.e(TAG, "Invalid cursor"); // 输出日志 Log.e(TAG, "Invalid cursor");
return; // 返回 return;
} }
} }
} }

@ -14,143 +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.content.Context; // 导入Context类用于获取上下文 import android.text.format.DateUtils;
import android.text.format.DateUtils; // 导入DateUtils类用于日期格式化 import android.view.View;
import android.view.View; // 导入View类用于视图操作 import android.widget.CheckBox;
import android.widget.CheckBox; // 导入CheckBox类用于复选框 import android.widget.ImageView;
import android.widget.ImageView; // 导入ImageView类用于图像显示 import android.widget.LinearLayout;
import android.widget.LinearLayout; // 导入LinearLayout类用于线性布局 import android.widget.TextView;
import android.widget.TextView; // 导入TextView类用于文本显示
import net.micode.notes.R;
import net.micode.notes.R; // 导入R类用于资源引用 import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes; // 导入Notes类用于笔记数据操作 import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.DataUtils; // 导入DataUtils类用于数据处理 import net.micode.notes.tool.ResourceParser.NoteItemBgResources;
import net.micode.notes.tool.ResourceParser.NoteItemBgResources; // 导入NoteItemBgResources类用于背景资源解析
/* public class NotesListItem extends LinearLayout {
* LinearLayout private ImageView mAlert;
* UI private TextView mTitle;
*/ private TextView mTime;
private TextView mCallName;
public class NotesListItem extends LinearLayout { // 定义NotesListItem类继承自LinearLayout private NoteItemData mItemData;
private ImageView mAlert; // 用于显示提醒图标 private CheckBox mCheckBox;
private TextView mTitle; // 显示笔记标题
private TextView mTime; // 显示修改时间 public NotesListItem(Context context) {
private TextView mCallName; // 在通话记录笔记中显示通话名称 super(context);
private NoteItemData mItemData; // 绑定的笔记数据 inflate(context, R.layout.note_item, this);
private CheckBox mCheckBox; // 选择框,用于多选模式 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);
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); // 初始化复选框
} }
/* public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) {
* if (choiceMode && data.getType() == Notes.TYPE_NOTE) {
* mCheckBox.setVisibility(View.VISIBLE);
* @param context mCheckBox.setChecked(checked);
* @param data
* @param choiceMode
* @param checked
*/
public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) { // 绑定数据方法
// 根据是否为选择模式和笔记类型,控制复选框的可见性和选中状态
if (choiceMode && data.getType() == Notes.TYPE_NOTE) { // 判断是否为选择模式且为笔记类型
mCheckBox.setVisibility(View.VISIBLE); // 显示复选框
mCheckBox.setChecked(checked); // 设置复选框选中状态
} else { } else {
mCheckBox.setVisibility(View.GONE); // 隐藏复选框 mCheckBox.setVisibility(View.GONE);
} }
mItemData = data; // 赋值笔记数据 mItemData = data;
// 根据笔记类型和状态,设置标题、提醒图标和背景 if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { // 判断是否为通话记录文件夹 mCallName.setVisibility(View.GONE);
// 通话记录文件夹 mAlert.setVisibility(View.VISIBLE);
mCallName.setVisibility(View.GONE); // 隐藏通话名称 mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
mAlert.setVisibility(View.VISIBLE); // 显示提醒图标
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); // 设置标题样式
mTitle.setText(context.getString(R.string.call_record_folder_name) mTitle.setText(context.getString(R.string.call_record_folder_name)
+ context.getString(R.string.format_folder_files_count, data.getNotesCount())); // 设置标题文本 + context.getString(R.string.format_folder_files_count, data.getNotesCount()));
mAlert.setImageResource(R.drawable.call_record); // 设置提醒图标 mAlert.setImageResource(R.drawable.call_record);
} else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) { // 判断是否为通话记录笔记 } else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) {
// 通话记录笔记 mCallName.setVisibility(View.VISIBLE);
mCallName.setVisibility(View.VISIBLE); // 显示通话名称 mCallName.setText(data.getCallName());
mCallName.setText(data.getCallName()); // 设置通话名称 mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem);
mTitle.setTextAppearance(context, R.style.TextAppearanceSecondaryItem); // 设置标题样式 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);
} }
} else { } else {
// 其他类型的笔记或文件夹 mCallName.setVisibility(View.GONE);
mCallName.setVisibility(View.GONE); // 隐藏通话名称 mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
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) {
* int id = data.getBgColorId();
*/ if (data.getType() == Notes.TYPE_NOTE) {
private void setBackground(NoteItemData data) { // 设置背景方法 if (data.isSingle() || data.isOneFollowingFolder()) {
int id = data.getBgColorId(); // 获取背景颜色ID setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id));
if (data.getType() == Notes.TYPE_NOTE) { // 判断是否为笔记类型 } else if (data.isLast()) {
// 根据笔记的状态设置不同的背景资源 setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id));
if (data.isSingle() || data.isOneFollowingFolder()) { // 判断是否为单个笔记或紧跟文件夹的笔记 } else if (data.isFirst() || data.isMultiFollowingFolder()) {
setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id)); // 设置单个笔记背景 setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id));
} else if (data.isLast()) { // 判断是否为最后一个笔记
setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id)); // 设置最后一个笔记背景
} else if (data.isFirst() || data.isMultiFollowingFolder()) { // 判断是否为第一个笔记或多个紧跟文件夹的笔记
setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id)); // 设置第一个笔记背景
} else { } else {
setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id)); // 设置普通笔记背景 setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id));
} }
} else { } else {
// 文件夹背景资源 setBackgroundResource(NoteItemBgResources.getFolderBgRes());
setBackgroundResource(NoteItemBgResources.getFolderBgRes()); // 设置文件夹背景
} }
} }
/* public NoteItemData getItemData() {
* return mItemData;
*
* @return NoteItemData
*/
public NoteItemData getItemData() { // 获取笔记数据方法
return mItemData; // 返回笔记数据
} }
} }

@ -13,9 +13,9 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* 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;
@ -41,64 +41,59 @@ 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_SET_BG_COLOR_KEY = "pref_key_bg_random_appear"; // 设置背景颜色的键 public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time";
private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key"; // 同步账户的键
private static final String AUTHORITIES_FILTER_KEY = "authorities"; // 权限过滤键 public static final String PREFERENCE_SET_BG_COLOR_KEY = "pref_key_bg_random_appear";
// 类成员变量定义部分主要用于账户同步和UI更新 private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key";
private PreferenceCategory mAccountCategory; // 账户分类偏好项
private GTaskReceiver mReceiver; // 接收同步任务的广播接收器 private static final String AUTHORITIES_FILTER_KEY = "authorities";
private Account[] mOriAccounts; // 原始账户数组
private boolean mHasAddedAccount; // 标记是否已添加新账户 private PreferenceCategory mAccountCategory;
/** private GTaskReceiver mReceiver;
* Activity
* private Account[] mOriAccounts;
*
* @param icicle ActivityBundle private boolean mHasAddedAccount;
*/
@Override @Override
protected void onCreate(Bundle icicle) { protected void onCreate(Bundle icicle) {
super.onCreate(icicle); super.onCreate(icicle);
// 设置返回按钮 /* using the app icon for navigation */
getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setDisplayHomeAsUpEnabled(true);
// 从XML加载偏好设置
addPreferencesFromResource(R.xml.preferences); addPreferencesFromResource(R.xml.preferences);
mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY); mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY);
mReceiver = new GTaskReceiver(); mReceiver = new GTaskReceiver();
IntentFilter filter = new IntentFilter(); IntentFilter filter = new IntentFilter();
filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME); filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME);
registerReceiver(mReceiver, filter); // 注册广播接收器以监听同步服务 registerReceiver(mReceiver, filter);
mOriAccounts = null; mOriAccounts = null;
// 添加设置头部视图
View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null); View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null);
getListView().addHeaderView(header, null, true); getListView().addHeaderView(header, null, true);
} }
/**
* Activity
*
*/
@Override @Override
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
// 自动设置新添加的账户进行同步 // need to set sync account automatically if user has added a new
// account
if (mHasAddedAccount) { if (mHasAddedAccount) {
Account[] accounts = getGoogleAccounts(); Account[] accounts = getGoogleAccounts();
if (mOriAccounts != null && accounts.length > mOriAccounts.length) { if (mOriAccounts != null && accounts.length > mOriAccounts.length) {
@ -111,144 +106,120 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
} }
if (!found) { if (!found) {
setSyncAccount(accountNew.name); // 设置新账户进行同步 setSyncAccount(accountNew.name);
break; break;
} }
} }
} }
} }
// 刷新UI
refreshUI(); refreshUI();
} }
/**
* Activity广
*/
@Override @Override
protected void onDestroy() { protected void onDestroy() {
if (mReceiver != null) { if (mReceiver != null) {
unregisterReceiver(mReceiver); // 注销广播接收器,避免内存泄漏 unregisterReceiver(mReceiver);
} }
super.onDestroy(); super.onDestroy();
} }
/**
*
*/
private void loadAccountPreference() { private void loadAccountPreference() {
mAccountCategory.removeAll(); // 清空账户分类下的所有条目 mAccountCategory.removeAll();
// 创建并配置账户偏好项
Preference accountPref = new Preference(this); Preference accountPref = new Preference(this);
final String defaultAccount = getSyncAccountName(this); // 获取默认同步账户名称 final String defaultAccount = getSyncAccountName(this);
accountPref.setTitle(getString(R.string.preferences_account_title)); // 设置标题 accountPref.setTitle(getString(R.string.preferences_account_title));
accountPref.setSummary(getString(R.string.preferences_account_summary)); // 设置摘要 accountPref.setSummary(getString(R.string.preferences_account_summary));
accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() { accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) { public boolean onPreferenceClick(Preference preference) {
// 处理账户点击事件
if (!GTaskSyncService.isSyncing()) { if (!GTaskSyncService.isSyncing()) {
if (TextUtils.isEmpty(defaultAccount)) { if (TextUtils.isEmpty(defaultAccount)) {
// 如果尚未设置账户,则展示选择账户对话框 // the first time to set account
showSelectAccountAlertDialog(); showSelectAccountAlertDialog();
} else { } else {
// 如果已经设置账户,则展示更改账户确认对话框 // if the account has already been set, we need to promp
// user about the risk
showChangeAccountConfirmAlertDialog(); showChangeAccountConfirmAlertDialog();
} }
} else { } else {
// 如果正在同步中,则展示无法更改账户的提示
Toast.makeText(NotesPreferenceActivity.this, Toast.makeText(NotesPreferenceActivity.this,
R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT) R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT)
.show(); .show();
} }
return true; return true;
} }
}); });
mAccountCategory.addPreference(accountPref); // 将账户偏好项添加到账户分类下 mAccountCategory.addPreference(accountPref);
} }
/**
*
*/
private void loadSyncButton() { private void loadSyncButton() {
Button syncButton = (Button) findViewById(R.id.preference_sync_button); // 获取同步按钮 Button syncButton = (Button) findViewById(R.id.preference_sync_button);
TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview); // 获取上次同步时间视图 TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
// 根据同步状态设置按钮文本和点击事件 // set button state
if (GTaskSyncService.isSyncing()) { if (GTaskSyncService.isSyncing()) {
syncButton.setText(getString(R.string.preferences_button_sync_cancel)); // 设置为取消同步文本 syncButton.setText(getString(R.string.preferences_button_sync_cancel));
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.cancelSync(NotesPreferenceActivity.this);
} }
}); });
} else { } else {
syncButton.setText(getString(R.string.preferences_button_sync_immediately)); // 设置为立即同步文本 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.startSync(NotesPreferenceActivity.this); // 设置点击事件为开始同步 GTaskSyncService.startSync(NotesPreferenceActivity.this);
} }
}); });
} }
syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this))); // 只有在设置了同步账户时才使能同步按钮 syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this)));
// 根据同步状态设置上次同步时间的显示 // set last sync time
if (GTaskSyncService.isSyncing()) { if (GTaskSyncService.isSyncing()) {
lastSyncTimeView.setText(GTaskSyncService.getProgressString()); // 如果正在同步,显示进度信息 lastSyncTimeView.setText(GTaskSyncService.getProgressString());
lastSyncTimeView.setVisibility(View.VISIBLE); // 显示上次同步时间视图 lastSyncTimeView.setVisibility(View.VISIBLE);
} else { } else {
long lastSyncTime = getLastSyncTime(this); // 获取上次同步时间 long lastSyncTime = getLastSyncTime(this);
if (lastSyncTime != 0) { if (lastSyncTime != 0) {
lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time, lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time,
DateFormat.format(getString(R.string.preferences_last_sync_time_format), DateFormat.format(getString(R.string.preferences_last_sync_time_format),
lastSyncTime))); // 格式化并显示上次同步时间 lastSyncTime)));
lastSyncTimeView.setVisibility(View.VISIBLE); // 显示上次同步时间视图 lastSyncTimeView.setVisibility(View.VISIBLE);
} else { } else {
lastSyncTimeView.setVisibility(View.GONE); // 如果未同步过,则隐藏上次同步时间视图 lastSyncTimeView.setVisibility(View.GONE);
} }
} }
} }
/**
*
*/
private void refreshUI() { private void refreshUI() {
loadAccountPreference(); // 加载账户偏好设置 loadAccountPreference();
loadSyncButton(); // 加载同步按钮 loadSyncButton();
} }
/**
*
* Google
*
*/
private void showSelectAccountAlertDialog() { private void showSelectAccountAlertDialog() {
// 创建对话框构建器并设置自定义标题
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title); TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_select_account_title)); titleTextView.setText(getString(R.string.preferences_dialog_select_account_title));
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle); TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips)); subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips));
dialogBuilder.setCustomTitle(titleView); dialogBuilder.setCustomTitle(titleView);
dialogBuilder.setPositiveButton(null, null); // 移除默认的确定按钮 dialogBuilder.setPositiveButton(null, null);
// 获取当前设备上的Google账户
Account[] accounts = getGoogleAccounts(); Account[] accounts = getGoogleAccounts();
String defAccount = getSyncAccountName(this); // 获取当前同步的账户名称 String defAccount = getSyncAccountName(this);
mOriAccounts = accounts; // 保存原始账户列表 mOriAccounts = accounts;
mHasAddedAccount = false; // 标记是否已添加新账户 mHasAddedAccount = false;
if (accounts.length > 0) { if (accounts.length > 0) {
// 创建账户选项并设置选中项
CharSequence[] items = new CharSequence[accounts.length]; CharSequence[] items = new CharSequence[accounts.length];
final CharSequence[] itemMapping = items; final CharSequence[] itemMapping = items;
int checkedItem = -1; // 记录默认选中的账户 int checkedItem = -1;
int index = 0; int index = 0;
for (Account account : accounts) { for (Account account : accounts) {
if (TextUtils.equals(account.name, defAccount)) { if (TextUtils.equals(account.name, defAccount)) {
@ -256,7 +227,6 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
items[index++] = account.name; items[index++] = account.name;
} }
// 设置单选列表,并为选中的账户执行同步操作
dialogBuilder.setSingleChoiceItems(items, checkedItem, dialogBuilder.setSingleChoiceItems(items, checkedItem,
new DialogInterface.OnClickListener() { new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
@ -266,34 +236,27 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
}); });
} }
// 添加“添加账户”选项
View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null); View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null);
dialogBuilder.setView(addAccountView); dialogBuilder.setView(addAccountView);
final AlertDialog dialog = dialogBuilder.show(); final AlertDialog dialog = dialogBuilder.show();
// 点击“添加账户”执行添加账户操作
addAccountView.setOnClickListener(new View.OnClickListener() { addAccountView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { public void onClick(View v) {
mHasAddedAccount = true; mHasAddedAccount = true;
Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS"); Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
intent.putExtra(AUTHORITIES_FILTER_KEY, new String[]{ intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] {
"gmail-ls" "gmail-ls"
}); });
startActivityForResult(intent, -1); startActivityForResult(intent, -1);
dialog.dismiss(); dialog.dismiss();
} }
}); });
} }
/**
*
*
*/
private void showChangeAccountConfirmAlertDialog() { private void showChangeAccountConfirmAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// 设置自定义标题,包含当前同步账户名称
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title); TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_change_account_title, titleTextView.setText(getString(R.string.preferences_dialog_change_account_title,
@ -301,9 +264,8 @@ public class NotesPreferenceActivity extends PreferenceActivity {
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle); TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg)); subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg));
dialogBuilder.setCustomTitle(titleView); dialogBuilder.setCustomTitle(titleView);
// 创建菜单项并设置点击事件 CharSequence[] menuItemArray = new CharSequence[] {
CharSequence[] menuItemArray = new CharSequence[]{
getString(R.string.preferences_menu_change_account), getString(R.string.preferences_menu_change_account),
getString(R.string.preferences_menu_remove_account), getString(R.string.preferences_menu_remove_account),
getString(R.string.preferences_menu_cancel) getString(R.string.preferences_menu_cancel)
@ -311,10 +273,8 @@ public class NotesPreferenceActivity extends PreferenceActivity {
dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() { dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
if (which == 0) { if (which == 0) {
// 选择更改账户,显示账户选择对话框
showSelectAccountAlertDialog(); showSelectAccountAlertDialog();
} else if (which == 1) { } else if (which == 1) {
// 选择移除账户执行移除操作并刷新UI
removeSyncAccount(); removeSyncAccount();
refreshUI(); refreshUI();
} }
@ -322,41 +282,27 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}); });
dialogBuilder.show(); dialogBuilder.show();
} }
/**
* Google
*
* @return Account[] com.google
*/
private Account[] getGoogleAccounts() { private Account[] getGoogleAccounts() {
AccountManager accountManager = AccountManager.get(this); AccountManager accountManager = AccountManager.get(this);
return accountManager.getAccountsByType("com.google"); return accountManager.getAccountsByType("com.google");
} }
/**
*
* SharedPreferencesgtask
*
* @param account
*/
private void setSyncAccount(String account) { private void setSyncAccount(String account) {
// 检查当前账户是否与传入账户名一致,不一致则更新账户信息
if (!getSyncAccountName(this).equals(account)) { if (!getSyncAccountName(this).equals(account)) {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit(); SharedPreferences.Editor editor = settings.edit();
// 如果账户名非空,则保存账户名,否则清除账户名
if (account != null) { if (account != null) {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account); editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account);
} else { } else {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
} }
editor.commit(); editor.commit();
// 清理上次同步时间 // clean up last sync time
setLastSyncTime(this, 0); setLastSyncTime(this, 0);
// 清理本地相关的gtask信息 // clean up local gtask related info
new Thread(new Runnable() { new Thread(new Runnable() {
public void run() { public void run() {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
@ -365,32 +311,25 @@ public class NotesPreferenceActivity extends PreferenceActivity {
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null); getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
} }
}).start(); }).start();
// 显示设置成功的提示信息
Toast.makeText(NotesPreferenceActivity.this, Toast.makeText(NotesPreferenceActivity.this,
getString(R.string.preferences_toast_success_set_accout, account), getString(R.string.preferences_toast_success_set_accout, account),
Toast.LENGTH_SHORT).show(); Toast.LENGTH_SHORT).show();
} }
} }
/**
*
* SharedPreferencesgtask
*/
private void removeSyncAccount() { private void removeSyncAccount() {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit(); SharedPreferences.Editor editor = settings.edit();
// 如果存在账户信息,则移除
if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) { if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) {
editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME); editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME);
} }
// 如果存在上次同步时间信息,则移除
if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) { if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) {
editor.remove(PREFERENCE_LAST_SYNC_TIME); editor.remove(PREFERENCE_LAST_SYNC_TIME);
} }
editor.commit(); editor.commit();
// 清理本地相关的gtask信息 // clean up local gtask related info
new Thread(new Runnable() { new Thread(new Runnable() {
public void run() { public void run() {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
@ -400,27 +339,13 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
}).start(); }).start();
} }
/**
*
* SharedPreferences
*
* @param context
* @return
*/
public static String getSyncAccountName(Context context) { public static String getSyncAccountName(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE); Context.MODE_PRIVATE);
return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
} }
/**
*
* SharedPreferences
*
* @param context
* @param time
*/
public static void setLastSyncTime(Context context, long time) { public static void setLastSyncTime(Context context, long time) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE); Context.MODE_PRIVATE);
@ -428,48 +353,30 @@ public class NotesPreferenceActivity extends PreferenceActivity {
editor.putLong(PREFERENCE_LAST_SYNC_TIME, time); editor.putLong(PREFERENCE_LAST_SYNC_TIME, time);
editor.commit(); editor.commit();
} }
/**
*
* SharedPreferences0
*
* @param context
* @return
*/
public static long getLastSyncTime(Context context) { public static long getLastSyncTime(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE); Context.MODE_PRIVATE);
return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0); return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0);
} }
/**
* 广gtask广UI
*/
private class GTaskReceiver extends BroadcastReceiver { private class GTaskReceiver extends BroadcastReceiver {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
refreshUI(); refreshUI();
// 如果广播消息表明正在同步则更新UI显示的同步状态信息
if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) { if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) {
TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview); TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
syncStatus.setText(intent syncStatus.setText(intent
.getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG)); .getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG));
} }
} }
} }
/**
*
*
* @param item
* @return truefalse
*/
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) { switch (item.getItemId()) {
case android.R.id.home: case android.R.id.home:
// 当选择返回按钮时启动NotesListActivity并清除当前活动栈顶以上的所有活动
Intent intent = new Intent(this, NotesListActivity.class); Intent intent = new Intent(this, NotesListActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent); startActivity(intent);

@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
//桌面挂件//
package net.micode.notes.widget; package net.micode.notes.widget;
import android.app.PendingIntent; import android.app.PendingIntent;
import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetManager;

@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
//二倍大小的桌面挂件//
package net.micode.notes.widget; package net.micode.notes.widget;
import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetManager;

@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
//四倍大小的桌面挂件//
package net.micode.notes.widget; package net.micode.notes.widget;
import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetManager;

Loading…
Cancel
Save