pull/6/head
yj 2 months ago
parent eb051cf5ee
commit 282e4e4843

@ -0,0 +1,163 @@
/*
* 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;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.view.Window;
import android.view.WindowManager;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.DataUtils;
import java.io.IOException;
public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener {
private long mNoteId; // 存储笔记的 ID
private String mSnippet; // 存储笔记的简短内容(摘要)
private static final int SNIPPET_PREW_MAX_LEN = 60; // 摘要最大长度
MediaPlayer mPlayer; // 用于播放闹铃音的媒体播放器
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); // 请求无标题窗口
final Window win = getWindow();
win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); // 当屏幕锁定时仍然显示窗口
// 如果屏幕关闭,保持屏幕亮起
if (!isScreenOn()) {
win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
| WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
| WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR);
}
Intent intent = getIntent(); // 获取传递进来的 Intent
try {
mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1)); // 获取笔记的 ID
// 获取笔记的简短摘要,如果摘要太长,截取并附加说明
mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId);
mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0,
SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info)
: mSnippet;
} catch (IllegalArgumentException e) {
e.printStackTrace();
return; // 如果获取笔记信息失败,则返回
}
mPlayer = new MediaPlayer(); // 初始化媒体播放器
// 如果笔记在数据库中是可见的,显示对话框并播放闹铃音
if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) {
showActionDialog();
playAlarmSound();
} else {
finish(); // 如果笔记不可见,则结束此活动
}
}
// 检查屏幕是否开启
private boolean isScreenOn() {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
return pm.isScreenOn();
}
// 播放闹铃音
private void playAlarmSound() {
// 获取系统的默认闹铃音 URI
Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);
// 获取当前铃声模式,检查闹铃是否会被静音
int silentModeStreams = Settings.System.getInt(getContentResolver(),
Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);
// 根据静音模式设置音频流类型
if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) {
mPlayer.setAudioStreamType(silentModeStreams);
} else {
mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); // 设置音频流类型为闹铃
}
try {
// 设置闹铃音频数据源,并准备播放
mPlayer.setDataSource(this, url);
mPlayer.prepare();
mPlayer.setLooping(true); // 设置闹铃音循环播放
mPlayer.start(); // 开始播放
} catch (IllegalArgumentException | SecurityException | IllegalStateException | IOException e) {
// 捕获并打印异常
e.printStackTrace();
}
}
// 显示提示操作对话框
private void showActionDialog() {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle(R.string.app_name); // 设置对话框标题为应用名称
dialog.setMessage(mSnippet); // 显示笔记的简短摘要
dialog.setPositiveButton(R.string.notealert_ok, this); // 设置“确定”按钮
// 如果屏幕开启,设置“进入”按钮
if (isScreenOn()) {
dialog.setNegativeButton(R.string.notealert_enter, this);
}
dialog.show().setOnDismissListener(this); // 显示对话框并设置监听器
}
// 处理按钮点击事件
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_NEGATIVE:
// 如果点击了“进入”按钮,启动编辑笔记活动
Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_VIEW); // 设置意图为查看笔记
intent.putExtra(Intent.EXTRA_UID, mNoteId); // 传递笔记 ID
startActivity(intent); // 启动活动
break;
default:
break;
}
}
// 对话框关闭时停止播放闹铃音
public void onDismiss(DialogInterface dialog) {
stopAlarmSound();
finish(); // 结束当前活动
}
// 停止播放闹铃音
private void stopAlarmSound() {
if (mPlayer != null) {
mPlayer.stop(); // 停止播放
mPlayer.release(); // 释放播放器资源
mPlayer = null; // 清空播放器对象
}
}
}

@ -0,0 +1,81 @@
/*
* 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;
import android.app.AlarmManager; // 引入AlarmManager用于设置系统闹铃
import android.app.PendingIntent; // 引入PendingIntent用于延迟执行的操作
import android.content.BroadcastReceiver; // 引入广播接收器,监听系统广播
import android.content.ContentUris; // 引入ContentUris用于构造URI
import android.content.Context; // 引入Context用于访问应用环境
import android.content.Intent; // 引入Intent用于启动其他活动或服务
import android.database.Cursor; // 引入Cursor用于查询数据库结果
import net.micode.notes.data.Notes; // 引入Notes类表示笔记相关的数据模型
import net.micode.notes.data.Notes.NoteColumns; // 引入NoteColumns类表示笔记数据表的字段
public class AlarmInitReceiver extends BroadcastReceiver {
// 定义查询数据库时需要的字段ID和警报日期
private static final String [] PROJECTION = new String [] {
NoteColumns.ID, // 笔记的ID
NoteColumns.ALERTED_DATE // 笔记的警报日期
};
private static final int COLUMN_ID = 0; // 表示ID字段的索引
private static final int COLUMN_ALERTED_DATE = 1; // 表示警报日期字段的索引
@Override
public void onReceive(Context context, Intent intent) {
// 获取当前系统时间
long currentDate = System.currentTimeMillis();
// 查询数据库,获取那些警报日期大于当前时间的笔记
Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI, // 笔记内容提供者的URI
PROJECTION, // 查询的字段ID和警报日期
NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE, // 查询条件:警报日期大于当前时间,且类型是笔记
new String[] { String.valueOf(currentDate) }, // 当前时间作为查询条件
null); // 排序方式为空
// 如果查询结果不为空
if (c != null) {
// 如果数据库中存在符合条件的记录,遍历每条记录
if (c.moveToFirst()) {
do {
long alertDate = c.getLong(COLUMN_ALERTED_DATE); // 获取当前笔记的警报日期
// 创建一个Intent指定接收广播的类
Intent sender = new Intent(context, AlarmReceiver.class);
// 设置Intent的Data为当前笔记的URI
sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID)));
// 创建一个PendingIntent用于延迟发送广播
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0);
// 获取系统的AlarmManager服务
AlarmManager alermManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
// 设置闹铃使用RTC_WAKEUP触发闹铃唤醒设备并在指定时间触发广播
alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);
} while (c.moveToNext()); // 继续处理下一条记录
}
// 关闭游标,释放数据库资源
c.close();
}
}
}

@ -0,0 +1,47 @@
/*
* 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;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
/**
* AlarmReceiver 广
* 广 AlarmAlertActivity
*/
public class AlarmReceiver extends BroadcastReceiver {
/**
* 广
* AlarmAlertActivity
*
* @param context
* @param intent 广
*/
@Override
public void onReceive(Context context, Intent intent) {
// 设置 intent 的目标活动为 AlarmAlertActivity
intent.setClass(context, AlarmAlertActivity.class);
// 添加 FLAG 来启动新的任务栈,这样 AlarmAlertActivity 会作为一个新的活动启动
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// 启动 AlarmAlertActivity
context.startActivity(intent);
}
}

@ -0,0 +1,437 @@
/*
* 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;
import java.text.DateFormatSymbols;
import java.util.Calendar;
import net.micode.notes.R;
import android.content.Context;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.NumberPicker;
/**
*
* AM/PM
*/
public class DateTimePicker extends FrameLayout {
// 常量定义,用于限制控件选择的值
private static final boolean DEFAULT_ENABLE_STATE = true;
private static final int HOURS_IN_HALF_DAY = 12; // 半天小时数
private static final int HOURS_IN_ALL_DAY = 24; // 一天的小时数
private static final int DAYS_IN_ALL_WEEK = 7; // 一周的天数
private static final int DATE_SPINNER_MIN_VAL = 0; // 日期选择器最小值
private static final int DATE_SPINNER_MAX_VAL = DAYS_IN_ALL_WEEK - 1; // 日期选择器最大值
private static final int HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW = 0; // 24小时制小时选择器最小值
private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23; // 24小时制小时选择器最大值
private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1; // 12小时制小时选择器最小值
private static final int HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW = 12; // 12小时制小时选择器最大值
private static final int MINUT_SPINNER_MIN_VAL = 0; // 分钟选择器最小值
private static final int MINUT_SPINNER_MAX_VAL = 59; // 分钟选择器最大值
private static final int AMPM_SPINNER_MIN_VAL = 0; // AM/PM选择器最小值
private static final int AMPM_SPINNER_MAX_VAL = 1; // AM/PM选择器最大值
// 控件定义
private final NumberPicker mDateSpinner; // 日期选择器
private final NumberPicker mHourSpinner; // 小时选择器
private final NumberPicker mMinuteSpinner; // 分钟选择器
private final NumberPicker mAmPmSpinner; // AM/PM选择器
private Calendar mDate; // 存储当前日期和时间的 Calendar 对象
// 日期显示的值数组
private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK];
// 当前是 AM 还是 PM
private boolean mIsAm;
// 是否为 24 小时制
private boolean mIs24HourView;
// 控件是否可用
private boolean mIsEnabled = DEFAULT_ENABLE_STATE;
// 初始化状态
private boolean mInitialising;
// 日期时间变化监听器
private OnDateTimeChangedListener mOnDateTimeChangedListener;
// 日期选择器值变化监听器
private NumberPicker.OnValueChangeListener mOnDateChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// 更新日期
mDate.add(Calendar.DAY_OF_YEAR, newVal - oldVal);
updateDateControl(); // 更新日期选择器
onDateTimeChanged(); // 通知日期时间变化
}
};
// 小时选择器值变化监听器
private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
boolean isDateChanged = false;
Calendar cal = Calendar.getInstance();
if (!mIs24HourView) {
// 12小时制模式下处理AM/PM的变化
if (!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1);
isDateChanged = true;
} else if (mIsAm && oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -1);
isDateChanged = true;
}
if (oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY ||
oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
mIsAm = !mIsAm;
updateAmPmControl(); // 更新AM/PM选择器
}
} else {
// 24小时制模式下处理日期变化
if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1);
isDateChanged = true;
} else if (oldVal == 0 && newVal == HOURS_IN_ALL_DAY - 1) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -1);
isDateChanged = true;
}
}
// 更新小时
int newHour = mHourSpinner.getValue() % HOURS_IN_HALF_DAY + (mIsAm ? 0 : HOURS_IN_HALF_DAY);
mDate.set(Calendar.HOUR_OF_DAY, newHour);
onDateTimeChanged(); // 通知日期时间变化
// 如果日期发生变化,更新年份、月份、日期
if (isDateChanged) {
setCurrentYear(cal.get(Calendar.YEAR));
setCurrentMonth(cal.get(Calendar.MONTH));
setCurrentDay(cal.get(Calendar.DAY_OF_MONTH));
}
}
};
// 分钟选择器值变化监听器
private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// 更新分钟
mDate.set(Calendar.MINUTE, newVal);
onDateTimeChanged(); // 通知日期时间变化
}
};
// AM/PM选择器值变化监听器
private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
mIsAm = !mIsAm;
// 根据AM/PM的选择调整小时
if (mIsAm) {
mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY);
} else {
mDate.add(Calendar.HOUR_OF_DAY, HOURS_IN_HALF_DAY);
}
updateAmPmControl(); // 更新AM/PM控制
onDateTimeChanged(); // 通知日期时间变化
}
};
// 日期时间变化监听器接口
public interface OnDateTimeChangedListener {
void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute);
}
// 构造函数,初始化日期时间选择器
public DateTimePicker(Context context) {
this(context, System.currentTimeMillis());
}
// 构造函数,初始化日期时间选择器,并传入日期
public DateTimePicker(Context context, long date) {
this(context, date, DateFormat.is24HourFormat(context));
}
// 构造函数初始化日期时间选择器并传入日期和是否24小时制
public DateTimePicker(Context context, long date, boolean is24HourView) {
super(context);
mDate = Calendar.getInstance();
mInitialising = true;
mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY;
inflate(context, R.layout.datetime_picker, this); // 加载自定义布局
// 初始化日期选择器控件
mDateSpinner = (NumberPicker) findViewById(R.id.date);
mDateSpinner.setMinValue(DATE_SPINNER_MIN_VAL);
mDateSpinner.setMaxValue(DATE_SPINNER_MAX_VAL);
mDateSpinner.setOnValueChangedListener(mOnDateChangedListener);
// 初始化小时选择器控件
mHourSpinner = (NumberPicker) findViewById(R.id.hour);
mHourSpinner.setOnValueChangedListener(mOnHourChangedListener);
// 初始化分钟选择器控件
mMinuteSpinner = (NumberPicker) findViewById(R.id.minute);
mMinuteSpinner.setMinValue(MINUT_SPINNER_MIN_VAL);
mMinuteSpinner.setMaxValue(MINUT_SPINNER_MAX_VAL);
mMinuteSpinner.setOnLongPressUpdateInterval(100);
mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener);
// 初始化AM/PM选择器控件
String[] stringsForAmPm = new DateFormatSymbols().getAmPmStrings();
mAmPmSpinner = (NumberPicker) findViewById(R.id.amPm);
mAmPmSpinner.setMinValue(AMPM_SPINNER_MIN_VAL);
mAmPmSpinner.setMaxValue(AMPM_SPINNER_MAX_VAL);
mAmPmSpinner.setDisplayedValues(stringsForAmPm);
mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener);
// 更新控件为初始状态
updateDateControl();
updateHourControl();
updateAmPmControl();
// 设置24小时制模式
set24HourView(is24HourView);
// 设置当前时间
setCurrentDate(date);
setEnabled(isEnabled()); // 设置是否启用
// 设置控件的内容描述
mInitialising = false;
}
@Override
public void setEnabled(boolean enabled) {
if (mIsEnabled == enabled) {
return;
}
super.setEnabled(enabled);
mDateSpinner.setEnabled(enabled);
mMinuteSpinner.setEnabled(enabled);
mHourSpinner.setEnabled(enabled);
mAmPmSpinner.setEnabled(enabled);
mIsEnabled = enabled;
}
@Override
public boolean isEnabled() {
return mIsEnabled;
}
// 获取当前日期的时间戳
public long getCurrentDateInTimeMillis() {
return mDate.getTimeInMillis();
}
// 设置当前日期时间
public void setCurrentDate(long date) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(date);
setCurrentDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH),
cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE));
}
// 设置当前日期和时间
public void setCurrentDate(int year, int month, int dayOfMonth, int hourOfDay, int minute) {
setCurrentYear(year);
setCurrentMonth(month);
setCurrentDay(dayOfMonth);
setCurrentHour(hourOfDay);
setCurrentMinute(minute);
}
// 获取当前年份
public int getCurrentYear() {
return mDate.get(Calendar.YEAR);
}
// 设置当前年份
public void setCurrentYear(int year) {
if (!mInitialising && year == getCurrentYear()) {
return;
}
mDate.set(Calendar.YEAR, year);
updateDateControl();
onDateTimeChanged();
}
// 获取当前月份
public int getCurrentMonth() {
return mDate.get(Calendar.MONTH);
}
// 设置当前月份
public void setCurrentMonth(int month) {
if (!mInitialising && month == getCurrentMonth()) {
return;
}
mDate.set(Calendar.MONTH, month);
updateDateControl();
onDateTimeChanged();
}
// 获取当前日期
public int getCurrentDay() {
return mDate.get(Calendar.DAY_OF_MONTH);
}
// 设置当前日期
public void setCurrentDay(int dayOfMonth) {
if (!mInitialising && dayOfMonth == getCurrentDay()) {
return;
}
mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateDateControl();
onDateTimeChanged();
}
// 获取当前小时24小时制
public int getCurrentHourOfDay() {
return mDate.get(Calendar.HOUR_OF_DAY);
}
// 获取当前小时12小时制或24小时制
private int getCurrentHour() {
if (mIs24HourView){
return getCurrentHourOfDay();
} else {
int hour = getCurrentHourOfDay();
if (hour > HOURS_IN_HALF_DAY) {
return hour - HOURS_IN_HALF_DAY;
} else {
return hour == 0 ? HOURS_IN_HALF_DAY : hour;
}
}
}
// 设置当前小时24小时制
public void setCurrentHour(int hourOfDay) {
if (!mInitialising && hourOfDay == getCurrentHourOfDay()) {
return;
}
mDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
if (!mIs24HourView) {
if (hourOfDay >= HOURS_IN_HALF_DAY) {
mIsAm = false;
if (hourOfDay > HOURS_IN_HALF_DAY) {
hourOfDay -= HOURS_IN_HALF_DAY;
}
} else {
mIsAm = true;
if (hourOfDay == 0) {
hourOfDay = HOURS_IN_HALF_DAY;
}
}
updateAmPmControl();
}
mHourSpinner.setValue(hourOfDay);
onDateTimeChanged();
}
// 获取当前分钟
public int getCurrentMinute() {
return mDate.get(Calendar.MINUTE);
}
// 设置当前分钟
public void setCurrentMinute(int minute) {
if (!mInitialising && minute == getCurrentMinute()) {
return;
}
mMinuteSpinner.setValue(minute);
mDate.set(Calendar.MINUTE, minute);
onDateTimeChanged();
}
// 判断是否为24小时制
public boolean is24HourView () {
return mIs24HourView;
}
// 设置是否为24小时制或AM/PM制
public void set24HourView(boolean is24HourView) {
if (mIs24HourView == is24HourView) {
return;
}
mIs24HourView = is24HourView;
mAmPmSpinner.setVisibility(is24HourView ? View.GONE : View.VISIBLE);
int hour = getCurrentHourOfDay();
updateHourControl();
setCurrentHour(hour);
updateAmPmControl();
}
// 更新日期选择器的显示内容
private void updateDateControl() {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -DAYS_IN_ALL_WEEK / 2 - 1);
mDateSpinner.setDisplayedValues(null);
for (int i = 0; i < DAYS_IN_ALL_WEEK; ++i) {
cal.add(Calendar.DAY_OF_YEAR, 1);
mDateDisplayValues[i] = (String) DateFormat.format("MM.dd EEEE", cal);
}
mDateSpinner.setDisplayedValues(mDateDisplayValues);
mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2);
mDateSpinner.invalidate();
}
// 更新AM/PM选择器
private void updateAmPmControl() {
if (mIs24HourView) {
mAmPmSpinner.setVisibility(View.GONE);
} else {
int index = mIsAm ? Calendar.AM : Calendar.PM;
mAmPmSpinner.setValue(index);
mAmPmSpinner.setVisibility(View.VISIBLE);
}
}
// 更新小时选择器
private void updateHourControl() {
if (mIs24HourView) {
mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW);
mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW);
} else {
mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW);
mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW);
}
}
// 设置日期时间变化的回调函数
public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) {
mOnDateTimeChangedListener = callback;
}
// 通知日期时间变化
private void onDateTimeChanged() {
if (mOnDateTimeChangedListener != null) {
mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(),
getCurrentMonth(), getCurrentDay(), getCurrentHourOfDay(), getCurrentMinute());
}
}
}

@ -0,0 +1,138 @@
/*
* 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;
import java.util.Calendar;
import net.micode.notes.R;
import net.micode.notes.ui.DateTimePicker;
import net.micode.notes.ui.DateTimePicker.OnDateTimeChangedListener;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
/**
*
* 2412
*/
public class DateTimePickerDialog extends AlertDialog implements OnClickListener {
// 当前选择的日期和时间
private Calendar mDate = Calendar.getInstance();
// 是否为24小时制
private boolean mIs24HourView;
// 日期时间选择回调
private OnDateTimeSetListener mOnDateTimeSetListener;
// 日期时间选择器控件
private DateTimePicker mDateTimePicker;
/**
*
*
*/
public interface OnDateTimeSetListener {
void OnDateTimeSet(AlertDialog dialog, long date);
}
/**
*
* @param context
* @param date
*/
public DateTimePickerDialog(Context context, long date) {
super(context);
// 创建 DateTimePicker 控件,并设置监听器
mDateTimePicker = new DateTimePicker(context);
setView(mDateTimePicker);
mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() {
// 日期时间改变监听器
public void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute) {
// 更新选中的日期和时间
mDate.set(Calendar.YEAR, year);
mDate.set(Calendar.MONTH, month);
mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
mDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
mDate.set(Calendar.MINUTE, minute);
// 更新对话框标题显示的日期时间
updateTitle(mDate.getTimeInMillis());
}
});
// 设置初始日期时间
mDate.setTimeInMillis(date);
mDate.set(Calendar.SECOND, 0); // 将秒数设置为0
mDateTimePicker.setCurrentDate(mDate.getTimeInMillis()); // 初始化日期时间选择器
// 设置对话框按钮
setButton(context.getString(R.string.datetime_dialog_ok), this); // 确定按钮
setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null); // 取消按钮
// 设置是否为24小时制
set24HourView(DateFormat.is24HourFormat(this.getContext()));
// 更新对话框标题
updateTitle(mDate.getTimeInMillis());
}
/**
* 24
* @param is24HourView 24
*/
public void set24HourView(boolean is24HourView) {
mIs24HourView = is24HourView;
}
/**
*
* @param callBack
*/
public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) {
mOnDateTimeSetListener = callBack;
}
/**
*
* @param date
*/
private void updateTitle(long date) {
// 设置显示的日期格式,包含年、月、日和时间
int flag =
DateUtils.FORMAT_SHOW_YEAR |
DateUtils.FORMAT_SHOW_DATE |
DateUtils.FORMAT_SHOW_TIME;
// 如果是24小时制更新显示格式
flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_12HOUR;
// 设置对话框标题为格式化后的日期时间
setTitle(DateUtils.formatDateTime(this.getContext(), date, flag));
}
/**
*
*
*/
public void onClick(DialogInterface arg0, int arg1) {
if (mOnDateTimeSetListener != null) {
// 回调监听器,传递选中的日期时间
mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis());
}
}
}

@ -0,0 +1,94 @@
/*
* 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;
import android.content.Context;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import net.micode.notes.R;
/**
* DropdownMenu
*
*/
public class DropdownMenu {
private Button mButton; // 存储与菜单关联的按钮
private PopupMenu mPopupMenu; // 存储弹出菜单对象
private Menu mMenu; // 存储菜单对象
/**
* DropdownMenu
* @param context
* @param button
* @param menuId ID
*/
public DropdownMenu(Context context, Button button, int menuId) {
mButton = button;
// 设置按钮背景图标(这里使用了一个下拉图标)
mButton.setBackgroundResource(R.drawable.dropdown_icon);
// 创建一个 PopupMenu 对象,显示在按钮下方
mPopupMenu = new PopupMenu(context, mButton);
// 获取菜单对象,之后可以对菜单进行操作
mMenu = mPopupMenu.getMenu();
// 根据给定的菜单ID加载对应的菜单资源
mPopupMenu.getMenuInflater().inflate(menuId, mMenu);
// 设置按钮的点击监听器,当点击按钮时显示弹出菜单
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPopupMenu.show(); // 显示弹出菜单
}
});
}
/**
*
* @param listener
*/
public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) {
if (mPopupMenu != null) {
mPopupMenu.setOnMenuItemClickListener(listener); // 设置菜单项点击监听器
}
}
/**
* ID
* @param id ID
* @return
*/
public MenuItem findItem(int id) {
return mMenu.findItem(id); // 查找菜单项
}
/**
*
* @param title
*/
public void setTitle(CharSequence title) {
mButton.setText(title); // 设置按钮显示的文本
}
}

@ -0,0 +1,125 @@
/*
* 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;
import android.content.Context;
import android.database.Cursor;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
/**
* FoldersListAdapter CursorAdapter
* cursor
*/
public class FoldersListAdapter extends CursorAdapter {
// 数据库查询时使用的投影,表示需要从数据库中获取的列
public static final String[] PROJECTION = {
NoteColumns.ID, // 文件夹 ID
NoteColumns.SNIPPET // 文件夹名称
};
// 表示各列的索引常量
public static final int ID_COLUMN = 0; // ID 列索引
public static final int NAME_COLUMN = 1; // 文件夹名称列索引
/**
* FoldersListAdapter
* @param context
* @param c Cursor
*/
public FoldersListAdapter(Context context, Cursor c) {
super(context, c);
// TODO Auto-generated constructor stub
}
/**
*
* ListView
* @param context
* @param cursor
* @param parent
* @return
*/
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new FolderListItem(context); // 返回一个新的 FolderListItem 视图
}
/**
*
* @param view
* @param context
* @param cursor
*/
@Override
public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof FolderListItem) {
// 判断当前文件夹是否是根文件夹,如果是,则显示"父文件夹"文本
String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
// 将文件夹名称绑定到 FolderListItem 上
((FolderListItem) view).bind(folderName);
}
}
/**
*
* @param context
* @param position
* @return
*/
public String getFolderName(Context context, int position) {
Cursor cursor = (Cursor) getItem(position);
// 如果是根文件夹,则返回 "父文件夹" 的名称
return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
}
/**
* FolderListItem
*/
private class FolderListItem extends LinearLayout {
private TextView mName; // 显示文件夹名称的 TextView
/**
* FolderListItem
* @param context
*/
public FolderListItem(Context context) {
super(context);
// 加载布局文件
inflate(context, R.layout.folder_list_item, this);
mName = (TextView) findViewById(R.id.tv_folder_name); // 获取文件夹名称的 TextView
}
/**
* TextView
* @param name
*/
public void bind(String name) {
mName.setText(name); // 设置文件夹名称
}
}
}

@ -0,0 +1,265 @@
/**
* MiCodeApache License 2.0
*/
package net.micode.notes.ui;
// 导入所需的Android库和自定义包
public class NoteEditActivity extends Activity implements OnClickListener,
NoteSettingChangedListener, OnTextViewChangeListener {
// 内部类,用于持有笔记标题区域的视图元素
private class HeadViewHolder {
public TextView tvModified;
public ImageView ivAlertIcon;
public TextView tvAlertDate;
public ImageView ibSetBgColor;
}
// 定义背景颜色选择器和字体大小选择器的映射关系
private static final Map<Integer, Integer> sBgSelectorBtnsMap = new HashMap<Integer, Integer>();
static {
// 初始化背景颜色按钮映射
}
private static final Map<Integer, Integer> sBgSelectorSelectionMap = new HashMap<Integer, Integer>();
static {
// 初始化背景颜色选择器映射
}
private static final Map<Integer, Integer> sFontSizeBtnsMap = new HashMap<Integer, Integer>();
static {
// 初始化字体大小按钮映射
}
private static final Map<Integer, Integer> sFontSelectorSelectionMap = new HashMap<Integer, Integer>();
static {
// 初始化字体大小选择器映射
}
// 类变量定义
private static final String TAG = "NoteEditActivity";
private HeadViewHolder mNoteHeaderHolder;
private View mHeadViewPanel;
private View mNoteBgColorSelector;
private View mFontSizeSelector;
private EditText mNoteEditor;
private View mNoteEditorPanel;
private WorkingNote mWorkingNote;
private SharedPreferences mSharedPrefs;
private int mFontSizeId;
private static final String PREFERENCE_FONT_SIZE = "pref_font_size";
private static final int SHORTCUT_ICON_TITLE_MAX_LEN = 10;
public static final String TAG_CHECKED = String.valueOf('\u221A');
public static final String TAG_UNCHECKED = String.valueOf('\u25A1');
private LinearLayout mEditTextList;
private String mUserQuery;
private Pattern mPattern;
// onCreate方法初始化Activity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.note_edit);
// 省略了部分代码...
}
// onRestoreInstanceState方法用于在Activity被系统销毁后恢复状态
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// 省略了部分代码...
}
// initActivityState方法初始化Activity状态
private boolean initActivityState(Intent intent) {
// 省略了部分代码...
}
// onResume方法初始化笔记屏幕
@Override
protected void onResume() {
super.onResume();
initNoteScreen();
}
// initNoteScreen方法初始化笔记屏幕视图
private void initNoteScreen() {
// 省略了部分代码...
}
// onNewIntent方法处理新的Intent
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
initActivityState(intent);
}
// onSaveInstanceState方法保存Activity状态
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// 省略了部分代码...
}
// dispatchTouchEvent方法处理触摸事件
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
// 省略了部分代码...
}
// inRangeOfView方法判断触摸事件是否在视图范围内
private boolean inRangeOfView(View view, MotionEvent ev) {
// 省略了部分代码...
}
// initResources方法初始化资源
private void initResources() {
// 省略了部分代码...
}
// onPause方法保存笔记
@Override
protected void onPause() {
super.onPause();
if(saveNote()) {
Log.d(TAG, "Note data was saved with length:" + mWorkingNote.getContent().length());
}
clearSettingState();
}
// updateWidget方法更新Widget
private void updateWidget() {
// 省略了部分代码...
}
// onClick方法处理点击事件
public void onClick(View v) {
// 省略了部分代码...
}
// onBackPressed方法处理返回键事件
@Override
public void onBackPressed() {
// 省略了部分代码...
}
// clearSettingState方法清除设置状态
private boolean clearSettingState() {
// 省略了部分代码...
}
// onBackgroundColorChanged方法处理背景颜色变化
public void onBackgroundColorChanged() {
// 省略了部分代码...
}
// onPrepareOptionsMenu方法准备菜单
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// 省略了部分代码...
}
// onOptionsItemSelected方法处理菜单项点击事件
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// 省略了部分代码...
}
// setReminder方法设置提醒
private void setReminder() {
// 省略了部分代码...
}
// sendTo方法分享笔记到其他应用
private void sendTo(Context context, String info) {
// 省略了部分代码...
}
// createNewNote方法创建新笔记
private void createNewNote() {
// 省略了部分代码...
}
// deleteCurrentNote方法删除当前笔记
private void deleteCurrentNote() {
// 省略了部分代码...
}
// isSyncMode方法判断是否是同步模式
private boolean isSyncMode() {
// 省略了部分代码...
}
// onClockAlertChanged方法处理时钟提醒变化
public void onClockAlertChanged(long date, boolean set) {
// 省略了部分代码...
}
// onWidgetChanged方法处理Widget变化
public void onWidgetChanged() {
// 省略了部分代码...
}
// onEditTextDelete方法处理编辑文本删除
public void onEditTextDelete(int index, String text) {
// 省略了部分代码...
}
// onEditTextEnter方法处理编辑文本回车
public void onEditTextEnter(int index, String text) {
// 省略了部分代码...
}
// switchToListMode方法切换到列表模式
private void switchToListMode(String text) {
// 省略了部分代码...
}
// getHighlightQueryResult方法高亮查询结果
private Spannable getHighlightQueryResult(String fullText, String userQuery) {
// 省略了部分代码...
}
// getListItem方法获取列表项视图
private View getListItem(String item, int index) {
// 省略了部分代码...
}
// onTextChange方法处理文本变化
public void onTextChange(int index, boolean hasText) {
// 省略了部分代码...
}
// onCheckListModeChanged方法处理检查列表模式变化
public void onCheckListModeChanged(int oldMode, int newMode) {
// 省略了部分代码...
}
// getWorkingText方法获取工作文本
private boolean getWorkingText() {
// 省略了部分代码...
}
// saveNote方法保存笔记
private boolean saveNote() {
// 省略了部分代码...
}
// sendToDesktop方法发送到桌面
private void sendToDesktop() {
// 省略了部分代码...
}
// makeShortcutIconTitle方法制作快捷方式图标标题
private String makeShortcutIconTitle(String content) {
// 省略了部分代码...
}
// showToast方法显示Toast提示
private void showToast(int resId) {
showToast(resId, Toast.LENGTH_SHORT);
}
// showToast方法显示Toast提示带持续时间
private void showToast(int resId, int duration) {
}
}

@ -0,0 +1,269 @@
/*
* 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;
import android.content.Context;
import android.graphics.Rect;
import android.text.Layout;
import android.text.Selection;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.URLSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.MotionEvent;
import android.widget.EditText;
import net.micode.notes.R;
import java.util.HashMap;
import java.util.Map;
/**
* NoteEditText EditText
*
*/
public class NoteEditText extends EditText {
private static final String TAG = "NoteEditText";
// 当前 NoteEditText 的索引,用于区分不同的 EditText。
private int mIndex;
// 删除之前的光标位置,用于判断删除操作。
private int mSelectionStartBeforeDelete;
// 定义三种链接方案:电话、网页和电子邮件。
private static final String SCHEME_TEL = "tel:";
private static final String SCHEME_HTTP = "http:";
private static final String SCHEME_EMAIL = "mailto:";
// 用于映射链接方案和对应的菜单项资源。
private static final Map<String, Integer> sSchemaActionResMap = new HashMap<String, Integer>();
static {
// 初始化链接方案和对应的菜单项。
sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel);
sSchemaActionResMap.put(SCHEME_HTTP, R.string.note_link_web);
sSchemaActionResMap.put(SCHEME_EMAIL, R.string.note_link_email);
}
/**
* NoteEditText
*/
public interface OnTextViewChangeListener {
/**
*
* @param index
* @param text
*/
void onEditTextDelete(int index, String text);
/**
*
* @param index
* @param text
*/
void onEditTextEnter(int index, String text);
/**
*
* @param index
* @param hasText
*/
void onTextChange(int index, boolean hasText);
}
// 存储 OnTextViewChangeListener 的实例
private OnTextViewChangeListener mOnTextViewChangeListener;
// 构造函数,初始化 NoteEditText。
public NoteEditText(Context context) {
super(context, null);
mIndex = 0;
}
// 设置当前 NoteEditText 的索引
public void setIndex(int index) {
mIndex = index;
}
// 设置监听文本变化的监听器
public void setOnTextViewChangeListener(OnTextViewChangeListener listener) {
mOnTextViewChangeListener = listener;
}
// 通过属性集初始化 NoteEditText
public NoteEditText(Context context, AttributeSet attrs) {
super(context, attrs, android.R.attr.editTextStyle);
}
// 通过属性集和默认样式初始化 NoteEditText
public NoteEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/**
*
* @param event
* @return
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
int x = (int) event.getX();
int y = (int) event.getY();
x -= getTotalPaddingLeft(); // 获取点击点的 x 坐标
y -= getTotalPaddingTop(); // 获取点击点的 y 坐标
x += getScrollX(); // 获取滚动的 x 偏移
y += getScrollY(); // 获取滚动的 y 偏移
Layout layout = getLayout(); // 获取文本布局
int line = layout.getLineForVertical(y); // 获取点击点所在的行
int off = layout.getOffsetForHorizontal(line, x); // 获取点击点的偏移位置
Selection.setSelection(getText(), off); // 设置光标位置
break;
}
return super.onTouchEvent(event);
}
/**
*
* @param keyCode
* @param event
* @return
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_ENTER:
// 按下回车键时,如果设置了监听器则继续处理
if (mOnTextViewChangeListener != null) {
return false;
}
break;
case KeyEvent.KEYCODE_DEL:
// 按下删除键时记录光标位置
mSelectionStartBeforeDelete = getSelectionStart();
break;
default:
break;
}
return super.onKeyDown(keyCode, event);
}
/**
*
* @param keyCode
* @param event
* @return
*/
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DEL:
if (mOnTextViewChangeListener != null) {
// 如果删除键按下时光标位置在起始位置并且索引不为 0则通知监听器删除操作
if (0 == mSelectionStartBeforeDelete && mIndex != 0) {
mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString());
return true;
}
} else {
Log.d(TAG, "OnTextViewChangeListener was not setted");
}
break;
case KeyEvent.KEYCODE_ENTER:
if (mOnTextViewChangeListener != null) {
// 回车键按下时,将当前文本分割并传递给监听器
int selectionStart = getSelectionStart();
String text = getText().subSequence(selectionStart, length()).toString();
setText(getText().subSequence(0, selectionStart)); // 设置文本为回车前的内容
mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text); // 通知监听器添加新的编辑框
} else {
Log.d(TAG, "OnTextViewChangeListener was not setted");
}
break;
default:
break;
}
return super.onKeyUp(keyCode, event);
}
/**
*
* @param focused
* @param direction
* @param previouslyFocusedRect
*/
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
if (mOnTextViewChangeListener != null) {
if (!focused && TextUtils.isEmpty(getText())) {
mOnTextViewChangeListener.onTextChange(mIndex, false); // 如果文本为空且失去焦点,则通知监听器
} else {
mOnTextViewChangeListener.onTextChange(mIndex, true); // 否则通知监听器文本有内容
}
}
super.onFocusChanged(focused, direction, previouslyFocusedRect);
}
/**
* URL
* @param menu
*/
@Override
protected void onCreateContextMenu(ContextMenu menu) {
if (getText() instanceof Spanned) {
int selStart = getSelectionStart();
int selEnd = getSelectionEnd();
int min = Math.min(selStart, selEnd);
int max = Math.max(selStart, selEnd);
// 获取选中的文本中的 URLSpan
final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class);
if (urls.length == 1) {
int defaultResId = 0;
// 根据 URL 的 Scheme 映射到相应的菜单项
for(String schema: sSchemaActionResMap.keySet()) {
if(urls[0].getURL().indexOf(schema) >= 0) {
defaultResId = sSchemaActionResMap.get(schema);
break;
}
}
if (defaultResId == 0) {
defaultResId = R.string.note_link_other; // 如果没有匹配的 Scheme则使用默认菜单项
}
menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener(
new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// 当点击菜单项时,执行 URLSpan 的点击事件
urls[0].onClick(NoteEditText.this);
return true;
}
});
}
}
super.onCreateContextMenu(menu);
}
}

@ -0,0 +1,255 @@
/*
* 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;
import android.content.Context;
import android.database.Cursor;
import android.text.TextUtils;
import net.micode.notes.data.Contact;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.tool.DataUtils;
/**
* NoteItemData 访
*
*/
public class NoteItemData {
// 定义查询数据库时的投影字段(即需要从数据库查询的列)
static final String [] PROJECTION = new String [] {
NoteColumns.ID, // 笔记ID
NoteColumns.ALERTED_DATE, // 提醒日期
NoteColumns.BG_COLOR_ID, // 背景颜色ID
NoteColumns.CREATED_DATE, // 创建日期
NoteColumns.HAS_ATTACHMENT, // 是否有附件
NoteColumns.MODIFIED_DATE, // 修改日期
NoteColumns.NOTES_COUNT, // 笔记数量
NoteColumns.PARENT_ID, // 父文件夹ID
NoteColumns.SNIPPET, // 笔记内容摘要
NoteColumns.TYPE, // 笔记类型
NoteColumns.WIDGET_ID, // 小部件ID
NoteColumns.WIDGET_TYPE, // 小部件类型
};
// 各列索引
private static final int ID_COLUMN = 0;
private static final int ALERTED_DATE_COLUMN = 1;
private static final int BG_COLOR_ID_COLUMN = 2;
private static final int CREATED_DATE_COLUMN = 3;
private static final int HAS_ATTACHMENT_COLUMN = 4;
private static final int MODIFIED_DATE_COLUMN = 5;
private static final int NOTES_COUNT_COLUMN = 6;
private static final int PARENT_ID_COLUMN = 7;
private static final int SNIPPET_COLUMN = 8;
private static final int TYPE_COLUMN = 9;
private static final int WIDGET_ID_COLUMN = 10;
private static final int WIDGET_TYPE_COLUMN = 11;
// 笔记项的各个属性
private long mId; // 笔记ID
private long mAlertDate; // 提醒日期
private int mBgColorId; // 背景颜色ID
private long mCreatedDate; // 创建日期
private boolean mHasAttachment; // 是否有附件
private long mModifiedDate; // 修改日期
private int mNotesCount; // 笔记数量
private long mParentId; // 父文件夹ID
private String mSnippet; // 笔记摘要
private int mType; // 笔记类型
private int mWidgetId; // 小部件ID
private int mWidgetType; // 小部件类型
private String mName; // 联系人名称
private String mPhoneNumber; // 电话号码
// 状态标志
private boolean mIsLastItem; // 是否是最后一项
private boolean mIsFirstItem; // 是否是第一项
private boolean mIsOnlyOneItem; // 是否是唯一一项
private boolean mIsOneNoteFollowingFolder; // 是否是单个笔记跟随文件夹
private boolean mIsMultiNotesFollowingFolder; // 是否有多个笔记跟随文件夹
/**
* Context Cursor
* @param context
* @param cursor
*/
public NoteItemData(Context context, Cursor cursor) {
// 从游标中获取笔记项数据并初始化类的各个属性
mId = cursor.getLong(ID_COLUMN);
mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN);
mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN);
mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN);
mHasAttachment = (cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0); // 判断是否有附件
mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN);
mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN);
mParentId = cursor.getLong(PARENT_ID_COLUMN);
mSnippet = cursor.getString(SNIPPET_COLUMN); // 获取笔记摘要
// 清理掉摘要中的标签
mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace(
NoteEditActivity.TAG_UNCHECKED, "");
mType = cursor.getInt(TYPE_COLUMN);
mWidgetId = cursor.getInt(WIDGET_ID_COLUMN);
mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN);
// 如果笔记属于通话记录文件夹,则尝试获取联系人的名称和电话号码
mPhoneNumber = "";
if (mParentId == Notes.ID_CALL_RECORD_FOLDER) {
mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId);
if (!TextUtils.isEmpty(mPhoneNumber)) {
mName = Contact.getContact(context, mPhoneNumber); // 获取联系人名称
if (mName == null) {
mName = mPhoneNumber; // 如果没有联系人名称,则使用电话号码
}
}
}
// 如果没有联系人名称,则设置为空字符串
if (mName == null) {
mName = "";
}
// 检查笔记项在数据库中的位置(是否是第一个、最后一个或唯一项等)
checkPostion(cursor);
}
/**
*
* @param cursor
*/
private void checkPostion(Cursor cursor) {
mIsLastItem = cursor.isLast(); // 判断是否是最后一项
mIsFirstItem = cursor.isFirst(); // 判断是否是第一项
mIsOnlyOneItem = (cursor.getCount() == 1); // 判断是否是唯一一项
mIsMultiNotesFollowingFolder = false;
mIsOneNoteFollowingFolder = false;
// 如果笔记是普通笔记且不是第一个项,检查是否紧跟在文件夹后面
if (mType == Notes.TYPE_NOTE && !mIsFirstItem) {
int position = cursor.getPosition();
if (cursor.moveToPrevious()) {
if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER
|| cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) {
// 如果当前笔记项后面有多个笔记,则标记为多个笔记跟随文件夹
if (cursor.getCount() > (position + 1)) {
mIsMultiNotesFollowingFolder = true;
} else {
mIsOneNoteFollowingFolder = true; // 否则标记为单个笔记跟随文件夹
}
}
if (!cursor.moveToNext()) {
throw new IllegalStateException("cursor move to previous but can't move back");
}
}
}
}
// 以下是公开的访问方法,用于获取该笔记项的各个属性值
public boolean isOneFollowingFolder() {
return mIsOneNoteFollowingFolder;
}
public boolean isMultiFollowingFolder() {
return mIsMultiNotesFollowingFolder;
}
public boolean isLast() {
return mIsLastItem;
}
public String getCallName() {
return mName;
}
public boolean isFirst() {
return mIsFirstItem;
}
public boolean isSingle() {
return mIsOnlyOneItem;
}
public long getId() {
return mId;
}
public long getAlertDate() {
return mAlertDate;
}
public long getCreatedDate() {
return mCreatedDate;
}
public boolean hasAttachment() {
return mHasAttachment;
}
public long getModifiedDate() {
return mModifiedDate;
}
public int getBgColorId() {
return mBgColorId;
}
public long getParentId() {
return mParentId;
}
public int getNotesCount() {
return mNotesCount;
}
public long getFolderId () {
return mParentId;
}
public int getType() {
return mType;
}
public int getWidgetType() {
return mWidgetType;
}
public int getWidgetId() {
return mWidgetId;
}
public String getSnippet() {
return mSnippet;
}
public boolean hasAlert() {
return (mAlertDate > 0);
}
public boolean isCallRecord() {
return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber));
}
/**
*
* @param cursor
* @return
*/
public static int getNoteType(Cursor cursor) {
return cursor.getInt(TYPE_COLUMN);
}
}

@ -0,0 +1,230 @@
/**
* MiCodeApache License 2.0
*/
package net.micode.notes.ui;
// 导入所需的Android库和自定义包
public class NotesListActivity extends Activity implements OnClickListener, OnItemLongClickListener {
// 定义了一些查询操作的token用于识别不同的后台查询操作
private static final int FOLDER_NOTE_LIST_QUERY_TOKEN = 0;
private static final int FOLDER_LIST_QUERY_TOKEN = 1;
// 定义了菜单项的ID
private static final int MENU_FOLDER_DELETE = 0;
private static final int MENU_FOLDER_VIEW = 1;
private static final int MENU_FOLDER_CHANGE_NAME = 2;
// 定义了用户首次使用应用时显示的介绍信息的SharedPreferences键
private static final String PREFERENCE_ADD_INTRODUCTION = "net.micode.notes.introduction";
// 枚举,定义了不同的列表编辑状态
private enum ListEditState {
NOTE_LIST, SUB_FOLDER, CALL_RECORD_FOLDER
};
// 类变量定义
private ListEditState mState;
private BackgroundQueryHandler mBackgroundQueryHandler;
private NotesListAdapter mNotesListAdapter;
private ListView mNotesListView;
private Button mAddNewNote;
private boolean mDispatch;
private int mOriginY;
private int mDispatchY;
private TextView mTitleBar;
private long mCurrentFolderId;
private ContentResolver mContentResolver;
private ModeCallback mModeCallBack;
private static final String TAG = "NotesListActivity";
private static final int NOTES_LISTVIEW_SCROLL_RATE = 30;
private NoteItemData mFocusNoteDataItem;
private static final String NORMAL_SELECTION = NoteColumns.PARENT_ID + "=?";
private static final String ROOT_FOLDER_SELECTION = "(" + NoteColumns.TYPE + "<>?"
+ Notes.TYPE_SYSTEM + " AND " + NoteColumns.PARENT_ID + "=?)" + " OR ("
+ NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER + " AND "
+ NoteColumns.NOTES_COUNT + ">0)";
private final static int REQUEST_CODE_OPEN_NODE = 102;
private final static int REQUEST_CODE_NEW_NODE = 103;
// onCreate方法初始化Activity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note_list);
initResources();
// 用户首次使用应用时,插入介绍信息
setAppInfoFromRawRes();
}
// onActivityResult方法处理其他Activity返回的结果
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// 省略了部分代码...
}
// setAppInfoFromRawRes方法从raw资源中读取介绍信息并显示
private void setAppInfoFromRawRes() {
// 省略了部分代码...
}
// onStart方法Activity启动时开始异步查询笔记列表
@Override
protected void onStart() {
super.onStart();
startAsyncNotesListQuery();
}
// initResources方法初始化资源
private void initResources() {
// 省略了部分代码...
}
// ModeCallback内部类实现了ListView的MultiChoiceModeListener和OnMenuItemClickListener接口
private class ModeCallback implements ListView.MultiChoiceModeListener, OnMenuItemClickListener {
// 省略了部分代码...
}
// NewNoteOnTouchListener内部类处理“新建笔记”按钮的触摸事件
private class NewNoteOnTouchListener implements OnTouchListener {
// 省略了部分代码...
};
// startAsyncNotesListQuery方法开始异步查询笔记列表
private void startAsyncNotesListQuery() {
// 省略了部分代码...
}
// BackgroundQueryHandler内部类继承自AsyncQueryHandler处理异步查询完成的回调
private final class BackgroundQueryHandler extends AsyncQueryHandler {
// 省略了部分代码...
}
// showFolderListMenu方法显示文件夹列表菜单
private void showFolderListMenu(Cursor cursor) {
// 省略了部分代码...
}
// createNewNote方法创建新笔记
private void createNewNote() {
// 省略了部分代码...
}
// batchDelete方法批量删除笔记
private void batchDelete() {
// 省略了部分代码...
}
// deleteFolder方法删除文件夹
private void deleteFolder(long folderId) {
// 省略了部分代码...
}
// openNode方法打开笔记
private void openNode(NoteItemData data) {
// 省略了部分代码...
}
// openFolder方法打开文件夹
private void openFolder(NoteItemData data) {
// 省略了部分代码...
}
// onClick方法处理点击事件
public void onClick(View v) {
// 省略了部分代码...
}
// showSoftInput方法显示软键盘
private void showSoftInput() {
// 省略了部分代码...
}
// hideSoftInput方法隐藏软键盘
private void hideSoftInput(View view) {
// 省略了部分代码...
}
// showCreateOrModifyFolderDialog方法显示创建或修改文件夹的对话框
private void showCreateOrModifyFolderDialog(final boolean create) {
// 省略了部分代码...
}
// onBackPressed方法处理返回键事件
@Override
public void onBackPressed() {
// 省略了部分代码...
}
// updateWidget方法更新Widget
private void updateWidget(int appWidgetId, int appWidgetType) {
// 省略了部分代码...
}
// mFolderOnCreateContextMenuListener变量用于创建文件夹的上下文菜单
private final OnCreateContextMenuListener mFolderOnCreateContextMenuListener = new OnCreateContextMenuListener() {
// 省略了部分代码...
};
// onContextMenuClosed方法上下文菜单关闭时的回调
@Override
public void onContextMenuClosed(Menu menu) {
// 省略了部分代码...
}
// onContextItemSelected方法处理上下文菜单项的选中事件
@Override
public boolean onContextItemSelected(MenuItem item) {
// 省略了部分代码...
}
// onPrepareOptionsMenu方法准备选项菜单
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// 省略了部分代码...
}
// onOptionsItemSelected方法处理选项菜单项的点击事件
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// 省略了部分代码...
}
// onSearchRequested方法处理搜索请求
@Override
public boolean onSearchRequested() {
// 省略了部分代码...
}
// exportNoteToText方法将笔记导出为文本
private void exportNoteToText() {
// 省略了部分代码...
}
// isSyncMode方法判断是否是同步模式
private boolean isSyncMode() {
// 省略了部分代码...
}
// startPreferenceActivity方法启动设置Activity
private void startPreferenceActivity() {
// 省略了部分代码...
}
// OnListItemClickListener内部类实现了ListView的ItemClickListener接口
private class OnListItemClickListener implements OnItemClickListener {
// 省略了部分代码...
}
// startQueryDestinationFolders方法开始查询目标文件夹
private void startQueryDestinationFolders() {
// 省略了部分代码...
}
// onItemLongClick方法处理长按事件
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
}
}

@ -0,0 +1,257 @@
/*
* 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;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import net.micode.notes.data.Notes;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
/**
* NotesListAdapter CursorAdapter ListView
*
*/
public class NotesListAdapter extends CursorAdapter {
private static final String TAG = "NotesListAdapter"; // 日志标签
private Context mContext; // 上下文
private HashMap<Integer, Boolean> mSelectedIndex; // 存储选中项的索引
private int mNotesCount; // 笔记总数
private boolean mChoiceMode; // 是否处于选择模式
// 用于存储小部件属性的类
public static class AppWidgetAttribute {
public int widgetId; // 小部件ID
public int widgetType; // 小部件类型
};
/**
* NotesListAdapter
* @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
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new NotesListItem(context); // 返回自定义的列表项视图
}
/**
*
* @param view
* @param context
* @param cursor
*/
@Override
public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof NotesListItem) {
// 使用游标数据创建 NoteItemData 对象
NoteItemData itemData = new NoteItemData(context, cursor);
// 绑定数据到列表项视图
((NotesListItem) view).bind(context, itemData, mChoiceMode, isSelectedItem(cursor.getPosition()));
}
}
/**
*
* @param position
* @param checked
*/
public void setCheckedItem(final int position, final boolean checked) {
mSelectedIndex.put(position, checked); // 更新选中状态
notifyDataSetChanged(); // 刷新数据集
}
/**
*
* @return
*/
public boolean isInChoiceMode() {
return mChoiceMode;
}
/**
*
* @param mode
*/
public void setChoiceMode(boolean mode) {
mSelectedIndex.clear(); // 清除之前的选择状态
mChoiceMode = mode; // 更新选择模式
}
/**
*
* @param checked
*/
public void selectAll(boolean checked) {
Cursor cursor = getCursor();
for (int i = 0; i < getCount(); i++) {
if (cursor.moveToPosition(i)) {
// 如果是笔记类型,则更新其选中状态
if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) {
setCheckedItem(i, checked);
}
}
}
}
/**
* ID
* @return ID
*/
public HashSet<Long> getSelectedItemIds() {
HashSet<Long> itemSet = new HashSet<Long>();
// 遍历选中项索引,获取所有选中的项的 ID
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 {
itemSet.add(id); // 添加到集合中
}
}
}
return itemSet;
}
/**
*
* @return
*/
public HashSet<AppWidgetAttribute> getSelectedWidget() {
HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>();
// 遍历选中项索引,获取所有选中的项的小部件信息
for (Integer position : mSelectedIndex.keySet()) {
if (mSelectedIndex.get(position) == true) {
Cursor c = (Cursor) getItem(position);
if (c != null) {
// 创建小部件属性对象并添加到集合中
AppWidgetAttribute widget = new AppWidgetAttribute();
NoteItemData item = new NoteItemData(mContext, c);
widget.widgetId = item.getWidgetId();
widget.widgetType = item.getWidgetType();
itemSet.add(widget);
} else {
Log.e(TAG, "Invalid cursor");
return null; // 如果游标无效,返回 null
}
}
}
return itemSet;
}
/**
*
* @return
*/
public int getSelectedCount() {
Collection<Boolean> values = mSelectedIndex.values();
if (null == values) {
return 0; // 如果没有选中项,返回 0
}
Iterator<Boolean> iter = values.iterator();
int count = 0;
// 统计选中的项数
while (iter.hasNext()) {
if (true == iter.next()) {
count++;
}
}
return count;
}
/**
*
* @return
*/
public boolean isAllSelected() {
int checkedCount = getSelectedCount();
return (checkedCount != 0 && checkedCount == mNotesCount); // 如果选中的项数等于总项数,返回 true
}
/**
*
* @param position
* @return
*/
public boolean isSelectedItem(final int position) {
if (null == mSelectedIndex.get(position)) {
return false; // 如果没有记录选中状态,则返回 false
}
return mSelectedIndex.get(position); // 返回选中状态
}
/**
*
*/
@Override
protected void onContentChanged() {
super.onContentChanged();
calcNotesCount(); // 重新计算笔记数量
}
/**
*
* @param cursor
*/
@Override
public void changeCursor(Cursor cursor) {
super.changeCursor(cursor);
calcNotesCount(); // 重新计算笔记数量
}
/**
*
*/
private void calcNotesCount() {
mNotesCount = 0;
for (int i = 0; i < getCount(); i++) {
Cursor c = (Cursor) getItem(i);
if (c != null) {
if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) {
mNotesCount++; // 统计笔记数量
}
} else {
Log.e(TAG, "Invalid cursor");
return;
}
}
}
}

@ -0,0 +1,159 @@
/*
* 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;
import android.content.Context;
import android.text.format.DateUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.ResourceParser.NoteItemBgResources;
/**
* NotesListItem
*
*/
public class NotesListItem extends LinearLayout {
private ImageView mAlert; // 提醒图标
private TextView mTitle; // 标题
private TextView mTime; // 修改时间
private TextView mCallName; // 通话记录联系人名(如果是通话记录项)
private NoteItemData mItemData; // 当前项的数据
private CheckBox mCheckBox; // 复选框,用于选择项
/**
*
* @param context
*/
public NotesListItem(Context context) {
super(context);
inflate(context, R.layout.note_item, this); // 加载 note_item 布局
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); // 获取复选框
}
/**
*
*
* @param context
* @param data NoteItemData
* @param choiceMode
* @param checked
*/
public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) {
// 根据是否处于选择模式,显示复选框
if (choiceMode && data.getType() == Notes.TYPE_NOTE) {
mCheckBox.setVisibility(View.VISIBLE); // 显示复选框
mCheckBox.setChecked(checked); // 设置复选框的选中状态
} else {
mCheckBox.setVisibility(View.GONE); // 隐藏复选框
}
// 保存当前项的数据
mItemData = data;
// 判断当前项是否为通话记录文件夹
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
mCallName.setVisibility(View.GONE); // 隐藏联系人名
mAlert.setVisibility(View.VISIBLE); // 显示提醒图标
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); // 设置标题样式
mTitle.setText(context.getString(R.string.call_record_folder_name)
+ context.getString(R.string.format_folder_files_count, data.getNotesCount())); // 设置标题文本
mAlert.setImageResource(R.drawable.call_record); // 设置提醒图标
} else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) {
// 如果当前项是通话记录项
mCallName.setVisibility(View.VISIBLE); // 显示联系人名
mCallName.setText(data.getCallName()); // 设置联系人名
mTitle.setTextAppearance(context, R.style.TextAppearanceSecondaryItem); // 设置标题样式
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); // 设置标题文本(格式化后的内容)
// 设置提醒图标
if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock); // 设置提醒图标
mAlert.setVisibility(View.VISIBLE); // 显示提醒图标
} else {
mAlert.setVisibility(View.GONE); // 隐藏提醒图标
}
} else {
// 普通笔记项或文件夹项
mCallName.setVisibility(View.GONE); // 隐藏联系人名
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); // 设置标题样式
if (data.getType() == Notes.TYPE_FOLDER) {
// 如果是文件夹类型
mTitle.setText(data.getSnippet()
+ context.getString(R.string.format_folder_files_count,
data.getNotesCount())); // 设置标题文本(文件夹名称和文件数量)
mAlert.setVisibility(View.GONE); // 隐藏提醒图标
} else {
// 如果是普通笔记类型
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); // 设置标题文本
// 设置提醒图标
if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock); // 设置提醒图标
mAlert.setVisibility(View.VISIBLE); // 显示提醒图标
} else {
mAlert.setVisibility(View.GONE); // 隐藏提醒图标
}
}
}
// 设置修改时间文本
mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate()));
// 根据数据设置背景
setBackground(data);
}
/**
*
* @param data NoteItemData
*/
private void setBackground(NoteItemData data) {
int id = data.getBgColorId(); // 获取背景颜色ID
if (data.getType() == Notes.TYPE_NOTE) {
// 如果是普通笔记
if (data.isSingle() || data.isOneFollowingFolder()) {
setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id)); // 设置单一笔记背景
} else if (data.isLast()) {
setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id)); // 设置最后一个笔记背景
} else if (data.isFirst() || data.isMultiFollowingFolder()) {
setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id)); // 设置第一个笔记背景
} else {
setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id)); // 设置普通笔记背景
}
} else {
// 如果是文件夹
setBackgroundResource(NoteItemBgResources.getFolderBgRes()); // 设置文件夹背景
}
}
/**
*
* @return NoteItemData
*/
public NoteItemData getItemData() {
return mItemData;
}
}

@ -0,0 +1,429 @@
/*
* 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;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.remote.GTaskSyncService;
public class NotesPreferenceActivity extends PreferenceActivity {
// 常量:用于设置和获取 SharedPreferences 中的 key 值
public static final String PREFERENCE_NAME = "notes_preferences";
public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name";
public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time";
public static final String PREFERENCE_SET_BG_COLOR_KEY = "pref_key_bg_random_appear";
private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key";
private static final String AUTHORITIES_FILTER_KEY = "authorities";
private PreferenceCategory mAccountCategory; // 用于显示账户相关的设置项
private GTaskReceiver mReceiver; // 广播接收器,接收同步服务的广播
private Account[] mOriAccounts; // 保存原始的账户列表,用于比较新添加的账户
private boolean mHasAddedAccount; // 标志,表示用户是否已添加新账户
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
// 设置 ActionBar 显示返回按钮
getActionBar().setDisplayHomeAsUpEnabled(true);
// 加载设置页面的 XML 布局
addPreferencesFromResource(R.xml.preferences);
mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY); // 获取账户设置项
mReceiver = new GTaskReceiver(); // 初始化广播接收器
IntentFilter filter = new IntentFilter();
filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME); // 监听同步服务广播
registerReceiver(mReceiver, filter);
mOriAccounts = null; // 初始化原始账户为空
View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null); // 设置页头
getListView().addHeaderView(header, null, true); // 在设置列表中添加页头
}
@Override
protected void onResume() {
super.onResume();
// 如果用户添加了新账户,自动设置同步账户
if (mHasAddedAccount) {
Account[] accounts = getGoogleAccounts(); // 获取当前的 Google 账户列表
if (mOriAccounts != null && accounts.length > mOriAccounts.length) {
// 遍历账户,检查是否新增账户
for (Account accountNew : accounts) {
boolean found = false;
for (Account accountOld : mOriAccounts) {
if (TextUtils.equals(accountOld.name, accountNew.name)) {
found = true;
break;
}
}
if (!found) {
setSyncAccount(accountNew.name); // 设置新账户为同步账户
break;
}
}
}
}
// 刷新 UI 显示
refreshUI();
}
@Override
protected void onDestroy() {
if (mReceiver != null) {
unregisterReceiver(mReceiver); // 注销广播接收器
}
super.onDestroy();
}
/**
*
*/
private void loadAccountPreference() {
mAccountCategory.removeAll(); // 清空当前账户设置项
Preference accountPref = new Preference(this);
final String defaultAccount = getSyncAccountName(this); // 获取当前的同步账户
accountPref.setTitle(getString(R.string.preferences_account_title)); // 设置标题
accountPref.setSummary(getString(R.string.preferences_account_summary)); // 设置摘要
accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
// 如果当前没有同步账户,显示选择账户的对话框
if (!GTaskSyncService.isSyncing()) {
if (TextUtils.isEmpty(defaultAccount)) {
showSelectAccountAlertDialog();
} else {
// 如果已经有同步账户,确认是否更改账户
showChangeAccountConfirmAlertDialog();
}
} else {
// 如果正在同步,不能更改账户,显示提示
Toast.makeText(NotesPreferenceActivity.this,
R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT)
.show();
}
return true;
}
});
mAccountCategory.addPreference(accountPref); // 添加账户偏好设置项
}
/**
*
*/
private void loadSyncButton() {
Button syncButton = (Button) findViewById(R.id.preference_sync_button);
TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
// 设置同步按钮的状态
if (GTaskSyncService.isSyncing()) {
syncButton.setText(getString(R.string.preferences_button_sync_cancel));
syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
GTaskSyncService.cancelSync(NotesPreferenceActivity.this); // 取消同步
}
});
} else {
syncButton.setText(getString(R.string.preferences_button_sync_immediately));
syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
GTaskSyncService.startSync(NotesPreferenceActivity.this); // 开始同步
}
});
}
syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this))); // 如果没有同步账户,按钮禁用
// 显示最后同步时间
if (GTaskSyncService.isSyncing()) {
lastSyncTimeView.setText(GTaskSyncService.getProgressString()); // 显示同步进度
lastSyncTimeView.setVisibility(View.VISIBLE);
} else {
long lastSyncTime = getLastSyncTime(this);
if (lastSyncTime != 0) {
lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time,
DateFormat.format(getString(R.string.preferences_last_sync_time_format),
lastSyncTime)));
lastSyncTimeView.setVisibility(View.VISIBLE);
} else {
lastSyncTimeView.setVisibility(View.GONE);
}
}
}
/**
*
*/
private void refreshUI() {
loadAccountPreference(); // 加载账户设置
loadSyncButton(); // 加载同步按钮
}
/**
*
*/
private void showSelectAccountAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_select_account_title));
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips));
dialogBuilder.setCustomTitle(titleView);
dialogBuilder.setPositiveButton(null, null);
// 获取 Google 账户列表
Account[] accounts = getGoogleAccounts();
String defAccount = getSyncAccountName(this);
mOriAccounts = accounts;
mHasAddedAccount = false;
if (accounts.length > 0) {
CharSequence[] items = new CharSequence[accounts.length];
final CharSequence[] itemMapping = items;
int checkedItem = -1;
int index = 0;
for (Account account : accounts) {
if (TextUtils.equals(account.name, defAccount)) {
checkedItem = index;
}
items[index++] = account.name;
}
dialogBuilder.setSingleChoiceItems(items, checkedItem,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
setSyncAccount(itemMapping[which].toString()); // 设置同步账户
dialog.dismiss();
refreshUI(); // 刷新 UI
}
});
}
// 添加账户按钮
View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null);
dialogBuilder.setView(addAccountView);
final AlertDialog dialog = dialogBuilder.show();
addAccountView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mHasAddedAccount = true;
Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] {
"gmail-ls"
});
startActivityForResult(intent, -1); // 跳转到添加账户界面
dialog.dismiss();
}
});
}
/**
*
*/
private void showChangeAccountConfirmAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_change_account_title,
getSyncAccountName(this))); // 显示当前同步账户
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg));
dialogBuilder.setCustomTitle(titleView);
// 显示更改账户、删除账户、取消操作
CharSequence[] menuItemArray = new CharSequence[] {
getString(R.string.preferences_menu_change_account),
getString(R.string.preferences_menu_remove_account),
getString(R.string.preferences_menu_cancel)
};
dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
showSelectAccountAlertDialog(); // 更改账户
} else if (which == 1) {
removeSyncAccount(); // 删除同步账户
refreshUI(); // 刷新 UI
}
}
});
dialogBuilder.show();
}
/**
* Google
*/
private Account[] getGoogleAccounts() {
AccountManager accountManager = AccountManager.get(this);
return accountManager.getAccountsByType("com.google");
}
/**
*
*/
private void setSyncAccount(String account) {
if (!getSyncAccountName(this).equals(account)) {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
if (account != null) {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account);
} else {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
}
editor.commit();
// 清除上次同步时间
setLastSyncTime(this, 0);
// 清除本地与 gtask 相关的数据
new Thread(new Runnable() {
public void run() {
ContentValues values = new ContentValues();
values.put(NoteColumns.GTASK_ID, "");
values.put(NoteColumns.SYNC_ID, 0);
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
}
}).start();
// 显示成功提示
Toast.makeText(NotesPreferenceActivity.this,
getString(R.string.preferences_toast_success_set_accout, account),
Toast.LENGTH_SHORT).show();
}
}
/**
*
*/
private void removeSyncAccount() {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) {
editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME);
}
if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) {
editor.remove(PREFERENCE_LAST_SYNC_TIME);
}
editor.commit();
// 清除本地与 gtask 相关的数据
new Thread(new Runnable() {
public void run() {
ContentValues values = new ContentValues();
values.put(NoteColumns.GTASK_ID, "");
values.put(NoteColumns.SYNC_ID, 0);
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
}
}).start();
}
/**
*
*/
public static String getSyncAccountName(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
}
/**
*
*/
public static void setLastSyncTime(Context context, long time) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putLong(PREFERENCE_LAST_SYNC_TIME, time);
editor.commit();
}
/**
*
*/
public static long getLastSyncTime(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0);
}
/**
* 广 GTask
*/
private class GTaskReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
refreshUI(); // 刷新界面
// 如果正在同步,显示同步进度
if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) {
TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
syncStatus.setText(intent
.getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG));
}
}
}
/**
*
*/
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// 返回主页面
Intent intent = new Intent(this, NotesListActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
default:
return false;
}
}
}
Loading…
Cancel
Save