diff --git a/xkw2/AlarmAlertActivity.java b/xkw2/AlarmAlertActivity.java new file mode 100644 index 0000000..1b07867 --- /dev/null +++ b/xkw2/AlarmAlertActivity.java @@ -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.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;//mNoteId可能是笔记的唯一标识符 + private String mSnippet;//mSnippet可能是笔记的摘要或预览 + private static final int SNIPPET_PREW_MAX_LEN = 60;//SNIPPET_PREW_MAX_LEN可能是规定的摘要或预览的最大长度,初值为60 + MediaPlayer mPlayer;//定义了一个名为mPlayer的MediaPlayer对象 + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState);//调用父类的onCreate + 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(); + + try { + mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1)); + mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId);//获取传入的意图并从中获取笔记ID,然后使用该ID从内容提供程序中获取笔记的摘录 + mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0, + SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info) + : mSnippet;//如果摘录超过了预定义的最大长度,则将其截断并附加一些字符串,该代码将截断后的摘录分配给变量mSnippet + } catch (IllegalArgumentException e) { + e.printStackTrace(); + return; + }//从Intent中获取传递的数据,如果数据无效则抛出IllegalArgumentException异常并打印堆栈跟踪信息并返回 + + mPlayer = new MediaPlayer();//创建一个MediaPlayer对象 + if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) { + showActionDialog(); + playAlarmSound(); + }//检查当前笔记是否可见于笔记数据库,如果是,则显示操作对话框并播放警报声音 + else { + finish(); + }//如果不是,结束当前活动 + } + + private boolean isScreenOn() { + PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);//获取 PowerManager 对象,然后调用其 isScreenOn() + return pm.isScreenOn();//调用其 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 { // 设置闹钟铃声的Uri并准备播放 + mPlayer.setDataSource(this, url); + mPlayer.prepare(); // 循环播放闹钟铃声 + mPlayer.setLooping(true); + mPlayer.start(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalStateException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + 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);// 创建一个新的意图,指定跳转到NoteEditActivity类 + intent.setAction(Intent.ACTION_VIEW); // 设置意图的操作为ACTION_VIEW + intent.putExtra(Intent.EXTRA_UID, mNoteId);// 将笔记的ID作为额外的信息传递给NoteEditActivity类 + startActivity(intent);// 启动NoteEditActivity类 + break; + default: // 如果点击的不是对话框的取消按钮,则结束 + break; + } + } + + public void onDismiss(DialogInterface dialog) {// 当对话框消失时执行以下代码 + stopAlarmSound();// 停止闹钟声音 + finish(); // 结束当前Activity + } + + private void stopAlarmSound() { + if (mPlayer != null) {// 如果音频播放器不为空 + mPlayer.stop();// 停止播放音频 + mPlayer.release();// 释放音频播放器的资源 + mPlayer = null;// 将音频播放器置为空 + } + } +} diff --git a/xkw2/AlarmInitReceiver.java b/xkw2/AlarmInitReceiver.java new file mode 100644 index 0000000..997bab4 --- /dev/null +++ b/xkw2/AlarmInitReceiver.java @@ -0,0 +1,67 @@ +/* + * 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; +import android.app.PendingIntent; +import android.content.BroadcastReceiver; +import android.content.ContentUris; +import android.content.Context; +import android.content.Intent; +import android.database.Cursor; + +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; + + +public class AlarmInitReceiver extends BroadcastReceiver {// AlarmInitReceiver类继承自BroadcastReceiver类 + + + private static final String [] PROJECTION = new String [] {// 定义一个字符串数组PROJECTION + NoteColumns.ID,// 第一个元素为NoteColumns.ID + NoteColumns.ALERTED_DATE// 第二个元素为NoteColumns.ALERTED_DATE + }; + + private static final int COLUMN_ID = 0; // 定义一个整型变量COLUMN_ID,值为0 + private static final int COLUMN_ALERTED_DATE = 1;// 定义一个整型变量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,// 通过内容提供器查询数据库 + PROJECTION,// 查询的列 + 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 sender = new Intent(context, AlarmReceiver.class);// 创建一个新的意图 + sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID)));// 设置意图的数据 + PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0);// 创建一个用于启动广播的PendingIntent + AlarmManager alermManager = (AlarmManager) context// 获取AlarmManager服务 + .getSystemService(Context.ALARM_SERVICE);// 设置定时器 + alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);// 移动游标到下一行 + } while (c.moveToNext());// 关闭游标 + } + c.close(); + } + } +} diff --git a/xkw2/AlarmReceiver.java b/xkw2/AlarmReceiver.java new file mode 100644 index 0000000..d3de3c4 --- /dev/null +++ b/xkw2/AlarmReceiver.java @@ -0,0 +1,30 @@ +/* + * 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; + +public class AlarmReceiver extends BroadcastReceiver {// 定义一个名为AlarmReceiver的广播接收器类,继承自BroadcastReceiver类 + @Override + public void onReceive(Context context, Intent intent) {//重写BroadcastReceiver类的onReceive方法,该方法在接收到广播时会被调用 + intent.setClass(context, AlarmAlertActivity.class);// 设置Intent的目标Activity为AlarmAlertActivity + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// 给Intent添加FLAG_ACTIVITY_NEW_TASK标志,表示启动一个新的任务栈 + context.startActivity(intent);// 启动Intent所指定的Activity + } +} diff --git a/xkw2/DateTimePicker.java b/xkw2/DateTimePicker.java new file mode 100644 index 0000000..38e488e --- /dev/null +++ b/xkw2/DateTimePicker.java @@ -0,0 +1,502 @@ +/* + * 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; + +public class DateTimePicker extends FrameLayout {// 定义一个名为DateTimePicker的类,继承自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; + private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23; + private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1; + 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_MAX_VAL = 59; + private static final int AMPM_SPINNER_MIN_VAL = 0; + private static final int AMPM_SPINNER_MAX_VAL = 1; + // 定义控件 + private final NumberPicker mDateSpinner; + private final NumberPicker mHourSpinner; + private final NumberPicker mMinuteSpinner; + private final NumberPicker mAmPmSpinner; + private Calendar mDate; // 定义日历对象 + + private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK]; // 定义字符串数组 + + private boolean mIsAm; // 定义布尔型变量 + + private boolean mIs24HourView; // 是否为24小时制 + + 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) { // 如果不是24小时制 + // 如果从上午11点变成下午12点 + if (!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) { + cal.setTimeInMillis(mDate.getTimeInMillis());// 设置时间为当前时间 + cal.add(Calendar.DAY_OF_YEAR, 1);// 将日期加1天 + isDateChanged = true; // 标记日期已改变 + } // 如果从下午12点变成上午11点 + 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);// 将日期减1天 + isDateChanged = true;// 标记日期已改变 + }// 如果从11点到12点或从12点到11点 + 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();// 更新上下午控件 + } + } // 如果是24小时制 + else {// 如果从23点到0点 + if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) { + cal.setTimeInMillis(mDate.getTimeInMillis()); // 设置时间为当前时间 + cal.add(Calendar.DAY_OF_YEAR, 1);// 将日期加1天 + isDateChanged = true;// 标记日期已改变 + }// 如果从0点到23点 + else if (oldVal == 0 && newVal == HOURS_IN_ALL_DAY - 1) { + cal.setTimeInMillis(mDate.getTimeInMillis());// 设置时间为当前时间 + cal.add(Calendar.DAY_OF_YEAR, -1);// 将日期减1天 + isDateChanged = true;// 标记日期已改变 + } + } + int newHour = mHourSpinner.getValue() % HOURS_IN_HALF_DAY + (mIsAm ? 0 : HOURS_IN_HALF_DAY); + // 获取小时数,对半天的小时数取模,如果是下午,加上半天的小时数 + // 这一行代码的作用是将 12 小时制转换为 24 小时制 + // mHourSpinner 是一个 Spinner 控件,用于选择小时数 + // HOURS_IN_HALF_DAY 是常量,表示半天的小时数 + // mIsAm 是一个布尔值,表示当前是否是上午 + mDate.set(Calendar.HOUR_OF_DAY, newHour); + // 将新的小时数设置到 Calendar 对象中 + // Calendar 是一个日期时间类,用于处理日期时间相关的操作 + onDateTimeChanged();// 调用 onDateTimeChanged() 方法,通知界面更新日期时间显示 + + if (isDateChanged) { + setCurrentYear(cal.get(Calendar.YEAR)); + setCurrentMonth(cal.get(Calendar.MONTH)); + setCurrentDay(cal.get(Calendar.DAY_OF_MONTH)); + }// 如果日期有变化,更新当前年、月、日的显示 + // cal 是一个 Calendar 对象,表示当前的日期时间 + + } + }; + + private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() { // 在值发生改变时调用的回调函数 + + @Override + public void onValueChange(NumberPicker picker, int oldVal, int newVal) {// 获取分钟选择器的最小值和最大值 + int minValue = mMinuteSpinner.getMinValue(); + int maxValue = mMinuteSpinner.getMaxValue(); + int offset = 0;// 如果旧值等于最大值且新值等于最小值,那么时间向后偏移一小时 + if (oldVal == maxValue && newVal == minValue) { + offset += 1;// 如果旧值等于最小值且新值等于最大值,那么时间向前偏移一小时 + } else if (oldVal == minValue && newVal == maxValue) { + offset -= 1; + } // 如果偏移量不为0,那么更新日期和小时选择器的值 + if (offset != 0) { + mDate.add(Calendar.HOUR_OF_DAY, offset); + mHourSpinner.setValue(getCurrentHour()); + updateDateControl();// 获取当前的小时数 + int newHour = getCurrentHourOfDay(); // 如果小时数大于等于12,那么设置上午/下午为下午 + if (newHour >= HOURS_IN_HALF_DAY) { + mIsAm = false; + updateAmPmControl();// 否则设置上午/下午为上午 + } else { + mIsAm = true; + updateAmPmControl(); + } + } // 设置日期的分钟数为新值 + mDate.set(Calendar.MINUTE, newVal); // 调用日期时间改变的回调函数 + onDateTimeChanged(); + } + }; + + private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() {// 重写监听器的onValueChange方法 + @Override + public void onValueChange(NumberPicker picker, int oldVal, int newVal) { + mIsAm = !mIsAm; // 反转mIsAm的布尔值 + if (mIsAm) {// 如果mIsAm为true,则将mDate时间减去12小时 + mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY); + } else {// 如果mIsAm为false,则将mDate时间加上12小时 + mDate.add(Calendar.HOUR_OF_DAY, HOURS_IN_HALF_DAY); + }// 更新上午/下午控件的状态 + updateAmPmControl(); + onDateTimeChanged();// 调用onDateTimeChanged方法 + } + }; + + public interface OnDateTimeChangedListener {// 定义一个OnDateTimeChangedListener接口 + void onDateTimeChanged(DateTimePicker view, int year, int month, + int dayOfMonth, int hourOfDay, int minute); + }// 定义onDateTimeChanged方法,传入日期时间选择器的年、月、日、时、分等参数 + + public DateTimePicker(Context context)// 定义一个公共的构造函数,传入上下文参数 + { + this(context, System.currentTimeMillis());// 调用另一个构造函数,传入上下文和当前时间的毫秒数 + }// 调用父类的构造函数,传入上下文、时间毫秒数和是否为24小时制参数。这里用到了Java中的this关键字,表示当前对象。 + + + public DateTimePicker(Context context, long date) {// 定义一个公共的构造函数,传入上下文和时间毫秒数参数 + this(context, date, DateFormat.is24HourFormat(context));// 调用另一个构造函数,传入上下文、时间毫秒数和是否为24小时制参数 + } + + public DateTimePicker(Context context, long date, boolean is24HourView) {// 定义一个公共的日期选择器类,继承自View类 + super(context);// 调用父类的构造函数 + mDate = Calendar.getInstance(); // 获取当前时间 + mInitialising = true; // 设置初始化状态为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);// 设置长按分钟选择器按钮的更新间隔为100毫秒 + mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener);// 设置分钟选择器的值改变监听器 + + 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);// 设置上午/下午选择器的值改变监听器 + + // update controls to initial state + updateDateControl();// 更新日期选择器的控件状态 + updateHourControl();// 更新小时选择器的控件状态 + updateAmPmControl();// 更新上午/下午选择器的控件状态 + + set24HourView(is24HourView);//设置是否为24小时制 + + // set to current time + setCurrentDate(date);// 设置当前时间 + + setEnabled(isEnabled());// 设置是否可用 + + // set the content descriptions + mInitialising = false;// 设置内容描述 + } + + @Override + public void setEnabled(boolean enabled) { + if (mIsEnabled == enabled) {// 设置控件是否可用的方法 + return; // 如果当前可用状态与要设置的状态一致,则直接返回,不进行任何操作 + } + super.setEnabled(enabled);// 调用父类的setEnabled方法,设置控件是否可用 + mDateSpinner.setEnabled(enabled);// 设置日期选择器是否可用 + mMinuteSpinner.setEnabled(enabled);// 设置分钟选择器是否可用 + mHourSpinner.setEnabled(enabled);// 设置小时选择器是否可用 + mAmPmSpinner.setEnabled(enabled);// 设置上午/下午选择器是否可用 + mIsEnabled = enabled;// 更新当前可用状态 + } + + @Override + public boolean isEnabled() { + return mIsEnabled; + }// 判断是否启用 + + /** + * Get the current date in millis + * + * @return the current date in millis + */ + public long getCurrentDateInTimeMillis() { + return mDate.getTimeInMillis(); + }// 获取当前时间的毫秒数 + + /** + * Set the current date + * + * @param date The current date in millis + */ + 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));// 调用设置当前日期的方法 + } + + /** + * Set the current date + * + * @param year The current year + * @param month The current month + * @param dayOfMonth The current dayOfMonth + * @param hourOfDay The current hourOfDay + * @param minute The current minute + */ + public void setCurrentDate(int year, int month, + int dayOfMonth, int hourOfDay, int minute) {// 设置当前日期 + setCurrentYear(year);// 设置年份 + setCurrentMonth(month); // 设置月份 + setCurrentDay(dayOfMonth);// 设置日期 + setCurrentHour(hourOfDay);// 设置小时 + setCurrentMinute(minute);// 设置分钟 + } + + /** + * Get current year + * + * @return The current year + */ + public int getCurrentYear() { + return mDate.get(Calendar.YEAR); + }// 获取当前年份 + + /** + * Set current year + * + * @param year The current year + */ + public void setCurrentYear(int year) { + if (!mInitialising && year == getCurrentYear()) { + return; + } // 如果不是初始化,并且年份与当前年份相同,则不进行任何操作 + mDate.set(Calendar.YEAR, year);// 设置当前年份 + updateDateControl();// 更新日期控件 + onDateTimeChanged();// 触发日期时间改变事件 + } + + /** + * Get current month in the year + * + * @return The current month in the year + */ + public int getCurrentMonth() { + return mDate.get(Calendar.MONTH); + } // 获取当前月份 + + /** + * Set current month in the year + * + * @param month The month in the year + */ + public void setCurrentMonth(int month) { + if (!mInitialising && month == getCurrentMonth()) { + return; + }// 如果不是初始化,并且月份与当前月份相同,则不进行任何操作 + mDate.set(Calendar.MONTH, month); // 设置当前月份 + updateDateControl();// 更新日期控件 + onDateTimeChanged(); // 触发日期时间改变事件 + } + + /** + * Get current day of the month + * + * @return The day of the month + */ + public int getCurrentDay() { + return mDate.get(Calendar.DAY_OF_MONTH); + }// 获取当前日期 + + /** + * Set current day of the month + * + * @param dayOfMonth The day of the month + */ + public void setCurrentDay(int dayOfMonth) { + if (!mInitialising && dayOfMonth == getCurrentDay()) { + return; + } // 如果不是初始化,并且日期与当前日期相同,则不进行任何操作 + mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);// 设置当前日期 + updateDateControl();// 更新日期控件 + onDateTimeChanged(); // 触发日期时间改变事件 + } + + /** + * Get current hour in 24 hour mode, in the range (0~23) + * @return The current hour in 24 hour mode + */ + public int getCurrentHourOfDay() { + return mDate.get(Calendar.HOUR_OF_DAY); + }// 获取当前小时数(24小时制) + + private int getCurrentHour() { + if (mIs24HourView){ // 如果是24小时制 + return getCurrentHourOfDay();// 直接返回当前小时数 + } else {// 如果是12小时制 + int hour = getCurrentHourOfDay();// 获取当前小时数 + if (hour > HOURS_IN_HALF_DAY) {// 如果当前小时数大于12 + return hour - HOURS_IN_HALF_DAY;// 返回减去12的小时数 + } else {// 如果当前小时数小于等于12 + return hour == 0 ? HOURS_IN_HALF_DAY : hour;// 如果当前小时数为0,则返回12,否则返回当前小时数 + } + } + } + + /** + * Set current hour in 24 hour mode, in the range (0~23) + * + * @param hourOfDay + */ + public void setCurrentHour(int hourOfDay) { + if (!mInitialising && hourOfDay == getCurrentHourOfDay()) { + return;// 如果不是初始化并且设置的小时数与当前小时数相同,则直接返回 + } + mDate.set(Calendar.HOUR_OF_DAY, hourOfDay);// 设置日期的小时数为设置的小时数 + if (!mIs24HourView) {// 如果是12小时制 + if (hourOfDay >= HOURS_IN_HALF_DAY) {// 如果设置的小时数大于等于12 + mIsAm = false;// 设置为下午 + if (hourOfDay > HOURS_IN_HALF_DAY) {// 如果设置的小时数大于12 + hourOfDay -= HOURS_IN_HALF_DAY;// 小时数减去12 + } + } else {// 如果设置的小时数小于12 + mIsAm = true;// 设置为上午 + if (hourOfDay == 0) {// 如果设置的小时数为0 + hourOfDay = HOURS_IN_HALF_DAY;// 小时数设置为12 + } + } + updateAmPmControl();// 更新上午/下午控件 + } + mHourSpinner.setValue(hourOfDay);// 设置小时数的Spinner的值为设置的小时数 + onDateTimeChanged();// 调用日期时间改变的回调方法 + } + + /** + * Get currentMinute + * + * @return The Current Minute + */ + public int getCurrentMinute() { + return mDate.get(Calendar.MINUTE); + }// 获取当前时间的分钟数 + + /** + * Set current minute + */ + public void setCurrentMinute(int minute) {// 设置当前时间的分钟数 + if (!mInitialising && minute == getCurrentMinute()) { + return; + }// 如果不是初始化过程并且传入的分钟数等于当前分钟数,则直接返回 + mMinuteSpinner.setValue(minute);// 设置分钟数的滚轮控件的值 + mDate.set(Calendar.MINUTE, minute); // 设置时间对象的分钟数 + onDateTimeChanged();// 调用日期时间改变的回调方法 + } + + /** + * @return true if this is in 24 hour view else false. + */ + public boolean is24HourView () { + return mIs24HourView; + } + + /** + * Set whether in 24 hour or AM/PM mode. + * + * @param is24HourView True for 24 hour mode. False for AM/PM mode. + */ + public void set24HourView(boolean is24HourView) { + if (mIs24HourView == is24HourView) { + return; + }// 判断是否为24小时制 + mIs24HourView = is24HourView;// 设置是否为24小时制 + 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(); + } + + private void updateAmPmControl() {// 更新上午/下午控件的显示状态 + if (mIs24HourView) {// 如果是24小时制 + mAmPmSpinner.setVisibility(View.GONE);// 隐藏上午/下午控件 + } else {// 如果是12小时制 + int index = mIsAm ? Calendar.AM : Calendar.PM;// 获取当前时间是上午还是下午 + mAmPmSpinner.setValue(index); // 设置上午/下午控件的值 + mAmPmSpinner.setVisibility(View.VISIBLE);// 显示上午/下午控件 + } + } + + private void updateHourControl() {// 更新小时控件的显示范围 + if (mIs24HourView) { // 如果是24小时制 + mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW); // 设置小时控件的最小值为0 + mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW);// 设置小时控件的最大值为23 + } else { + mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW);// 设置小时控件的最小值为1 + mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW);// 设置小时控件的最大值为12 + } + } + + /** + * Set the callback that indicates the 'Set' button has been pressed. + * @param callback the callback, if null will do nothing + */ + public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) { + mOnDateTimeChangedListener = callback; + }// 设置日期时间变化监听器 + + private void onDateTimeChanged() {// 当日期时间发生变化时调用此方法 + if (mOnDateTimeChangedListener != null) {// 如果日期时间变化监听器不为空 + mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(), + getCurrentMonth(), getCurrentDay(), getCurrentHourOfDay(), getCurrentMinute()); + }// 调用日期时间变化监听器的onDateTimeChanged方法,传递当前日期时间的各个参数 + } +} diff --git a/xkw2/DateTimePickerDialog.java b/xkw2/DateTimePickerDialog.java new file mode 100644 index 0000000..7e32622 --- /dev/null +++ b/xkw2/DateTimePickerDialog.java @@ -0,0 +1,90 @@ +/* + * 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; + +public class DateTimePickerDialog extends AlertDialog implements OnClickListener {// 创建一个日期时间选择器对话框类,继承自AlertDialog类,并实现OnClickListener接口。 + + private Calendar mDate = Calendar.getInstance();// 创建一个日期时间选择器对话框类,继承自AlertDialog类,并实现OnClickListener接口。 + private boolean mIs24HourView;// 创建一个日期时间选择器对话框类,继承自AlertDialog类,并实现OnClickListener接口。 + private OnDateTimeSetListener mOnDateTimeSetListener;// 创建一个日期时间选择器对话框类,继承自AlertDialog类,并实现OnClickListener接口。 + private DateTimePicker mDateTimePicker;// 创建一个日期时间选择器对话框类,继承自AlertDialog类,并实现OnClickListener接口。 + + public interface OnDateTimeSetListener {// 创建一个日期时间设置监听器接口OnDateTimeSetListener。 + void OnDateTimeSet(AlertDialog dialog, long date);// 创建一个日期时间设置监听器接口OnDateTimeSetListener。 + } + + public DateTimePickerDialog(Context context, long date) {// 构造函数,接收一个上下文和一个日期的时间 + super(context);// 构造函数,接收一个上下文和一个日期的时间 + mDateTimePicker = new DateTimePicker(context);// 构造函数,接收一个上下文和一个日期的时间 + setView(mDateTimePicker);// 构造函数,接收一个上下文和一个日期的时间 + mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() {// 构造函数,接收一个上下文和一个日期的时间 + public void onDateTimeChanged(DateTimePicker view, int year, int month, + int dayOfMonth, int hourOfDay, int minute) {// 当日期时间改变时,回调该方法 + 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); + set24HourView(DateFormat.is24HourFormat(this.getContext()));// 设置时间格式为24小时制或12小时制 + updateTitle(mDate.getTimeInMillis());// 更新对话框标题,显示当前选择的时间 + } + + public void set24HourView(boolean is24HourView) { + mIs24HourView = is24HourView; //将传入的值赋值给mIs24HourView变量 + } //设置是否是24小时制的方法,传入一个boolean值 + + public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) {//设置日期时间设置监听器的方法,传入一个OnDateTimeSetListener对象 + mOnDateTimeSetListener = callBack; //设置日期时间设置监听器的方法,传入一个OnDateTimeSetListener对象 + } + + private void updateTitle(long date) {//更新对话框标题的方法,传入一个日期时间的long型值 + int flag =//更新对话框标题的方法,传入一个日期时间的long型值 + DateUtils.FORMAT_SHOW_YEAR | //显示年份 + DateUtils.FORMAT_SHOW_DATE | //显示日期 + DateUtils.FORMAT_SHOW_TIME; //显示时间 + flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR;//根据mIs24HourView变量的值,判断是否显示24小时制,将标志位赋值给flag变量 + setTitle(DateUtils.formatDateTime(this.getContext(), date, flag));//根据传入的日期时间值和标志位,格式化日期时间并设置为对话框标题 + } + + public void onClick(DialogInterface arg0, int arg1) { + if (mOnDateTimeSetListener != null) { + mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis());//当用户点击对话框上的“确认”按钮时,如果设置了日期时间设置监听器,则调用该监听器的OnDateTimeSet方法 + } + } + +} \ No newline at end of file diff --git a/xkw2/DropdownMenu.java b/xkw2/DropdownMenu.java new file mode 100644 index 0000000..70516d1 --- /dev/null +++ b/xkw2/DropdownMenu.java @@ -0,0 +1,62 @@ +/* + * 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; + +public class DropdownMenu { + private Button mButton;// 按钮控件 + private PopupMenu mPopupMenu;// 弹出菜单控件 + private Menu mMenu; // 菜单控件 + + public DropdownMenu(Context context, Button button, int menuId) { // 构造函数,传入上下文、按钮控件和菜单 ID + mButton = button; // 初始化按钮控件 + mButton.setBackgroundResource(R.drawable.dropdown_icon); // 设置按钮控件背景为下拉菜单图标 + mPopupMenu = new PopupMenu(context, mButton);// 初始化弹出菜单控件,传入上下文和按钮控件 + mMenu = mPopupMenu.getMenu();// 初始化弹出菜单控件,传入上下文和按钮控件 + mPopupMenu.getMenuInflater().inflate(menuId, mMenu);// 从菜单资源 ID 中填充菜单控件 + mButton.setOnClickListener(new OnClickListener() {// 从菜单资源 ID 中填充菜单控件 + public void onClick(View v)// 点击事件处理 + { + mPopupMenu.show();// 显示弹出菜单控件 + } + }); + } + + public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) { + if (mPopupMenu != null) { + mPopupMenu.setOnMenuItemClickListener(listener); + } + } // 设置下拉菜单项的点击监听器 + + public MenuItem findItem(int id) { + return mMenu.findItem(id); + }// 查找指定id的菜单项 + + public void setTitle(CharSequence title) { + mButton.setText(title); + }// 设置按钮的标题文字 +} diff --git a/xkw2/FoldersListAdapter.java b/xkw2/FoldersListAdapter.java new file mode 100644 index 0000000..affea7e --- /dev/null +++ b/xkw2/FoldersListAdapter.java @@ -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.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; + + +public class FoldersListAdapter extends CursorAdapter { // 文件夹列表适配器类,继承自CursorAdapter + public static final String [] PROJECTION = {// 查询列的数组,包含ID和SNIPPET两列 + NoteColumns.ID, + NoteColumns.SNIPPET + }; + + public static final int ID_COLUMN = 0;// ID列的索引为0 + public static final int NAME_COLUMN = 1;// SNIPPET列的索引为1 + + public FoldersListAdapter(Context context, Cursor c) {// 构造函数,接收上下文和游标作为参数 + super(context, c); + // TODO Auto-generated constructor stub + } + + @Override + public View newView(Context context, Cursor cursor, ViewGroup parent) {// 创建新的视图 + return new FolderListItem(context); // 返回自定义的文件夹列表项视图 + } + + @Override + public void bindView(View view, Context context, Cursor cursor) {// 绑定视图和数据 + if (view instanceof FolderListItem) { // 判断视图类型是否为FolderListItem + // 获取文件夹名称 + String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context + .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);// 绑定文件夹名称到视图 + ((FolderListItem) view).bind(folderName); + } + } + + public String getFolderName(Context context, int position) {// 获取指定位置的Cursor对象 + Cursor cursor = (Cursor) getItem(position);// 获取文件夹名称 + return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context + .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); + } + + private class FolderListItem extends LinearLayout {//私有类 FolderListItem,继承自 LinearLayout + private TextView mName; + + public FolderListItem(Context context) { + super(context);//调用了 super(context) 来初始化父类 LinearLayout + inflate(context, R.layout.folder_list_item, this);//过 inflate 方法将布局文件 R.layout.folder_list_item 填充到当前 LinearLayout 中 + mName = (TextView) findViewById(R.id.tv_folder_name);//通过 findViewById 方法获取到布局文件中的 TextView 控件 tv_folder_name,并将其赋值给成员变量 mName + } + + public void bind(String name) { + mName.setText(name); + }//定义了一个 bind 方法,用于将文件夹的名称绑定到 mName 控件上。在该方法中,通过 mName.setText(name) 将名称显示在 TextView 上 + } + +} diff --git a/xkw2/NoteEditActivity.java b/xkw2/NoteEditActivity.java new file mode 100644 index 0000000..60d8eab --- /dev/null +++ b/xkw2/NoteEditActivity.java @@ -0,0 +1,879 @@ +/* + * 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.AlarmManager; +import android.app.AlertDialog; +import android.app.PendingIntent; +import android.app.SearchManager; +import android.appwidget.AppWidgetManager; +import android.content.ContentUris; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.Paint; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.text.Spannable; +import android.text.SpannableString; +import android.text.TextUtils; +import android.text.format.DateUtils; +import android.text.style.BackgroundColorSpan; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuItem; +import android.view.MotionEvent; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.WindowManager; +import android.widget.CheckBox; +import android.widget.CompoundButton; +import android.widget.CompoundButton.OnCheckedChangeListener; +import android.widget.EditText; +import android.widget.ImageView; +import android.widget.LinearLayout; +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.TextNote; +import net.micode.notes.model.WorkingNote; +import net.micode.notes.model.WorkingNote.NoteSettingChangedListener; +import net.micode.notes.tool.DataUtils; +import net.micode.notes.tool.ResourceParser; +import net.micode.notes.tool.ResourceParser.TextAppearanceResources; +import net.micode.notes.ui.DateTimePickerDialog.OnDateTimeSetListener; +import net.micode.notes.ui.NoteEditText.OnTextViewChangeListener; +import net.micode.notes.widget.NoteWidgetProvider_2x; +import net.micode.notes.widget.NoteWidgetProvider_4x; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + + +public class NoteEditActivity extends Activity implements OnClickListener, + NoteSettingChangedListener, OnTextViewChangeListener { + private class HeadViewHolder {// 内部类HeadViewHolder,用于存储标题栏的控件 + public TextView tvModified;// 最后修改时间的TextView + + public ImageView ivAlertIcon;// 提醒图标的ImageView + + public TextView tvAlertDate;// 提醒图标的ImageView + + public ImageView ibSetBgColor;// 设置背景颜色的ImageView + } + + private static final Map sBgSelectorBtnsMap = new HashMap(); + static { + sBgSelectorBtnsMap.put(R.id.iv_bg_yellow, ResourceParser.YELLOW); + sBgSelectorBtnsMap.put(R.id.iv_bg_red, ResourceParser.RED); + sBgSelectorBtnsMap.put(R.id.iv_bg_blue, ResourceParser.BLUE); + sBgSelectorBtnsMap.put(R.id.iv_bg_green, ResourceParser.GREEN); + sBgSelectorBtnsMap.put(R.id.iv_bg_white, ResourceParser.WHITE); + } + + private static final Map sBgSelectorSelectionMap = new HashMap(); + static {// 静态代码块,初始化sBgSelectorBtnsMap + sBgSelectorSelectionMap.put(ResourceParser.YELLOW, R.id.iv_bg_yellow_select);// 将黄色按钮id和黄色颜色值放入sBgSelectorBtnsMap中 + sBgSelectorSelectionMap.put(ResourceParser.RED, R.id.iv_bg_red_select);// 将红色按钮id和红色颜色值放入sBgSelectorBtnsMap中 + sBgSelectorSelectionMap.put(ResourceParser.BLUE, R.id.iv_bg_blue_select); // 将蓝色按钮id和蓝色颜色值放入sBgSelectorBtnsMap中 + sBgSelectorSelectionMap.put(ResourceParser.GREEN, R.id.iv_bg_green_select);// 将绿色按钮id和绿色颜色值放入sBgSelectorBtnsMap中 + sBgSelectorSelectionMap.put(ResourceParser.WHITE, R.id.iv_bg_white_select);// 将白色按钮id和白色颜色值放入sBgSelectorBtnsMap中 + } + + private static final Map sFontSizeBtnsMap = new HashMap();// 定义一个静态的、不可变的Map,用于存储字体大小按钮的ID和对应的字体大小值 + static { + sFontSizeBtnsMap.put(R.id.ll_font_large, ResourceParser.TEXT_LARGE);// 将“大号字体”按钮的ID和字体大小值存入Map中 + sFontSizeBtnsMap.put(R.id.ll_font_small, ResourceParser.TEXT_SMALL);// 将“小号字体”按钮的ID和字体大小值存入Map中 + sFontSizeBtnsMap.put(R.id.ll_font_normal, ResourceParser.TEXT_MEDIUM); // 将“中号字体”按钮的ID和字体大小值存入Map中 + sFontSizeBtnsMap.put(R.id.ll_font_super, ResourceParser.TEXT_SUPER);// 将“超大号字体”按钮的ID和字体大小值存入Map中 + } + + private static final Map sFontSelectorSelectionMap = new HashMap();// 定义一个静态的、不可变的Map,用于存储字体大小值和对应的字体选择器选中状态的ID + static { + sFontSelectorSelectionMap.put(ResourceParser.TEXT_LARGE, R.id.iv_large_select);// 将字体大小值为“大号字体”的选中状态ID存入Map中 + sFontSelectorSelectionMap.put(ResourceParser.TEXT_SMALL, R.id.iv_small_select); // 将字体大小值为“小号字体”的选中状态ID存入Map中 + sFontSelectorSelectionMap.put(ResourceParser.TEXT_MEDIUM, R.id.iv_medium_select);// 将字体大小值为“中号字体”的选中状态ID存入Map中 + sFontSelectorSelectionMap.put(ResourceParser.TEXT_SUPER, R.id.iv_super_select);// 将字体大小值为“超大号字体”的选中状态ID存入Map中 + } + + private static final String TAG = "NoteEditActivity";// 定义常量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; // 字体大小ID + + 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;// 模式匹配对象 + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState);//调用父类的onCreate方法 + this.setContentView(R.layout.note_edit); //设置当前Activity的布局文件为note_edit.xml + + if (savedInstanceState == null && !initActivityState(getIntent())) {//如果savedInstanceState为空且initActivityState方法返回false + finish(); //结束当前Activity + return; //返回 + } + initResources();//初始化资源 + } + + /** + * Current activity may be killed when the memory is low. Once it is killed, for another time + * user load this activity, we should restore the former state + */ + @Override + protected void onRestoreInstanceState(Bundle savedInstanceState) {//重写onRestoreInstanceState方法 + super.onRestoreInstanceState(savedInstanceState); //调用父类的onRestoreInstanceState方法 + if (savedInstanceState != null && savedInstanceState.containsKey(Intent.EXTRA_UID)) {//如果savedInstanceState不为空且包含Intent.EXTRA_UID键 + Intent intent = new Intent(Intent.ACTION_VIEW);//创建一个ACTION_VIEW的Intent对象 + intent.putExtra(Intent.EXTRA_UID, savedInstanceState.getLong(Intent.EXTRA_UID)); //将Intent.EXTRA_UID键对应的值放入Intent中 + if (!initActivityState(intent)) {//如果initActivityState方法返回false + finish();//结束当前Activity + return; + } + Log.d(TAG, "Restoring from killed activity"); //在Logcat中输出一条调试信息 + } + } + + private boolean initActivityState(Intent intent) {{ // 初始化Activity状态的方法,传入一个Intent对象 + /** + * If the user specified the {@link Intent#ACTION_VIEW} but not provided with id, + * then jump to the NotesListActivity + */ + mWorkingNote = null;{ // 初始化Activity状态的方法,传入一个Intent对象 + if (TextUtils.equals(Intent.ACTION_VIEW, intent.getAction())) { // 如果Intent的动作是ACTION_VIEW + long noteId = intent.getLongExtra(Intent.EXTRA_UID, 0); // 获取Intent中的noteId,如果没有则默认为0 + mUserQuery = "";// 初始化mUserQuery为空字符串 + + /** + * Starting from the searched result + */ + if (intent.hasExtra(SearchManager.EXTRA_DATA_KEY)) {// 初始化mUserQuery为空字符串 + noteId = Long.parseLong(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));// 获取搜索结果的noteId + mUserQuery = intent.getStringExtra(SearchManager.USER_QUERY);// 获取用户查询的字符串 + } + + if (!DataUtils.visibleInNoteDatabase(getContentResolver(), noteId, Notes.TYPE_NOTE)) {// 如果noteId在Note数据库中不可见 + Intent jump = new Intent(this, NotesListActivity.class); // 创建一个跳转到NotesListActivity的Intent + startActivity(jump); // 启动该Intent + showToast(R.string.error_note_not_exist); // 显示提示信息 + finish(); // 结束当前Activity + return false; // 返回false + } else {// 如果noteId在Note数据库中可见 + mWorkingNote = WorkingNote.load(this, noteId);// 加载指定noteId对应的WorkingNote对象 + if (mWorkingNote == null) {// 如果加载失败 + Log.e(TAG, "load note failed with note id" + noteId);// 记录错误信息 + finish(); + return false; + } + } + getWindow().setSoftInputMode( // 设置窗口的软输入模式 + WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN // 软输入状态为隐藏 + | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); // 软输入调整方式为自适应 + } else if(TextUtils.equals(Intent.ACTION_INSERT_OR_EDIT, intent.getAction())) {// 如果Intent的动作是ACTION_INSERT_OR_EDIT + // New note + long folderId = intent.getLongExtra(Notes.INTENT_EXTRA_FOLDER_ID, 0);// 获取文件夹id + int widgetId = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_ID, + AppWidgetManager.INVALID_APPWIDGET_ID);// 获取小部件id + int widgetType = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, + Notes.TYPE_WIDGET_INVALIDE); // 获取小部件类型 + int bgResId = intent.getIntExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, // 获取背景资源id + ResourceParser.getDefaultBgId(this)); + + // Parse call-record note + String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER); // 获取电话号码 + long callDate = intent.getLongExtra(Notes.INTENT_EXTRA_CALL_DATE, 0);// 获取通话记录日期 + if (callDate != 0 && phoneNumber != null) {//如果通话日期和电话号码都存在 + if (TextUtils.isEmpty(phoneNumber)) {//如果电话号码为空 + Log.w(TAG, "The call record number is null");//输出警告信息 + } + long noteId = 0; //定义笔记id变量 + if ((noteId = DataUtils.getNoteIdByPhoneNumberAndCallDate(getContentResolver(), + phoneNumber, callDate)) > 0) {//如果能够通过电话号码和通话日期获取到笔记id + mWorkingNote = WorkingNote.load(this, noteId);//加载笔记 + if (mWorkingNote == null) {//如果笔记加载失败 + Log.e(TAG, "load call note failed with note id" + noteId); //输出错误信息 + finish(); + return false; + } + } else { //如果无法通过电话号码和通话日期获取到笔记id + mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId, + widgetType, bgResId);//创建一个空的笔记 + mWorkingNote.convertToCallNote(phoneNumber, callDate);//将笔记转换为通话记录类型 + } + } else { //如果通话日期或电话号码不存在 + mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId, widgetType, + bgResId); //创建一个空的笔记 + } + + getWindow().setSoftInputMode(//设置窗口的软键盘模式 + WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE + | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); + } else { //如果意图未指定操作 + Log.e(TAG, "Intent not specified action, should not support"); //输出错误信息 + finish(); + return false; + } + mWorkingNote.setOnSettingStatusChangedListener(this);//设置 mWorkingNote 对象的状态改变监听器为当前类(this) + return true; + } + + @Override + protected void onResume() { + super.onResume(); + initNoteScreen(); + }//在onResume方法中,调用initNoteScreen方法初始化笔记界面 + //初始化笔记界面 + private void initNoteScreen() {//设置笔记编辑器的字体样式 + mNoteEditor.setTextAppearance(this, TextAppearanceResources + .getTexAppearanceResource(mFontSizeId));//如果是清单模式,则切换到列表模式 + if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { + switchToListMode(mWorkingNote.getContent()); + } else {//否则,将笔记内容显示在编辑器中,并高亮查询结果 + mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery));//将光标移到文本末尾 + mNoteEditor.setSelection(mNoteEditor.getText().length());//隐藏所有背景选择器 + } + for (Integer id : sBgSelectorSelectionMap.keySet()) { + findViewById(sBgSelectorSelectionMap.get(id)).setVisibility(View.GONE); + }//设置标题栏背景 + mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId());//设置笔记编辑器背景 + mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId());//设置笔记修改时间 + + mNoteHeaderHolder.tvModified.setText(DateUtils.formatDateTime(this, + mWorkingNote.getModifiedDate(), DateUtils.FORMAT_SHOW_DATE + | DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_SHOW_TIME + | DateUtils.FORMAT_SHOW_YEAR)); + + /** + * TODO: Add the menu for setting alert. Currently disable it because the DateTimePicker + * is not ready + */ + showAlertHeader(); + } + + private void showAlertHeader() {// 显示警报头部信息的方法 + if (mWorkingNote.hasClockAlert()) {// 如果当前笔记设置了警报 + long time = System.currentTimeMillis(); // 获取当前时间 + if (time > mWorkingNote.getAlertDate()) { // 如果当前时间已经超过了警报时间 + mNoteHeaderHolder.tvAlertDate.setText(R.string.note_alert_expired); // 在警报时间的文本框中显示“已过期” + } else { + mNoteHeaderHolder.tvAlertDate.setText(DateUtils.getRelativeTimeSpanString( + mWorkingNote.getAlertDate(), time, DateUtils.MINUTE_IN_MILLIS));// 在警报时间的文本框中显示距离警报时间还有多长时间 + } + mNoteHeaderHolder.tvAlertDate.setVisibility(View.VISIBLE); // 显示警报时间的文本框 + mNoteHeaderHolder.ivAlertIcon.setVisibility(View.VISIBLE); // 显示警报图标 + } else { // 如果当前笔记没有设置警报 + mNoteHeaderHolder.tvAlertDate.setVisibility(View.GONE);// 隐藏警报时间的文本框 + mNoteHeaderHolder.ivAlertIcon.setVisibility(View.GONE);// 隐藏警报图标 + }; + } + + @Override + protected void onNewIntent(Intent intent) {// 当用户从其它界面返回到此界面时调用的方法 + super.onNewIntent(intent); // 调用父类的方法 + initActivityState(intent);// 初始化Activity的状态 + } + + @Override + protected void onSaveInstanceState(Bundle outState) { // 当Activity被销毁时调用的方法,用于保存Activity的状态 + super.onSaveInstanceState(outState); + /** + * For new note without note id, we should firstly save it to + * generate a id. If the editing note is not worth saving, there + * is no id which is equivalent to create new note + */ + if (!mWorkingNote.existInDatabase()) {// 如果工作笔记不存在于数据库中 + saveNote();// 保存笔记 + } + outState.putLong(Intent.EXTRA_UID, mWorkingNote.getNoteId());// 将工作笔记的ID放入保存状态中 + Log.d(TAG, "Save working note id: " + mWorkingNote.getNoteId() + " onSaveInstanceState"); + }// 在日志中记录保存的工作笔记ID + // 触摸事件分发函数 + @Override + public boolean dispatchTouchEvent(MotionEvent ev) { + if (mNoteBgColorSelector.getVisibility() == View.VISIBLE + && !inRangeOfView(mNoteBgColorSelector, ev))// 如果笔记背景颜色选择器可见且触摸位置不在选择器内部 + { + mNoteBgColorSelector.setVisibility(View.GONE);// 隐藏笔记背景颜色选择器 + return true; + } + + if (mFontSizeSelector.getVisibility() == View.VISIBLE// 如果字号选择器可见且触摸位置不在选择器内部 + && !inRangeOfView(mFontSizeSelector, ev)) { + mFontSizeSelector.setVisibility(View.GONE);// 隐藏字号选择器 + return true; + }// 调用父类的触摸事件分发函数 + return super.dispatchTouchEvent(ev); + } + // 判断触摸位置是否在视图范围内 + + private boolean inRangeOfView(View view, MotionEvent ev) {// 获取视图在屏幕上的位置 + int []location = new int[2]; + view.getLocationOnScreen(location); + int x = location[0]; + int y = location[1];// 获取视图在屏幕上的位置 + if (ev.getX() < x + || ev.getX() > (x + view.getWidth()) + || ev.getY() < y + || ev.getY() > (y + view.getHeight())) { + return false; + }// 触摸位置在视图范围内 + return true; + } + + private void initResources() {// 获取笔记标题视图面板 + mHeadViewPanel = findViewById(R.id.note_title);// 获取笔记标题视图面板 + mNoteHeaderHolder = new HeadViewHolder();// 获取笔记标题视图面板 + mNoteHeaderHolder.tvModified = (TextView) findViewById(R.id.tv_modified_date);// 获取笔记标题视图面板 + mNoteHeaderHolder.ivAlertIcon = (ImageView) findViewById(R.id.iv_alert_icon);// 获取提醒时间文本视图 + mNoteHeaderHolder.tvAlertDate = (TextView) findViewById(R.id.tv_alert_date);// 获取设置背景颜色按钮视图 + mNoteHeaderHolder.ibSetBgColor = (ImageView) findViewById(R.id.btn_set_bg_color);// 设置设置背景颜色按钮的点击监听器 + mNoteHeaderHolder.ibSetBgColor.setOnClickListener(this);// 获取笔记编辑器视图 + mNoteEditor = (EditText) findViewById(R.id.note_edit_view);// 获取笔记编辑器面板视图 + mNoteEditorPanel = findViewById(R.id.sv_note_edit);// 获取笔记背景颜色选择器视图 + mNoteBgColorSelector = findViewById(R.id.note_bg_color_selector);// 为所有背景选择器按钮设置点击监听器 + for (int id : sBgSelectorBtnsMap.keySet()) { + ImageView iv = (ImageView) findViewById(id); + iv.setOnClickListener(this); + } + + mFontSizeSelector = findViewById(R.id.font_size_selector);// 设置字体大小选择器控件 + for (int id : sFontSizeBtnsMap.keySet()) { + View view = findViewById(id); + view.setOnClickListener(this); + };// 遍历字体大小按钮映射表,并为每个按钮设置点击事件监听器 + mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);// 获取默认的共享首选项对象 + mFontSizeId = mSharedPrefs.getInt(PREFERENCE_FONT_SIZE, ResourceParser.BG_DEFAULT_FONT_SIZE);// 获取上一次使用的字体大小ID,如果没有则使用默认值 + /** + * HACKME: Fix bug of store the resource id in shared preference. + * The id may larger than the length of resources, in this case, + * return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE} + */ + if(mFontSizeId >= TextAppearanceResources.getResourcesSize()) { + mFontSizeId = ResourceParser.BG_DEFAULT_FONT_SIZE; + }//ID可能大于资源长度,在这种情况下, + mEditTextList = (LinearLayout) findViewById(R.id.note_edit_list); + }// 获取笔记编辑列表布局 + + @Override + protected void onPause() { + super.onPause(); + if(saveNote()) { + Log.d(TAG, "Note data was saved with length:" + mWorkingNote.getContent().length()); + }// 如果保存笔记成功,则输出日志记录笔记内容长度 + clearSettingState();// 清除设置状态 + + } + + private void updateWidget() { + Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);// 创建更新小部件的意图 + if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_2X) { + intent.setClass(this, NoteWidgetProvider_2x.class); + }// 根据当前笔记的小部件类型,设置意图的类别 + else if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_4X) { + intent.setClass(this, NoteWidgetProvider_4x.class); + } + else { + Log.e(TAG, "Unspported widget type"); + return; + }// 如果小部件类型不支持,则输出错误日志并返回 + + intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { + mWorkingNote.getWidgetId() + });// 将当前笔记的小部件ID添加到意图中 + + sendBroadcast(intent);// 发送广播更新小部件 + setResult(RESULT_OK, intent);// 设置结果为“操作成功” + } + + public void onClick(View v) {// 点击事件监听器 + int id = v.getId();// 获取被点击的 View 的 ID + if (id == R.id.btn_set_bg_color) {// 如果被点击的是设置背景颜色的按钮 + mNoteBgColorSelector.setVisibility(View.VISIBLE);// 显示背景颜色选择器 + findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( + - View.VISIBLE); // 显示当前背景颜色的选中状态 + } else if (sBgSelectorBtnsMap.containsKey(id)) { // 如果被点击的是背景颜色选择器中的按钮 + findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( + View.GONE);// 隐藏之前选中的背景颜色的选中状态 + mWorkingNote.setBgColorId(sBgSelectorBtnsMap.get(id)); // 设置笔记的背景颜色 ID + mNoteBgColorSelector.setVisibility(View.GONE); // 隐藏背景颜色选择器 + } else if (sFontSizeBtnsMap.containsKey(id)) {// 如果被点击的是字体大小选择器中的按钮 + findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.GONE); // 隐藏之前选中的字体大小的选中状态 + mFontSizeId = sFontSizeBtnsMap.get(id);// 设置笔记的字体大小 ID + mSharedPrefs.edit().putInt(PREFERENCE_FONT_SIZE, mFontSizeId).commit();// 将字体大小 ID 存储到 SharedPreferences 中 + findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.VISIBLE);// 显示新选中的字体大小的选中状态 + if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {//如果当前笔记处于待办事项模式 + getWorkingText();//获取当前笔记的文本内容; + switchToListMode(mWorkingNote.getContent());//将当前笔记的编辑器切换为列表模式 + } else { + mNoteEditor.setTextAppearance(this, + TextAppearanceResources.getTexAppearanceResource(mFontSizeId));//将当前笔记的编辑器文本外观设置为指定字体大小 + } + mFontSizeSelector.setVisibility(View.GONE);//隐藏字体大小选择器 + } + } + + @Override + public void onBackPressed() { // 当用户按下返回键时执行该方法 + if(clearSettingState()) { // 如果设置状态已经被清除,则直接返回 + return; + } + + saveNote(); // 保存笔记 + super.onBackPressed(); // 调用父类的onBackPressed方法,关闭当前Activity + } + + private boolean clearSettingState() {// 清除设置状态的方法 + if (mNoteBgColorSelector.getVisibility() == View.VISIBLE) {// 如果笔记背景颜色选择器可见 + mNoteBgColorSelector.setVisibility(View.GONE);// 如果笔记背景颜色选择器可见 + return true; // 返回true,表示设置状态已经被清除 + } else if (mFontSizeSelector.getVisibility() == View.VISIBLE) {// 否则如果字体大小选择器可见 + mFontSizeSelector.setVisibility(View.GONE); // 隐藏字体大小选择器 + return true; // 返回true,表示设置状态已经被清除 + } + return false; // 返回false,表示设置状态未被清除 + } + + public void onBackgroundColorChanged() {// 当笔记背景颜色改变时执行该方法 + findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( + View.VISIBLE); // 根据当前背景颜色id获取对应的选择器,并将其设置为可见 + mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId()); // 根据当前背景颜色id获取对应的选择器,并将其设置为可见 + mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId()); // 设置笔记标题栏的背景颜色为当前选择的背景颜色 + } + + @Override + public boolean onPrepareOptionsMenu(Menu menu) {// 当准备显示选项菜单时调用 + if (isFinishing()) {// 如果Activity正在被销毁,则返回true + return true; + } + clearSettingState(); // 清除设置状态(即隐藏字体大小选择器和背景颜色选择器) + menu.clear();// 清除菜单项 + if (mWorkingNote.getFolderId() == Notes.ID_CALL_RECORD_FOLDER) { // 如果当前笔记所在的文件夹是通话记录文件夹,则加载通话记录编辑菜单项 + getMenuInflater().inflate(R.menu.call_note_edit, menu); + } else { // 否则加载笔记编辑菜单项 + getMenuInflater().inflate(R.menu.note_edit, menu); + } + if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { // 如果当前是清单模式,则将选项菜单中的“清单模式”改为“正常模式” + menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_normal_mode); + } else {// 否则将选项菜单中的“正常模式”改为“清单模式” + menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_list_mode); + } + if (mWorkingNote.hasClockAlert()) { // 如果当前笔记设置了提醒,则隐藏“添加提醒”菜单项 + menu.findItem(R.id.menu_alert).setVisible(false); + } else { // 否则隐藏“删除提醒”菜单项 + menu.findItem(R.id.menu_delete_remind).setVisible(false); + } + return true; // 返回true表示已准备好显示选项菜单 + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { // 当用户点击菜单项时执行该方法 + switch (item.getItemId()) {// 获取用户点击的菜单项ID + case R.id.menu_new_note:// 如果用户点击的是新建笔记菜单项 + createNewNote();// 调用创建新笔记的方法 + break; + case R.id.menu_delete:// 如果用户点击的是删除笔记菜单项 + AlertDialog.Builder builder = new AlertDialog.Builder(this);// 创建一个对话框 + builder.setTitle(getString(R.string.alert_title_delete)); // 设置对话框标题 + builder.setIcon(android.R.drawable.ic_dialog_alert);// 设置对话框图标 + builder.setMessage(getString(R.string.alert_message_delete_note)); // 设置对话框提示信息 + builder.setPositiveButton(android.R.string.ok,// 设置对话框确认按钮的点击事件 + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { // 当用户点击确认按钮时执行该方法 + deleteCurrentNote(); // 调用删除笔记的方法 + finish(); // 关闭当前活动 + } + }); + builder.setNegativeButton(android.R.string.cancel, null); // 设置对话框取消按钮的点击事件 + builder.show();// 显示对话框 + break; + case R.id.menu_font_size:// 如果用户点击的是字体大小菜单项 + mFontSizeSelector.setVisibility(View.VISIBLE); // 显示字体大小选择器 + findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.VISIBLE);// 显示当前选中的字体大小 + break; + case R.id.menu_list_mode: // 如果用户点击的是清单模式菜单项 + mWorkingNote.setCheckListMode(mWorkingNote.getCheckListMode() == 0 ?// 切换清单模式 + TextNote.MODE_CHECK_LIST : 0); + break; + case R.id.menu_share:// 如果用户点击的是分享菜单项 + getWorkingText();// 获取当前笔记的内容 + sendTo(this, mWorkingNote.getContent());// 调用分享方法,将笔记内容分享到其他应用 + break; + case R.id.menu_send_to_desktop:// 如果用户点击的是发送到桌面菜单项 + sendToDesktop(); // 调用发送到桌面的方法 + break; + case R.id.menu_alert:// 如果用户点击的是设置提醒菜单项 + setReminder();// 调用设置提醒的方法 + break; + case R.id.menu_delete_remind: // 如果用户点击的是删除提醒菜单项 + mWorkingNote.setAlertDate(0, false);// 将笔记的提醒日期设置为0,表示删除提醒 + break; + default:// 如果用户点击的是其他菜单项 + break; + } + return true;// 返回true表示菜单项已经被处理 + } + + private void setReminder() {// 设置提醒时间 + DateTimePickerDialog d = new DateTimePickerDialog(this, System.currentTimeMillis());// 创建日期时间选择对话框 + d.setOnDateTimeSetListener(new OnDateTimeSetListener() { // 设置日期时间选择监听器 + public void OnDateTimeSet(AlertDialog dialog, long date) { // 在日期时间选择监听器中设置提醒时间 + mWorkingNote.setAlertDate(date , true);// 设置提醒时间 + } + }); + d.show(); // 显示日期时间选择对话框 + } + + /** + * Share note to apps that support {@link Intent#ACTION_SEND} action + * and {@text/plain} type + */ + private void sendTo(Context context, String info) { // 分享笔记到其他应用 + Intent intent = new Intent(Intent.ACTION_SEND); // 创建发送意图 + intent.putExtra(Intent.EXTRA_TEXT, info);// 设置分享内容 + intent.setType("text/plain");// 设置分享内容 + context.startActivity(intent);// 启动分享应用 + } + + private void createNewNote() { // 创建新笔记 + // Firstly, save current editing notes + saveNote();// 保存笔记 + + // For safety, start a new NoteEditActivity + finish();// 结束当前Activity + Intent intent = new Intent(this, NoteEditActivity.class);// 结束当前Activity + intent.setAction(Intent.ACTION_INSERT_OR_EDIT); // 设置意图的操作为插入或编辑 + intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mWorkingNote.getFolderId()); // 设置意图的操作为插入或编辑 + startActivity(intent);// 启动新笔记的Activity + } + + private void deleteCurrentNote() {// 删除当前笔记 + if (mWorkingNote.existInDatabase()) {// 如果当前笔记存在于数据库中 + HashSet ids = new HashSet();// 初始化一个HashSet用于存储笔记的id + long id = mWorkingNote.getNoteId();// 初始化一个HashSet用于存储笔记的id + if (id != Notes.ID_ROOT_FOLDER) {// 如果id不是根文件夹的id + ids.add(id); + } else { + Log.d(TAG, "Wrong note id, should not happen");// 把id添加到HashSet中 + } + if (!isSyncMode()) {// 把id添加到HashSet中 + if (!DataUtils.batchDeleteNotes(getContentResolver(), ids)) {// 批量删除笔记 + Log.e(TAG, "Delete Note error");// 输出错误日志 + } + } else { + if (!DataUtils.batchMoveToFolder(getContentResolver(), ids, Notes.ID_TRASH_FOLER)) {// 批量移动笔记到垃圾箱 + Log.e(TAG, "Move notes to trash folder error, should not happens");// 输出错误日志 + } + } + } + mWorkingNote.markDeleted(true);// 标记当前笔记已被删除 + } + + private boolean isSyncMode() {// 判断是否为同步模式 + return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; + } + + public void onClockAlertChanged(long date, boolean set) {// 监听提醒时间的变化 + /** + * User could set clock to an unsaved note, so before setting the + * alert clock, we should save the note first + */ + if (!mWorkingNote.existInDatabase()) { + saveNote(); + }// 如果笔记已保存到数据库中 + if (mWorkingNote.getNoteId() > 0) { + Intent intent = new Intent(this, AlarmReceiver.class);// 初始化一个意图用于启动闹钟接收器 + intent.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mWorkingNote.getNoteId()));// 设置意图的数据为当前笔记的Uri + PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);// 获取一个用于启动闹钟接收器的PendingIntent + AlarmManager alarmManager = ((AlarmManager) getSystemService(ALARM_SERVICE));// 获取一个闹钟管理器 + showAlertHeader();// 获取一个闹钟管理器 + if(!set) {// 如果不设置提醒时间 + alarmManager.cancel(pendingIntent);// 如果不设置提醒时间 + } else { + alarmManager.set(AlarmManager.RTC_WAKEUP, date, pendingIntent);// 设置当前闹钟 + } + } else { + /** + * There is the condition that user has input nothing (the note is + * not worthy saving), we have no note id, remind the user that he + * should input something + */ + Log.e(TAG, "Clock alert setting error"); + showToast(R.string.error_note_empty_for_clock); + } + } + + public void onWidgetChanged() {// 当小部件发生改变时触发该方法 + updateWidget();// 更新小部件 + } + + public void onEditTextDelete(int index, String text) {// 当删除编辑文本时触发该方法,index表示编辑文本的索引,text表示删除的文本内容 + int childCount = mEditTextList.getChildCount();// 获取编辑文本列表中的子项数量 + if (childCount == 1) {// 如果只有一个子项,则不进行删除操作 + return; + } + + for (int i = index + 1; i < childCount; i++) {// 循环遍历编辑文本列表,将所有索引大于被删除文本的索引的文本的索引减1 + ((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text)) + .setIndex(i - 1); + } + + mEditTextList.removeViewAt(index); // 移除被删除的编辑文本 + NoteEditText edit = null; + if(index == 0) { // 如果被删除的是第一个编辑文本,则将焦点设置到第一个编辑文本 + edit = (NoteEditText) mEditTextList.getChildAt(0).findViewById( + R.id.et_edit_text); + } else { // 如果被删除的是第一个编辑文本,则将焦点设置到第一个编辑文本 + edit = (NoteEditText) mEditTextList.getChildAt(index - 1).findViewById( + R.id.et_edit_text); + } + int length = edit.length();// 获取编辑文本的长度 + edit.append(text);// 将被删除的文本追加到编辑文本上 + edit.requestFocus();// 获取焦点 + edit.setSelection(length); // 设置光标位置为文本末尾 + } + + public void onEditTextEnter(int index, String text) {// 当添加编辑文本时触发该方法,index表示编辑文本的索引,text表示添加的文本内容 + /** + * Should not happen, check for debug + */ + if(index > mEditTextList.getChildCount()) {// 如果索引大于编辑文本列表中的子项数量,则输出错误日志 + Log.e(TAG, "Index out of mEditTextList boundrary, should not happen"); + } + + View view = getListItem(text, index); // 根据传入的文本和索引获取列表项视图 + mEditTextList.addView(view, index);// 将列表项添加到编辑文本列表中 + NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); + edit.requestFocus();// 获取焦点 + edit.setSelection(0); // 设置光标位置为文本开头 + for (int i = index + 1; i < mEditTextList.getChildCount(); i++) {// 循环遍历编辑文本列表,将所有索引大于被添加文本的索引的文本的索引加1 + ((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text)) + .setIndex(i); + } + } + + private void switchToListMode(String text) {// 切换到列表模式 + mEditTextList.removeAllViews();// 移除所有的 View + String[] items = text.split("\n");// 以换行符为分隔符,将字符串 text 分割成多个条目 + int index = 0; + for (String item : items) {// 遍历每个条目 + if(!TextUtils.isEmpty(item)) {// 如果条目不为空 + mEditTextList.addView(getListItem(item, index));// 将新建的条目添加到 mEditTextList 中 + index++; + } + } + mEditTextList.addView(getListItem("", index));// 添加一个空条目 + mEditTextList.getChildAt(index).findViewById(R.id.et_edit_text).requestFocus();// 获取最后一个条目中的 NoteEditText,并将其设为焦点 + + mNoteEditor.setVisibility(View.GONE);// 隐藏 mNoteEditor + mEditTextList.setVisibility(View.VISIBLE);// 显示 mEditTextList + } + + private Spannable getHighlightQueryResult(String fullText, String userQuery) {// 获取高亮显示查询结果的 Spannable 对象 + SpannableString spannable = new SpannableString(fullText == null ? "" : fullText);// 将 fullText 转换为 SpannableString 对象 + if (!TextUtils.isEmpty(userQuery)) {// 使用正则表达式匹配 userQuery + mPattern = Pattern.compile(userQuery); + Matcher m = mPattern.matcher(fullText); + int start = 0; + while (m.find(start)) {// 将匹配到的字符串进行高亮显示 + spannable.setSpan( + new BackgroundColorSpan(this.getResources().getColor( + R.color.user_query_highlight)), m.start(), m.end(), + Spannable.SPAN_INCLUSIVE_EXCLUSIVE); + start = m.end(); + } + } + return spannable; + } + + private View getListItem(String item, int index) {// 获取列表项视图 + View view = LayoutInflater.from(this).inflate(R.layout.note_edit_list_item, null);// 从布局文件中加载视图 + final NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text);// 获取编辑框 + edit.setTextAppearance(this, TextAppearanceResources.getTexAppearanceResource(mFontSizeId));// 设置编辑框文本的外观样式 + CheckBox cb = ((CheckBox) view.findViewById(R.id.cb_edit_item));// 获取复选框 + cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {// 设置复选框状态改变的监听器 + public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {// 复选框状态改变时的回调方法 + if (isChecked) {// 如果被选中,则在编辑框中添加删除线 + edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); + } else {// 否则,编辑框中的文本恢复正常样式 + edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG); + } + } + }); + + if (item.startsWith(TAG_CHECKED)) {// 否则,编辑框中的文本恢复正常样式 + cb.setChecked(true); // 设置复选框为选中状态 + edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); // 在编辑框中添加删除线 + item = item.substring(TAG_CHECKED.length(), item.length()).trim();// 截取文本内容 + } else if (item.startsWith(TAG_UNCHECKED)) { // 未选中 + cb.setChecked(false); // 设置复选框为未选中状态 + edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG); // 编辑框中的文本恢复正常样式 + item = item.substring(TAG_UNCHECKED.length(), item.length()).trim(); // 截取文本内容 + } + + edit.setOnTextViewChangeListener(this);// 设置编辑框的文本内容变化监听器 + edit.setIndex(index);// 设置编辑框的索引值 + edit.setText(getHighlightQueryResult(item, mUserQuery));// 设置编辑框的文本内容,并高亮显示用户查询结果 + return view;// 返回列表项视图 + } + + public void onTextChange(int index, boolean hasText) { + if (index >= mEditTextList.getChildCount()) {// 当文本框的内容改变时,根据文本框的索引和是否有文本来显示或隐藏复选框 + Log.e(TAG, "Wrong index, should not happen"); + return;// 如果索引超出范围,打印错误日志并返回 + } + if(hasText) { + mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.VISIBLE);// 如果有文本,显示复选框 + } else { + mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.GONE);// 如果没有文本,隐藏复选框 + } + } + + public void onCheckListModeChanged(int oldMode, int newMode) {// 当清单模式改变时 + if (newMode == TextNote.MODE_CHECK_LIST) { // 如果新模式是清单模式 + switchToListMode(mNoteEditor.getText().toString()); // 切换到清单模式 + } else { // 如果新模式不是清单模式 + if (!getWorkingText()) { // 如果当前没有工作文本 + mWorkingNote.setWorkingText(mWorkingNote.getContent().replace(TAG_UNCHECKED + " ", + "")); // 将工作文本设置为去掉未勾选标记的内容 + } + mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery));// 设置文本框的内容为高亮查询结果 + mEditTextList.setVisibility(View.GONE); // 隐藏文本框列表 + mNoteEditor.setVisibility(View.VISIBLE); // 显示文本框 + } + } + + private boolean getWorkingText() {//获取当前编辑的文本内容,包括已完成和未完成的任务列表 + boolean hasChecked = false;//标记是否有已完成的任务 + if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {//如果目前是任务列表模式 + StringBuilder sb = new StringBuilder(); //创建一个字符串构建器 + for (int i = 0; i < mEditTextList.getChildCount(); i++) { //循环遍历所有的子项 + View view = mEditTextList.getChildAt(i);//获取当前子项的视图 + NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text);//获取当前子项的编辑框 + if (!TextUtils.isEmpty(edit.getText())) { //如果编辑框不为空 + if (((CheckBox) view.findViewById(R.id.cb_edit_item)).isChecked()) { //如果当前项被选中 + sb.append(TAG_CHECKED).append(" ").append(edit.getText()).append("\n");//在字符串构建器中添加已完成的任务项 + hasChecked = true;//标记有已完成的任务 + } else {//如果当前项未被选中 + sb.append(TAG_UNCHECKED).append(" ").append(edit.getText()).append("\n");//在字符串构建器中添加未完成的任务项 + } + } + } + mWorkingNote.setWorkingText(sb.toString()); //将构建好的字符串设置为当前工作的文本内容 + } else { //如果不是任务列表模式 + mWorkingNote.setWorkingText(mNoteEditor.getText().toString()); //将编辑框中的文本设置为当前工作的文本内容 + } + return hasChecked; //返回是否有已完成的任务项的标记 + } + + private boolean saveNote() {// 保存笔记到数据库中 + getWorkingText();// 获取编辑框中的文本内容 + boolean saved = mWorkingNote.saveNote();// 将笔记保存到数据库中 + if (saved) { + /** + * There are two modes from List view to edit view, open one note, + * create/edit a node. Opening node requires to the original + * position in the list when back from edit view, while creating a + * new node requires to the top of the list. This code + * {@link #RESULT_OK} is used to identify the create/edit state + */ + setResult(RESULT_OK);// 设置返回结果为RESULT_OK + } + return saved; // 返回是否保存成功的结果 + } + + private void sendToDesktop() { + /** + * Before send message to home, we should make sure that current + * editing note is exists in databases. So, for new note, firstly + * save it + */ + if (!mWorkingNote.existInDatabase()) { + saveNote(); // 如果笔记不存在于数据库中,则先保存笔记 + } + + if (mWorkingNote.getNoteId() > 0) { // 如果笔记存在于数据库中 + Intent sender = new Intent(); // 创建Intent对象 + Intent shortcutIntent = new Intent(this, NoteEditActivity.class); // 创建快捷方式Intent对象 + shortcutIntent.setAction(Intent.ACTION_VIEW); // 设置快捷方式Intent的Action为ACTION_VIEW + shortcutIntent.putExtra(Intent.EXTRA_UID, mWorkingNote.getNoteId()); // 设置快捷方式Intent的额外数据 + sender.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); // 设置发送Intent的额外数据 + sender.putExtra(Intent.EXTRA_SHORTCUT_NAME, + makeShortcutIconTitle(mWorkingNote.getContent())); // 设置发送Intent的额外数据 + sender.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, + Intent.ShortcutIconResource.fromContext(this, R.drawable.icon_app)); // 设置发送Intent的额外数据 + sender.putExtra("duplicate", true); // 设置发送Intent的额外数据 + sender.setAction("com.android.launcher.action.INSTALL_SHORTCUT"); // 设置发送Intent的Action为INSTALL_SHORTCUT + showToast(R.string.info_note_enter_desktop);// 显示Toast提示信息 + sendBroadcast(sender); // 发送广播 + } else { + /** + * There is the condition that user has input nothing (the note is + * not worthy saving), we have no note id, remind the user that he + * should input something + */ + Log.e(TAG, "Send to desktop error");// 打印错误日志信息 + showToast(R.string.error_note_empty_for_send_to_desktop); // 显示Toast提示信息 + } + } + + private String makeShortcutIconTitle(String content) { // 生成快捷方式的图标标题,去掉勾选框的标记 + content = content.replace(TAG_CHECKED, ""); // 去掉已勾选的标记 + content = content.replace(TAG_UNCHECKED, ""); // 去掉未勾选的标记 + return content.length() > SHORTCUT_ICON_TITLE_MAX_LEN ? content.substring(0, + SHORTCUT_ICON_TITLE_MAX_LEN) : content; // 如果标题超出指定长度,截取前 SHORTCUT_ICON_TITLE_MAX_LEN 个字符作为标题 + } + + private void showToast(int resId) { // 显示短时间的提示信息 + showToast(resId, Toast.LENGTH_SHORT); + } + + private void showToast(int resId, int duration) { // 显示指定时间的提示信息 + Toast.makeText(this, resId, duration).show(); + } +} diff --git a/xkw2/NoteWidgetProvider.java b/xkw2/NoteWidgetProvider.java new file mode 100644 index 0000000..caa2dc6 --- /dev/null +++ b/xkw2/NoteWidgetProvider.java @@ -0,0 +1,136 @@ +/* + * 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.widget; +import android.app.PendingIntent; +import android.appwidget.AppWidgetManager; +import android.appwidget.AppWidgetProvider; +import android.content.ContentValues; +import android.content.Context; +import android.content.Intent; +import android.database.Cursor; +import android.util.Log; +import android.widget.RemoteViews; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.tool.ResourceParser; +import net.micode.notes.ui.NoteEditActivity; +import net.micode.notes.ui.NotesListActivity; + +public abstract class NoteWidgetProvider extends AppWidgetProvider { + public static final String [] PROJECTION = new String [] { + NoteColumns.ID,//便签的ID + NoteColumns.BG_COLOR_ID,//背景颜色ID + NoteColumns.SNIPPET//摘录 + };//定义了一个抽象类NoteWidgetProvider,它继承了AppWidgetProvider类 + + public static final int COLUMN_ID = 0; + public static final int COLUMN_BG_COLOR_ID = 1; + public static final int COLUMN_SNIPPET = 2; + + private static final String TAG = "NoteWidgetProvider";//定义字符串变量TAG用于在日志中标记该类的信息。 + + + @Override + public void onDeleted(Context context, int[] appWidgetIds) { + ContentValues values = new ContentValues();//通过使用 ContentResolver.update()方法来更新 Notes.CONTENT_NOTE_URI 数据库中的笔记数据实现的。 + values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); + for (int i = 0; i < appWidgetIds.length; i++) { + context.getContentResolver().update(Notes.CONTENT_NOTE_URI, + values, + NoteColumns.WIDGET_ID + "=?", + new String[] { String.valueOf(appWidgetIds[i])}); + }//更新操作使用 NoteColumns.WIDGET_ID + "=?" 作为查询条件,将笔记中 widget id 与当前 appWidgetId 匹配的记录进行更新。 + } + + private Cursor getNoteWidgetInfo(Context context, int widgetId) { + return context.getContentResolver().query(Notes.CONTENT_NOTE_URI, + PROJECTION,//查询便签内容提供程序的Notes表,查询的投影为PROJECTION + NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>?", + new String[] { String.valueOf(widgetId), String.valueOf(Notes.ID_TRASH_FOLER) }, + null);//查询的条件为NoteColumns.WIDGET_ID = widgetId且NoteColumns.PARENT_ID不等于Notes.ID_TRASH_FOLER。查询结果返回一个Cursor对象。 + }//一个私有方法,用于获取指定widgetId的便签小部件信息。它接收两个参数:上下文Context和widgetId + + protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { + update(context, appWidgetManager, appWidgetIds, false); + }//调用了另一个重载的 update 方法,并将最后一个参数设置为 false + + private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds, + boolean privacyMode) { + for (int i = 0; i < appWidgetIds.length; i++) { + if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) { + int bgId = ResourceParser.getDefaultBgId(context); + String snippet = ""; + Intent intent = new Intent(context, NoteEditActivity.class); + intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); + intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, appWidgetIds[i]); + intent.putExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, getWidgetType());//获取默认的背景ID和空字符串片段,并创建一个Intent对象,该对象指向NoteEditActivity类 + + Cursor c = getNoteWidgetInfo(context, appWidgetIds[i]);//调用 getNoteWidgetInfo() 方法获取 widget 的信息 + if (c != null && c.moveToFirst()) { + if (c.getCount() > 1) { + Log.e(TAG, "Multiple message with same widget id:" + appWidgetIds[i]); + c.close(); + return; + } + snippet = c.getString(COLUMN_SNIPPET); + bgId = c.getInt(COLUMN_BG_COLOR_ID); + intent.putExtra(Intent.EXTRA_UID, c.getLong(COLUMN_ID)); + intent.setAction(Intent.ACTION_VIEW); + } //如果获取到了信息,就从 Cursor 对象中获取 snippet 和背景图像 ID,并将这些数据设置到 Intent 对象中。 + else { + snippet = context.getResources().getString(R.string.widget_havenot_content); + intent.setAction(Intent.ACTION_INSERT_OR_EDIT); + }//如果没有获取到信息,就设置 snippet 为默认的文本内容,并将 Intent 对象的 action 设置为 ACTION_INSERT_OR_EDIT。 + + if (c != null) { + c.close(); + } + + RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId());//创建一个 RemoteViews 对象,并设置背景图像和文本内容 + rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId)); + intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId);//根据 privacyMode 的值,为 RemoteViews 对象设置一个点击事件 + /** + * Generate the pending intent to start host for the widget + */ + PendingIntent pendingIntent = null; + if (privacyMode) { + rv.setTextViewText(R.id.widget_text, + context.getString(R.string.widget_under_visit_mode)); + pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], new Intent( + context, NotesListActivity.class), PendingIntent.FLAG_UPDATE_CURRENT); + }//如果 privacyMode 为 true,就将文本内容设置为“正在访问模式下”,并创建一个 PendingIntent 对象,指向 NotesListActivity 类 + else { + rv.setTextViewText(R.id.widget_text, snippet); + pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], intent, + PendingIntent.FLAG_UPDATE_CURRENT); + }//如果 privacyMode 为 false,就将文本内容设置为 snippet,并创建一个 PendingIntent 对象,指向 NoteEditActivity 类 + + rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent);//PendingIntent 对象设置为 RemoteViews 对象的点击事件 + appWidgetManager.updateAppWidget(appWidgetIds[i], rv);//使用 AppWidgetManager 对象更新 widget。 + + }//检查每个ID是否为INVALID_APPWIDGET_ID, for 循环遍历 appWidgetIds 数组中的每个 widget,并对每个 widget 进行更新。 + } + } + + protected abstract int getBgResourceId(int bgId);//根据给定的背景资源ID获取背景资源的资源ID + + protected abstract int getLayoutId();//获取布局文件的资源ID + + protected abstract int getWidgetType();//获取小部件的类型 +} diff --git a/xkw2/NoteWidgetProvider_2x.java b/xkw2/NoteWidgetProvider_2x.java new file mode 100644 index 0000000..3fbb2da --- /dev/null +++ b/xkw2/NoteWidgetProvider_2x.java @@ -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.widget; + +import android.appwidget.AppWidgetManager; +import android.content.Context; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.tool.ResourceParser; + + +public class NoteWidgetProvider_2x extends NoteWidgetProvider { + @Override + public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { + super.update(context, appWidgetManager, appWidgetIds);//重写了 onUpdate() 方法,调用了父类的 update() 方法 + }//继承自 NoteWidgetProvider 类 + + @Override + protected int getLayoutId() { + return R.layout.widget_2x; + }//重写了 getLayoutId() 方法,返回小部件布局的 ID + + @Override + protected int getBgResourceId(int bgId) { + return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId); + }//重写了 getBgResourceId() 方法,返回小部件背景资源的 ID + + @Override + protected int getWidgetType() { + return Notes.TYPE_WIDGET_2X; + } +}//重写了 getWidgetType() 方法,返回小部件的类型 diff --git a/xkw2/NoteWidgetProvider_4x.java b/xkw2/NoteWidgetProvider_4x.java new file mode 100644 index 0000000..4c43477 --- /dev/null +++ b/xkw2/NoteWidgetProvider_4x.java @@ -0,0 +1,46 @@ +/* + * 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.widget; + +import android.appwidget.AppWidgetManager; +import android.content.Context; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.tool.ResourceParser; + + +public class NoteWidgetProvider_4x extends NoteWidgetProvider { + @Override + public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { + super.update(context, appWidgetManager, appWidgetIds); + }//调用了父类NoteWidgetProvider的update方法,更新了widget + + protected int getLayoutId() { + return R.layout.widget_4x; + }//返回了widget布局文件的资源id,即R.layout.widget_4x + + @Override + protected int getBgResourceId(int bgId) { + return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId); + }//据传入的背景id,获取对应的widget背景资源id,具体实现在ResourceParser.WidgetBgResources类中 + + @Override + protected int getWidgetType() { + return Notes.TYPE_WIDGET_4X; + } +}//返回了widget类型,即Notes.TYPE_WIDGET_4X