From 42ab2829259dc3e4b1b7db115b07ae32edcf37ea Mon Sep 17 00:00:00 2001 From: liuzhilong <1715279031@QQ.com> Date: Wed, 28 Jan 2026 13:30:07 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BB=A3=E7=A0=81=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ui/AlarmAlertActivity.java | 158 ++ src/ui/AlarmInitReceiver.java | 65 + src/ui/AlarmReceiver.java | 30 + src/ui/DateTimePicker.java | 485 ++++++ src/ui/DateTimePickerDialog.java | 90 ++ src/ui/DropdownMenu.java | 61 + src/ui/FoldersListAdapter.java | 80 + src/ui/NoteEditActivity.java | 2278 +++++++++++++++++++++++++++ src/ui/NoteEditText.java | 411 +++++ src/ui/NoteItemData.java | 293 ++++ src/ui/NotesListActivity.java | 1690 ++++++++++++++++++++ src/ui/NotesListAdapter.java | 353 +++++ src/ui/NotesListItem.java | 169 ++ src/ui/NotesPreferenceActivity.java | 426 +++++ src/ui/PasswordLockActivity.java | 229 +++ src/ui/PasswordSetActivity.java | 315 ++++ src/ui/TableEditActivity.java | 244 +++ src/ui/TrashListActivity.java | 386 +++++ 18 files changed, 7763 insertions(+) create mode 100644 src/ui/AlarmAlertActivity.java create mode 100644 src/ui/AlarmInitReceiver.java create mode 100644 src/ui/AlarmReceiver.java create mode 100644 src/ui/DateTimePicker.java create mode 100644 src/ui/DateTimePickerDialog.java create mode 100644 src/ui/DropdownMenu.java create mode 100644 src/ui/FoldersListAdapter.java create mode 100644 src/ui/NoteEditActivity.java create mode 100644 src/ui/NoteEditText.java create mode 100644 src/ui/NoteItemData.java create mode 100644 src/ui/NotesListActivity.java create mode 100644 src/ui/NotesListAdapter.java create mode 100644 src/ui/NotesListItem.java create mode 100644 src/ui/NotesPreferenceActivity.java create mode 100644 src/ui/PasswordLockActivity.java create mode 100644 src/ui/PasswordSetActivity.java create mode 100644 src/ui/TableEditActivity.java create mode 100644 src/ui/TrashListActivity.java diff --git a/src/ui/AlarmAlertActivity.java b/src/ui/AlarmAlertActivity.java new file mode 100644 index 0000000..85723be --- /dev/null +++ b/src/ui/AlarmAlertActivity.java @@ -0,0 +1,158 @@ +/* + * 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; + 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(); + + try { + mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1)); + 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 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 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); + intent.setAction(Intent.ACTION_VIEW); + intent.putExtra(Intent.EXTRA_UID, mNoteId); + startActivity(intent); + break; + default: + break; + } + } + + public void onDismiss(DialogInterface dialog) { + stopAlarmSound(); + finish(); + } + + private void stopAlarmSound() { + if (mPlayer != null) { + mPlayer.stop(); + mPlayer.release(); + mPlayer = null; + } + } +} diff --git a/src/ui/AlarmInitReceiver.java b/src/ui/AlarmInitReceiver.java new file mode 100644 index 0000000..b2d58ca --- /dev/null +++ b/src/ui/AlarmInitReceiver.java @@ -0,0 +1,65 @@ +/* + * 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 { + + private static final String [] PROJECTION = new String [] { + NoteColumns.ID, + NoteColumns.ALERTED_DATE + }; + + private static final int COLUMN_ID = 0; + 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, + 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, PendingIntent.FLAG_IMMUTABLE); + AlarmManager alermManager = (AlarmManager) context + .getSystemService(Context.ALARM_SERVICE); + alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent); + } while (c.moveToNext()); + } + c.close(); + } + } +} diff --git a/src/ui/AlarmReceiver.java b/src/ui/AlarmReceiver.java new file mode 100644 index 0000000..54e503b --- /dev/null +++ b/src/ui/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 { + @Override + public void onReceive(Context context, Intent intent) { + intent.setClass(context, AlarmAlertActivity.class); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + context.startActivity(intent); + } +} diff --git a/src/ui/DateTimePicker.java b/src/ui/DateTimePicker.java new file mode 100644 index 0000000..496b0cd --- /dev/null +++ b/src/ui/DateTimePicker.java @@ -0,0 +1,485 @@ +/* + * 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 { + + 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; + + 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) { + 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(); + } + } else { + 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) { + 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; + } + if (offset != 0) { + mDate.add(Calendar.HOUR_OF_DAY, offset); + mHourSpinner.setValue(getCurrentHour()); + updateDateControl(); + int newHour = getCurrentHourOfDay(); + 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() { + @Override + public void onValueChange(NumberPicker picker, int oldVal, int newVal) { + mIsAm = !mIsAm; + if (mIsAm) { + mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY); + } else { + mDate.add(Calendar.HOUR_OF_DAY, HOURS_IN_HALF_DAY); + } + updateAmPmControl(); + 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)); + } + + 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); + + 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); + + // 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); + 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); + } + + 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; + } + } + } + + /** + * 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) { + 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(); + } + + /** + * 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; + } + 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(); + } + + 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); + } + } + + /** + * 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()); + } + } +} diff --git a/src/ui/DateTimePickerDialog.java b/src/ui/DateTimePickerDialog.java new file mode 100644 index 0000000..2c47ba4 --- /dev/null +++ b/src/ui/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 { + + private Calendar mDate = Calendar.getInstance(); + private boolean mIs24HourView; + private OnDateTimeSetListener mOnDateTimeSetListener; + private DateTimePicker mDateTimePicker; + + public interface OnDateTimeSetListener { + void OnDateTimeSet(AlertDialog dialog, long date); + } + + 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); + 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())); + updateTitle(mDate.getTimeInMillis()); + } + + public void set24HourView(boolean is24HourView) { + mIs24HourView = is24HourView; + } + + public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) { + mOnDateTimeSetListener = callBack; + } + + private void updateTitle(long date) { + int flag = + DateUtils.FORMAT_SHOW_YEAR | + DateUtils.FORMAT_SHOW_DATE | + DateUtils.FORMAT_SHOW_TIME; + flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR; + setTitle(DateUtils.formatDateTime(this.getContext(), date, flag)); + } + + public void onClick(DialogInterface arg0, int arg1) { + if (mOnDateTimeSetListener != null) { + mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis()); + } + } + +} \ No newline at end of file diff --git a/src/ui/DropdownMenu.java b/src/ui/DropdownMenu.java new file mode 100644 index 0000000..613dc74 --- /dev/null +++ b/src/ui/DropdownMenu.java @@ -0,0 +1,61 @@ +/* + * 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) { + mButton = button; + mButton.setBackgroundResource(R.drawable.dropdown_icon); + mPopupMenu = new PopupMenu(context, mButton); + mMenu = mPopupMenu.getMenu(); + mPopupMenu.getMenuInflater().inflate(menuId, mMenu); + mButton.setOnClickListener(new OnClickListener() { + 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); + } + + public void setTitle(CharSequence title) { + mButton.setText(title); + } +} diff --git a/src/ui/FoldersListAdapter.java b/src/ui/FoldersListAdapter.java new file mode 100644 index 0000000..96b77da --- /dev/null +++ b/src/ui/FoldersListAdapter.java @@ -0,0 +1,80 @@ +/* + * 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 { + public static final String [] PROJECTION = { + NoteColumns.ID, + NoteColumns.SNIPPET + }; + + public static final int ID_COLUMN = 0; + public static final int NAME_COLUMN = 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) { + 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) 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 { + private TextView mName; + + public FolderListItem(Context context) { + super(context); + inflate(context, R.layout.folder_list_item, this); + mName = (TextView) findViewById(R.id.tv_folder_name); + } + + public void bind(String name) { + mName.setText(name); + } + } + +} diff --git a/src/ui/NoteEditActivity.java b/src/ui/NoteEditActivity.java new file mode 100644 index 0000000..62374c9 --- /dev/null +++ b/src/ui/NoteEditActivity.java @@ -0,0 +1,2278 @@ +/* + * 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.database.Cursor; +import android.graphics.Paint; +import android.os.AsyncTask; +import android.os.Bundle; +import android.os.Handler; +import android.preference.PreferenceManager; +import android.text.Spannable; +import android.text.SpannableString; +import android.text.SpannableStringBuilder; +import android.text.Spanned; +import android.text.TextUtils; +import android.text.format.DateUtils; +import android.text.style.BackgroundColorSpan; +import android.text.style.StrikethroughSpan; +import android.text.style.StyleSpan; +import android.text.style.UnderlineSpan; +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.ViewGroup; +import android.view.WindowManager; +import android.widget.ArrayAdapter; +import android.widget.Button; +import android.widget.CheckBox; +import android.widget.CompoundButton; +import android.widget.CompoundButton.OnCheckedChangeListener; +import android.widget.EditText; +import android.widget.ImageButton; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.ListView; +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.ArrayList; +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 { + public TextView tvModified; + + public ImageView ivAlertIcon; + + public TextView tvAlertDate; + + public ImageView ibSetBgColor; + } + 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 sFontSizeBtnsMap = new HashMap(); + static { + sFontSizeBtnsMap.put(R.id.ll_font_large, ResourceParser.TEXT_LARGE); + sFontSizeBtnsMap.put(R.id.ll_font_small, ResourceParser.TEXT_SMALL); + sFontSizeBtnsMap.put(R.id.ll_font_normal, ResourceParser.TEXT_MEDIUM); + sFontSizeBtnsMap.put(R.id.ll_font_super, ResourceParser.TEXT_SUPER); + } + + 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; + private static final int REQUEST_CODE_TABLE_EDIT = 100; + private static final int REQUEST_CODE_PICK_IMAGE = 101; + private static final int REQUEST_CODE_IMAGE_PERMISSIONS = 102; + + public static final String TAG_CHECKED = String.valueOf('\u221A'); + public static final String TAG_UNCHECKED = String.valueOf('\u25A1'); + + private LinearLayout mEditTextList; + + // 标签显示区域 + private LinearLayout mTagsLayout; + private LinearLayout mRichTextToolbar; + + // 字数统计 + private TextView mWordCountTextView; + + private String mUserQuery; + private Pattern mPattern; + + // 搜索相关 + private ImageButton mSearchButton; + private LinearLayout mSearchContainer; + private EditText mSearchEditText; + private ImageButton mClearSearchButton; + private ImageButton mCloseSearchButton; + private LinearLayout mSearchResultsContainer; + private ListView mSearchResultsListView; + private TextView mNoSearchResultsTextView; + private ArrayList mSearchResults; + private SearchResultAdapter mSearchResultAdapter; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + this.setContentView(R.layout.note_edit); + + if (savedInstanceState == null && !initActivityState(getIntent())) { + finish(); + return; + } + initResources(); + + // 确保富文本工具栏可见 + LinearLayout richTextToolbar = (LinearLayout) findViewById(R.id.rich_text_toolbar); + if (richTextToolbar != null) { + richTextToolbar.setVisibility(View.VISIBLE); + Log.d(TAG, "Rich text toolbar visibility set to VISIBLE in onCreate"); + } + + // 延迟一段时间后再次设置富文本工具栏可见性,确保所有初始化完成后仍然可见 + new Handler().postDelayed(new Runnable() { + @Override + public void run() { + LinearLayout delayedToolbar = (LinearLayout) findViewById(R.id.rich_text_toolbar); + if (delayedToolbar != null) { + delayedToolbar.setVisibility(View.VISIBLE); + Log.d(TAG, "Rich text toolbar visibility set to VISIBLE with delay"); + } + } + }, 100); + } + + /** + * 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) { + super.onRestoreInstanceState(savedInstanceState); + if (savedInstanceState != null && savedInstanceState.containsKey(Intent.EXTRA_UID)) { + Intent intent = new Intent(Intent.ACTION_VIEW); + intent.putExtra(Intent.EXTRA_UID, savedInstanceState.getLong(Intent.EXTRA_UID)); + if (!initActivityState(intent)) { + finish(); + return; + } + Log.d(TAG, "Restoring from killed activity"); + } + } + + private boolean initActivityState(Intent intent) { + try { + /** + * If the user specified the {@link Intent#ACTION_VIEW} but not provided with id, + * then jump to the NotesListActivity + */ + mWorkingNote = null; + if (TextUtils.equals(Intent.ACTION_VIEW, intent.getAction())) { + long noteId = intent.getLongExtra(Intent.EXTRA_UID, 0); + mUserQuery = ""; + + /** + * Starting from the searched result + */ + if (intent.hasExtra(SearchManager.EXTRA_DATA_KEY)) { + noteId = Long.parseLong(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY)); + mUserQuery = intent.getStringExtra(SearchManager.USER_QUERY); + } + + if (!DataUtils.visibleInNoteDatabase(getContentResolver(), noteId, Notes.TYPE_NOTE)) { + Intent jump = new Intent(this, NotesListActivity.class); + startActivity(jump); + showToast(R.string.error_note_not_exist); + finish(); + return false; + } else { + mWorkingNote = WorkingNote.load(this, noteId); + 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())) { + // New note + long folderId = intent.getLongExtra(Notes.INTENT_EXTRA_FOLDER_ID, 0); + int widgetId = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_ID, + AppWidgetManager.INVALID_APPWIDGET_ID); + int widgetType = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, + Notes.TYPE_WIDGET_INVALIDE); + int bgResId = intent.getIntExtra(Notes.INTENT_EXTRA_BACKGROUND_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; + if ((noteId = DataUtils.getNoteIdByPhoneNumberAndCallDate(getContentResolver(), + phoneNumber, callDate)) > 0) { + mWorkingNote = WorkingNote.load(this, noteId); + if (mWorkingNote == null) { + Log.e(TAG, "load call note failed with note id" + noteId); + finish(); + return false; + } + } else { + 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); + return true; + } catch (Exception e) { + Log.e(TAG, "Error initializing activity state: " + e.toString()); + e.printStackTrace(); + showToast(R.string.error_note_not_exist); + finish(); + return false; + } + } + + @Override + protected void onResume() { + super.onResume(); + if (mWorkingNote != null) { + // 优化:只在必要时初始化界面 + initNoteScreen(); + // 优化:只在必要时更新标签显示 + updateTagsDisplay(); + } + } + + private void initNoteScreen() { + if (mWorkingNote == null || mNoteEditor == null || mHeadViewPanel == null || mNoteEditorPanel == null || mNoteHeaderHolder == null) { + return; + } + + try { + mNoteEditor.setTextAppearance(this, TextAppearanceResources + .getTexAppearanceResource(mFontSizeId)); + if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { + switchToListMode(mWorkingNote.getContent()); + } else { + // 普通文本模式下,处理内容 + CharSequence content = mWorkingNote.getContent(); + if (content != null) { + String contentStr = content.toString(); + if (contentStr.contains("[IMAGE]") && contentStr.contains("[/IMAGE]")) { + // 包含图片占位符,处理图片显示 + android.text.SpannableStringBuilder spannableContent = processImageContent(contentStr); + mNoteEditor.setText(getHighlightQueryResult(spannableContent, mUserQuery)); + } else if (contentStr.startsWith("<")) { + // 是HTML格式,转换为SpannableString + content = android.text.Html.fromHtml(contentStr); + mNoteEditor.setText(getHighlightQueryResult(content, mUserQuery)); + } else { + // 普通文本,直接加载 + mNoteEditor.setText(getHighlightQueryResult(content, mUserQuery)); + } + mNoteEditor.setSelection(mNoteEditor.getText().length()); + } + } + // 无论什么模式,都强制显示富文本工具栏 + if (mRichTextToolbar != null) { + mRichTextToolbar.setVisibility(View.VISIBLE); + } + 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(); + } catch (Exception e) { + Log.e(TAG, "Error initializing note screen: " + e.toString()); + e.printStackTrace(); + } + } + + 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); + if (!initActivityState(intent)) { + finish(); + return; + } + } + + @Override + protected void onSaveInstanceState(Bundle outState) { + 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()); + Log.d(TAG, "Save working note id: " + mWorkingNote.getNoteId() + " onSaveInstanceState"); + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + if (requestCode == REQUEST_CODE_TABLE_EDIT && resultCode == RESULT_OK) { + Log.d(TAG, "收到表格编辑器返回结果"); + if (data != null && data.hasExtra(TableEditActivity.RESULT_TABLE_HTML)) { + String tableHtml = data.getStringExtra(TableEditActivity.RESULT_TABLE_HTML); + Log.d(TAG, "接收到表格HTML,长度: " + (tableHtml != null ? tableHtml.length() : 0)); + Log.d(TAG, "表格HTML内容: " + tableHtml); + if (tableHtml != null && !tableHtml.isEmpty()) { + insertHtmlAtCursor(tableHtml); + } + } + } else if (requestCode == REQUEST_CODE_PICK_IMAGE && resultCode == RESULT_OK && data != null) { + // 处理图片选择结果 + android.net.Uri imageUri = data.getData(); + if (imageUri != null) { + try { + // 处理选择的图片 + handleSelectedImage(imageUri); + } catch (Exception e) { + e.printStackTrace(); + Log.e(TAG, "Error handling selected image: " + e.toString()); + showToast(R.string.error_image_processing); + } + } + } + } + + /** + * 处理权限请求结果 + */ + @Override + public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + if (requestCode == REQUEST_CODE_IMAGE_PERMISSIONS) { + if (grantResults.length > 0 && grantResults[0] == android.content.pm.PackageManager.PERMISSION_GRANTED) { + // 权限授予成功,启动图片选择 + pickImageFromGallery(); + } else { + // 权限授予失败 + showToast(R.string.error_permission_denied); + } + } + } + + /** + * 在光标位置插入HTML内容 + * @param html HTML内容 + */ + private void insertHtmlAtCursor(String html) { + try { + if (mNoteEditor == null) { + return; + } + + // 直接将表格HTML作为纯文本插入,因为Html.fromHtml()不支持表格标签 + String tableText = "[表格]\n" + html + "\n[/表格]"; + + // 获取当前光标位置 + int cursorPosition = mNoteEditor.getSelectionStart(); + + // 在光标位置插入表格文本 + SpannableStringBuilder builder = new SpannableStringBuilder(mNoteEditor.getText()); + builder.insert(cursorPosition, tableText); + + // 设置文本并移动光标到插入内容之后 + mNoteEditor.setText(builder); + mNoteEditor.setSelection(cursorPosition + tableText.length()); + + Log.d(TAG, "Inserted table HTML as text: " + html); + } catch (Exception e) { + Log.e(TAG, "Error inserting HTML at cursor: " + e.toString()); + e.printStackTrace(); + showToast(R.string.operation_failed); + } + } + + @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; + } + + // 点击空白区域关闭搜索框 + if (mSearchContainer != null && mSearchContainer.getVisibility() == View.VISIBLE) { + boolean inSearchContainer = inRangeOfView(mSearchContainer, ev); + boolean inSearchResults = false; + if (mSearchResultsContainer != null && mSearchResultsContainer.getVisibility() == View.VISIBLE) { + inSearchResults = inRangeOfView(mSearchResultsContainer, ev); + } + if (!inSearchContainer && !inSearchResults) { + closeSearch(); + 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); + if (mNoteHeaderHolder.ibSetBgColor != null) { + mNoteHeaderHolder.ibSetBgColor.setOnClickListener(this); + } + + // 初始化字体大小按钮(T图标) + ImageButton btnFontSize = (ImageButton) findViewById(R.id.btn_font_size); + if (btnFontSize != null) { + btnFontSize.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); + if (iv != null) { + iv.setOnClickListener(this); + } + } + + mFontSizeSelector = findViewById(R.id.font_size_selector); + for (int id : sFontSizeBtnsMap.keySet()) { + View view = findViewById(id); + if (view != null) { + view.setOnClickListener(this); + } + }; + mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); + mFontSizeId = mSharedPrefs.getInt(PREFERENCE_FONT_SIZE, ResourceParser.BG_DEFAULT_FONT_SIZE); + /** + * 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; + } + mEditTextList = (LinearLayout) findViewById(R.id.note_edit_list); + + // 初始化富文本工具栏 + mRichTextToolbar = (LinearLayout) findViewById(R.id.rich_text_toolbar); + Log.d(TAG, "Rich text toolbar initialized: " + (mRichTextToolbar != null)); + + // 设置富文本按钮点击事件 + View btnBold = findViewById(R.id.btn_bold); + if (btnBold != null) { + btnBold.setOnClickListener(this); + Log.d(TAG, "Bold button found and set up"); + } + View btnItalic = findViewById(R.id.btn_italic); + if (btnItalic != null) { + btnItalic.setOnClickListener(this); + Log.d(TAG, "Italic button found and set up"); + } + View btnUnderline = findViewById(R.id.btn_underline); + if (btnUnderline != null) { + btnUnderline.setOnClickListener(this); + Log.d(TAG, "Underline button found and set up"); + } + View btnStrikethrough = findViewById(R.id.btn_strikethrough); + if (btnStrikethrough != null) { + btnStrikethrough.setOnClickListener(this); + Log.d(TAG, "Strikethrough button found and set up"); + } + + View btnTable = findViewById(R.id.btn_table); + if (btnTable != null) { + btnTable.setOnClickListener(this); + Log.d(TAG, "Table button found and set up"); + } + + // 初始化图片插入按钮 + View btnImage = findViewById(R.id.btn_image); + if (btnImage != null) { + btnImage.setOnClickListener(this); + Log.d(TAG, "Image button found and set up"); + } + + // 初始化搜索按钮 + mSearchButton = (ImageButton) findViewById(R.id.btn_search); + if (mSearchButton != null) { + mSearchButton.setOnClickListener(this); + Log.d(TAG, "Search button found and set up"); + } + + // 初始化搜索相关控件 + mSearchContainer = (LinearLayout) findViewById(R.id.search_container); + mSearchEditText = (EditText) findViewById(R.id.et_search); + mClearSearchButton = (ImageButton) findViewById(R.id.btn_clear_search); + mCloseSearchButton = (ImageButton) findViewById(R.id.btn_close_search); + mSearchResultsContainer = (LinearLayout) findViewById(R.id.search_results); + mSearchResultsListView = (ListView) findViewById(R.id.lv_search_results); + mNoSearchResultsTextView = (TextView) findViewById(R.id.tv_search_no_results); + + // 设置搜索相关按钮点击事件 + if (mClearSearchButton != null) { + mClearSearchButton.setOnClickListener(this); + } + if (mCloseSearchButton != null) { + mCloseSearchButton.setOnClickListener(this); + } + + // 设置搜索输入框文本变化监听器 + if (mSearchEditText != null) { + mSearchEditText.addTextChangedListener(new android.text.TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + // 当搜索文本变化时,执行搜索 + performSearch(s.toString()); + } + + @Override + public void afterTextChanged(android.text.Editable s) { + } + }); + } + + // 初始化搜索结果列表 + mSearchResults = new ArrayList<>(); + mSearchResultAdapter = new SearchResultAdapter(this, mSearchResults); + if (mSearchResultsListView != null) { + mSearchResultsListView.setAdapter(mSearchResultAdapter); + // 设置搜索结果点击事件 + mSearchResultsListView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() { + @Override + public void onItemClick(android.widget.AdapterView parent, View view, int position, long id) { + // 点击搜索结果,跳转到对应位置 + SearchResult result = mSearchResults.get(position); + jumpToSearchResult(result); + } + }); + } + + // 初始化标签显示区域 + mTagsLayout = (LinearLayout) findViewById(R.id.ll_note_tags); + if (mTagsLayout != null) { + // 初始化标签管理按钮 + ImageButton btnManageTags = (ImageButton) findViewById(R.id.btn_manage_tags); + if (btnManageTags != null) { + btnManageTags.setOnClickListener(this); + } + updateTagsDisplay(); + } + + // 初始化字数统计 TextView + mWordCountTextView = (TextView) findViewById(R.id.tv_word_count); + + // 为普通文本模式添加文本变化监听器 + if (mNoteEditor != null) { + mNoteEditor.addTextChangedListener(new android.text.TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + // 文本变化时更新字数统计 + updateWordCount(); + } + + @Override + public void afterTextChanged(android.text.Editable s) { + } + }); + } + + // 确保富文本工具栏默认可见 + if (mRichTextToolbar != null) { + mRichTextToolbar.setVisibility(View.VISIBLE); + Log.d(TAG, "Rich text toolbar visibility set to VISIBLE"); + } + + // 额外的可见性设置,确保富文本工具栏显示 + LinearLayout richTextToolbar = (LinearLayout) findViewById(R.id.rich_text_toolbar); + if (richTextToolbar != null) { + richTextToolbar.setVisibility(View.VISIBLE); + Log.d(TAG, "Rich text toolbar visibility set to VISIBLE (extra)"); + } + + // 初始化时更新字数统计 + updateWordCount(); + } + + @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() + }); + + sendBroadcast(intent); + setResult(RESULT_OK, intent); + } + + public void onClick(View v) { + int id = v.getId(); + if (id == R.id.btn_set_bg_color) { + mNoteBgColorSelector.setVisibility(View.VISIBLE); + } else if (id == R.id.btn_font_size) { + // 处理字体大小按钮点击事件 + if (mFontSizeSelector != null) { + mFontSizeSelector.setVisibility(View.VISIBLE); + } + } else if (sBgSelectorBtnsMap.containsKey(id)) { + mWorkingNote.setBgColorId(sBgSelectorBtnsMap.get(id)); + mNoteBgColorSelector.setVisibility(View.GONE); + } else if (sFontSizeBtnsMap.containsKey(id)) { + mFontSizeId = sFontSizeBtnsMap.get(id); + mSharedPrefs.edit().putInt(PREFERENCE_FONT_SIZE, mFontSizeId).commit(); + if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { + getWorkingText(); + switchToListMode(mWorkingNote.getContent()); + } else { + mNoteEditor.setTextAppearance(this, + TextAppearanceResources.getTexAppearanceResource(mFontSizeId)); + } + mFontSizeSelector.setVisibility(View.GONE); + } else if (id == R.id.btn_bold) { + applyRichTextStyle(android.graphics.Typeface.BOLD); + } else if (id == R.id.btn_italic) { + applyRichTextStyle(android.graphics.Typeface.ITALIC); + } else if (id == R.id.btn_underline) { + applyUnderlineStyle(); + } else if (id == R.id.btn_strikethrough) { + applyStrikethroughStyle(); + } else if (id == R.id.btn_table) { + // 启动表格编辑器 + Intent intent = new Intent(this, TableEditActivity.class); + startActivityForResult(intent, REQUEST_CODE_TABLE_EDIT); + } else if (id == R.id.btn_image) { + // 处理图片插入按钮点击 + requestImagePermissionsAndPick(); + } else if (id == R.id.btn_manage_tags) { + // 处理标签管理按钮点击 + showTagsDialog(); + } else if (id == R.id.btn_search) { + // 处理搜索按钮点击 + toggleSearch(); + } else if (id == R.id.btn_clear_search) { + // 处理清除搜索按钮点击 + clearSearch(); + } else if (id == R.id.btn_close_search) { + // 处理关闭搜索按钮点击 + closeSearch(); + } + } + + @Override + public void onBackPressed() { + if(clearSettingState()) { + return; + } + + saveNote(); + super.onBackPressed(); + } + + private boolean clearSettingState() { + if (mNoteBgColorSelector.getVisibility() == View.VISIBLE) { + mNoteBgColorSelector.setVisibility(View.GONE); + return true; + } else if (mFontSizeSelector.getVisibility() == View.VISIBLE) { + mFontSizeSelector.setVisibility(View.GONE); + return true; + } + return false; + } + + public void onBackgroundColorChanged() { + mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId()); + mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId()); + } + + @Override + public boolean onPrepareOptionsMenu(Menu menu) { + if (isFinishing()) { + 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; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + try { + if (item == null) { + return true; + } + + int itemId = item.getItemId(); + if (itemId == R.id.menu_new_note) { + createNewNote(); + } else if (itemId == 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) { + try { + deleteCurrentNote(); + finish(); + } catch (Exception e) { + Log.e(TAG, "Error deleting note: " + e.toString()); + e.printStackTrace(); + } + } + }); + builder.setNegativeButton(android.R.string.cancel, null); + builder.show(); + } else if (itemId == R.id.menu_font_size) { + if (mFontSizeSelector != null) { + mFontSizeSelector.setVisibility(View.VISIBLE); + } + } else if (itemId == R.id.menu_list_mode) { + if (mWorkingNote != null) { + mWorkingNote.setCheckListMode(mWorkingNote.getCheckListMode() == 0 ? + TextNote.MODE_CHECK_LIST : 0); + } + } else if (itemId == R.id.menu_share) { + if (mWorkingNote != null) { + getWorkingText(); + sendTo(this, mWorkingNote.getContent()); + } + } else if (itemId == R.id.menu_send_to_desktop) { + sendToDesktop(); + } else if (itemId == R.id.menu_alert) { + setReminder(); + } else if (itemId == R.id.menu_delete_remind) { + if (mWorkingNote != null) { + mWorkingNote.setAlertDate(0, false); + } + } else if (itemId == R.id.menu_tags) { + showTagsDialog(); + } + } catch (Exception e) { + Log.e(TAG, "Error handling options item selection: " + e.toString()); + e.printStackTrace(); + showToast(R.string.operation_failed); + } + return 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(); + Intent intent = new Intent(this, NoteEditActivity.class); + intent.setAction(Intent.ACTION_INSERT_OR_EDIT); + intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mWorkingNote.getFolderId()); + startActivity(intent); + } + + private void deleteCurrentNote() { + if (mWorkingNote.existInDatabase()) { + HashSet ids = new HashSet(); + long id = mWorkingNote.getNoteId(); + if (id != Notes.ID_ROOT_FOLDER) { + ids.add(id); + } else { + Log.d(TAG, "Wrong note id, should not happen"); + } + if (!isSyncMode()) { + if (!DataUtils.batchDeleteNotes(getContentResolver(), ids)) { + Log.e(TAG, "Delete Note error"); + } + } else { + if (!DataUtils.batchMoveToFolder(getContentResolver(), ids, Notes.ID_TRASH_FOLDER)) { + 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())); + PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_IMMUTABLE); + 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(); + } + + /** + * 处理置顶状态变化 + * + * @param pinned 新的置顶状态:0-未置顶,1-已置顶 + */ + @Override + public void onPinnedStatusChanged(int pinned) { + Log.d(TAG, "Pinned status changed to: " + pinned); + // 可以在这里添加UI更新逻辑,比如显示/隐藏置顶图标 + // 或者更新菜单项状态等 + if (mWorkingNote != null) { + // 可以在这里触发相关的UI更新 + // 例如:刷新标题栏显示、更新菜单项等 + } + } + + public void onEditTextDelete(int index, String text) { + int childCount = mEditTextList.getChildCount(); + if (childCount == 1) { + return; + } + + for (int i = index + 1; i < childCount; i++) { + ((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) { + /** + * 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++) { + ((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text)) + .setIndex(i); + } + } + + private void switchToListMode(String text) { + mEditTextList.removeAllViews(); + String[] items = text.split("\n"); + int index = 0; + for (String item : items) { + if(!TextUtils.isEmpty(item)) { + mEditTextList.addView(getListItem(item, index)); + index++; + } + } + mEditTextList.addView(getListItem("", index)); + mEditTextList.getChildAt(index).findViewById(R.id.et_edit_text).requestFocus(); + + mNoteEditor.setVisibility(View.GONE); + mEditTextList.setVisibility(View.VISIBLE); + } + + private Spannable getHighlightQueryResult(CharSequence fullText, String userQuery) { + SpannableString spannable; + if (fullText instanceof Spannable) { + // 如果已经是Spannable,创建一个新的SpannableString来保留格式 + spannable = new SpannableString(fullText); + } else { + // 否则创建一个新的SpannableString + spannable = new SpannableString(fullText == null ? "" : fullText.toString()); + } + + if (!TextUtils.isEmpty(userQuery)) { + mPattern = Pattern.compile(userQuery); + Matcher m = mPattern.matcher(spannable); + 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); + } + + // 清单模式下文本变化时更新字数统计 + updateWordCount(); + } + + 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); + } + + // 模式切换时更新字数统计 + updateWordCount(); + } + + /** + * 获取当前编辑的文本内容 + */ + private boolean getWorkingText() { + try { + if (mWorkingNote == null) { + return false; + } + + if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { + // 处理清单模式的文本 + StringBuilder sb = new StringBuilder(); + if (mEditTextList != null) { + for (int i = 0; i < mEditTextList.getChildCount(); i++) { + View v = mEditTextList.getChildAt(i); + if (v != null) { + EditText et = (EditText) v.findViewById(R.id.et_edit_text); + CheckBox cb = (CheckBox) v.findViewById(R.id.cb_edit_item); + if (et != null && cb != null) { + String text = et.getText().toString(); + if (!TextUtils.isEmpty(text)) { + sb.append(cb.isChecked() ? TAG_CHECKED : TAG_UNCHECKED); + sb.append(" ").append(text); + } + if (i != mEditTextList.getChildCount() - 1) { + sb.append("\n"); + } + } + } + } + } + mWorkingNote.setWorkingText(sb.toString()); + } else { + // 处理普通模式的文本,保存为HTML格式以保留富文本格式 + if (mNoteEditor != null) { + CharSequence text = mNoteEditor.getText(); + if (text != null) { + String textStr = text.toString(); + // 检查文本是否包含图片占位符 + if (textStr.contains("[IMAGE]") && textStr.contains("[/IMAGE]")) { + // 包含图片占位符,直接保存为纯文本 + mWorkingNote.setWorkingText(textStr); + } else if (text instanceof Spanned) { + // 不包含图片占位符,保存为HTML格式 + String html = android.text.Html.toHtml((Spanned) text); + mWorkingNote.setWorkingText(html); + } else { + // 普通文本,直接保存 + mWorkingNote.setWorkingText(textStr); + } + } else { + mWorkingNote.setWorkingText(""); + } + } else { + mWorkingNote.setWorkingText(""); + } + } + return true; + } catch (Exception e) { + Log.e(TAG, "Error getting working text: " + e.toString()); + e.printStackTrace(); + return false; + } + } + + /** + * 更新标签显示区域 + */ + private void updateTagsDisplay() { + if (mTagsLayout == null || mWorkingNote == null) { + return; + } + + try { + // 获取标签水平滚动区域 + LinearLayout tagItemsLayout = (LinearLayout) findViewById(R.id.ll_tag_items); + if (tagItemsLayout == null) { + return; + } + + // 清空现有标签 + tagItemsLayout.removeAllViews(); + + // 获取当前笔记的标签 + String[] tags = mWorkingNote.getTags(); + if (tags == null || tags.length == 0) { + // 如果没有标签,隐藏标签显示区域 + mTagsLayout.setVisibility(View.GONE); + return; + } + + // 显示标签显示区域 + mTagsLayout.setVisibility(View.VISIBLE); + + // 在标签水平滚动区域中添加标签 + for (final String tag : tags) { + if (tag != null && !tag.isEmpty()) { + // 创建标签TextView + TextView tagView = new TextView(this); + tagView.setText(tag); + tagView.setTextSize(12); + tagView.setBackgroundResource(R.drawable.edit_green); + tagView.setPadding(12, 6, 12, 6); + + // 设置标签的边距 + LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( + LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); + params.setMargins(8, 4, 8, 4); + tagView.setLayoutParams(params); + + tagView.setClickable(true); + tagView.setTextColor(getResources().getColor(android.R.color.white)); + + // 添加点击事件,点击标签可以移除标签 + tagView.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + try { + mWorkingNote.removeTag(tag); + updateTagsDisplay(); + } catch (Exception e) { + Log.e(TAG, "Error removing tag: " + e.toString()); + e.printStackTrace(); + } + } + }); + + // 添加标签到水平滚动区域 + tagItemsLayout.addView(tagView); + } + } + } catch (Exception e) { + Log.e(TAG, "Error updating tags display: " + e.toString()); + e.printStackTrace(); + mTagsLayout.setVisibility(View.GONE); + } + } + + /** + * 应用或移除加粗/斜体样式 + */ + private void applyRichTextStyle(int style) { + int start = mNoteEditor.getSelectionStart(); + int end = mNoteEditor.getSelectionEnd(); + if (start >= end) { + return; + } + + SpannableString spannable = new SpannableString(mNoteEditor.getText()); + StyleSpan[] spans = spannable.getSpans(start, end, StyleSpan.class); + + boolean hasStyle = false; + // 检查选中区域是否已应用该样式 + for (StyleSpan span : spans) { + if (span.getStyle() == style) { + hasStyle = true; + break; + } + } + + if (hasStyle) { + // 移除样式 + for (StyleSpan span : spans) { + if (span.getStyle() == style) { + spannable.removeSpan(span); + } + } + } else { + // 添加样式 + spannable.setSpan(new StyleSpan(style), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + } + + mNoteEditor.setText(spannable); + mNoteEditor.setSelection(start, end); + } + + /** + * 应用或移除下划线样式 + */ + private void applyUnderlineStyle() { + int start = mNoteEditor.getSelectionStart(); + int end = mNoteEditor.getSelectionEnd(); + if (start >= end) { + return; + } + + SpannableString spannable = new SpannableString(mNoteEditor.getText()); + UnderlineSpan[] spans = spannable.getSpans(start, end, UnderlineSpan.class); + + if (spans.length > 0) { + // 移除下划线 + for (UnderlineSpan span : spans) { + spannable.removeSpan(span); + } + } else { + // 添加下划线 + spannable.setSpan(new UnderlineSpan(), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + } + + mNoteEditor.setText(spannable); + mNoteEditor.setSelection(start, end); + } + + /** + * 应用或移除删除线样式 + */ + private void applyStrikethroughStyle() { + int start = mNoteEditor.getSelectionStart(); + int end = mNoteEditor.getSelectionEnd(); + if (start >= end) { + return; + } + + SpannableString spannable = new SpannableString(mNoteEditor.getText()); + StrikethroughSpan[] spans = spannable.getSpans(start, end, StrikethroughSpan.class); + + if (spans.length > 0) { + // 移删除线 + for (StrikethroughSpan span : spans) { + spannable.removeSpan(span); + } + } else { + // 添加删除线 + spannable.setSpan(new StrikethroughSpan(), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + } + + mNoteEditor.setText(spannable); + mNoteEditor.setSelection(start, end); + } + + /** + * 更新字数统计 + */ + private void updateWordCount() { + if (mWordCountTextView == null || mWorkingNote == null) { + return; + } + + int wordCount = 0; + + if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { + // 清单模式:遍历所有列表项 + int childCount = mEditTextList.getChildCount(); + for (int i = 0; i < childCount; i++) { + View childView = mEditTextList.getChildAt(i); + NoteEditText editText = (NoteEditText) childView.findViewById(R.id.et_edit_text); + if (editText != null) { + CharSequence text = editText.getText(); + if (text != null) { + wordCount += text.toString().length(); + } + } + } + } else { + // 普通文本模式:直接计算编辑框内容 + if (mNoteEditor != null) { + CharSequence text = mNoteEditor.getText(); + if (text != null) { + wordCount += text.toString().length(); + } + } + } + + // 更新显示 + mWordCountTextView.setText(wordCount + "字"); + } + + private boolean saveNote() { + getWorkingText(); + // 在这里我们只返回true,因为实际的保存操作会在后台线程中执行 + // 这样可以避免主线程卡顿 + new AsyncTask() { + @Override + protected Boolean doInBackground(Void... params) { + try { + return mWorkingNote.saveNote(); + } catch (Exception e) { + e.printStackTrace(); + Log.e(TAG, "Error saving note: " + e.toString()); + return false; + } + } + + @Override + protected void onPostExecute(Boolean saved) { + 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); + } + } + }.execute(); + return true; + } + + 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 shortcutIntent = new Intent(this, NoteEditActivity.class); + shortcutIntent.setAction(Intent.ACTION_VIEW); + shortcutIntent.putExtra(Intent.EXTRA_UID, mWorkingNote.getNoteId()); + sender.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); + sender.putExtra(Intent.EXTRA_SHORTCUT_NAME, + makeShortcutIconTitle(mWorkingNote.getContent())); + sender.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, + Intent.ShortcutIconResource.fromContext(this, R.drawable.icon_app)); + sender.putExtra("duplicate", true); + sender.setAction("com.android.launcher.action.INSTALL_SHORTCUT"); + showToast(R.string.info_note_enter_desktop); + 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); + } + } + + 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; + } + + private void showToast(int resId) { + Toast.makeText(this, resId, Toast.LENGTH_SHORT).show(); + } + + private void showTableEditorDialog() { + try { + // 加载表格编辑器对话框布局 + View dialogView = LayoutInflater.from(this).inflate(R.layout.table_editor_dialog, null); + + // 获取输入框 + final EditText etRows = (EditText) dialogView.findViewById(R.id.et_rows); + final EditText etCols = (EditText) dialogView.findViewById(R.id.et_cols); + + // 获取按钮 + Button btnCancel = (Button) dialogView.findViewById(R.id.btn_cancel); + Button btnConfirm = (Button) dialogView.findViewById(R.id.btn_confirm); + + // 创建对话框 + final AlertDialog dialog = new AlertDialog.Builder(this) + .setView(dialogView) + .create(); + + // 设置取消按钮点击事件 + btnCancel.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + dialog.dismiss(); + } + }); + + // 设置确认按钮点击事件 + btnConfirm.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + try { + // 获取用户输入的行数和列数 + int rows = Integer.parseInt(etRows.getText().toString()); + int cols = Integer.parseInt(etCols.getText().toString()); + + // 验证输入 + if (rows < 1 || rows > 10 || cols < 1 || cols > 10) { + showToast(R.string.error_invalid_table_size); + return; + } + + // 生成表格HTML并插入 + String tableHtml = generateTableHtml(rows, cols); + Log.d(TAG, "Generated table HTML: " + tableHtml); + insertHtmlAtCursor(tableHtml); + Log.d(TAG, "Table HTML inserted successfully"); + + // 关闭对话框 + dialog.dismiss(); + } catch (NumberFormatException e) { + showToast(R.string.error_invalid_input); + Log.e(TAG, "Number format exception: " + e.toString()); + } catch (Exception e) { + showToast(R.string.operation_failed); + Log.e(TAG, "Error creating table: " + e.toString()); + e.printStackTrace(); + } + } + }); + + // 显示对话框 + dialog.show(); + } catch (Exception e) { + Log.e(TAG, "Error showing table editor dialog: " + e.toString()); + e.printStackTrace(); + } + } + + private String generateTableHtml(int rows, int cols) { + StringBuilder tableBuilder = new StringBuilder(); + + // 使用Markdown表格语法,这种格式更简单且易于编辑 + tableBuilder.append("| "); + for (int j = 0; j < cols; j++) { + tableBuilder.append("列").append(j + 1).append(" | "); + } + tableBuilder.append("\n"); + + tableBuilder.append("| "); + for (int j = 0; j < cols; j++) { + tableBuilder.append("--- | "); + } + tableBuilder.append("\n"); + + for (int i = 0; i < rows; i++) { + tableBuilder.append("| "); + for (int j = 0; j < cols; j++) { + tableBuilder.append(" ").append(" | "); + } + tableBuilder.append("\n"); + } + + return tableBuilder.toString(); + } + + + + private void showTagsDialog() { + try { + // 获取所有标签 + final String[] allTags = getAllTags(); + // 获取当前笔记的标签 + final String[] currentTags = mWorkingNote.getTags(); + + // 创建已选中标签的布尔数组 + boolean[] checkedItems = new boolean[allTags.length]; + if (currentTags != null) { + for (int i = 0; i < allTags.length; i++) { + for (String currentTag : currentTags) { + if (allTags[i].equals(currentTag)) { + checkedItems[i] = true; + break; + } + } + } + } + + // 创建标签选择对话框 + AlertDialog.Builder builder = new AlertDialog.Builder(this); + builder.setTitle(R.string.menu_tags); + builder.setMultiChoiceItems(allTags, checkedItems, new DialogInterface.OnMultiChoiceClickListener() { + @Override + public void onClick(DialogInterface dialog, int which, boolean isChecked) { + try { + String tagName = allTags[which]; + if (isChecked) { + // 添加标签 + mWorkingNote.addTag(tagName); + } else { + // 移除标签 + mWorkingNote.removeTag(tagName); + } + } catch (Exception e) { + e.printStackTrace(); + Log.e(TAG, "Error handling tag selection: " + e.toString()); + } + } + }); + + // 添加添加新标签的按钮 + builder.setPositiveButton("Add New Tag", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + // 显示输入新标签的对话框 + showAddNewTagDialog(); + } + }); + + // 添加清除所有标签的按钮 + builder.setNeutralButton("Clear All", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + try { + mWorkingNote.clearTags(); + } catch (Exception e) { + e.printStackTrace(); + Log.e(TAG, "Error clearing tags: " + e.toString()); + } + } + }); + + builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + // 关闭对话框后更新标签显示 + updateTagsDisplay(); + } + }); + builder.show(); + } catch (Exception e) { + e.printStackTrace(); + Log.e(TAG, "Error showing tags dialog: " + e.toString()); + showToast(R.string.error_init_failed); + } + } + + /** + * 获取所有已存在的标签 + * @return 标签名称数组 + */ + private String[] getAllTags() { + Cursor cursor = null; + try { + cursor = getContentResolver().query( + Notes.CONTENT_TAG_URI, + new String[]{Notes.TagColumns.NAME}, + null, + null, + Notes.TagColumns.NAME + " ASC" + ); + + if (cursor == null || cursor.getCount() == 0) { + return new String[0]; + } + + String[] tags = new String[cursor.getCount()]; + int i = 0; + while (cursor.moveToNext()) { + tags[i++] = cursor.getString(0); + } + return tags; + } catch (Exception e) { + e.printStackTrace(); + Log.e(TAG, "Error getting all tags: " + e.toString()); + return new String[0]; + } finally { + if (cursor != null) { + cursor.close(); + } + } + } + + /** + * 显示添加新标签的对话框 + */ + private void showAddNewTagDialog() { + AlertDialog.Builder builder = new AlertDialog.Builder(this); + builder.setTitle("Add New Tag"); + + View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_edit_text, null); + final EditText tagInput = (EditText) dialogView.findViewById(R.id.et_foler_name); + tagInput.setHint("Enter tag name"); + + builder.setView(dialogView); + + builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + String tagName = tagInput.getText().toString().trim(); + if (!TextUtils.isEmpty(tagName)) { + try { + mWorkingNote.addTag(tagName); + updateTagsDisplay(); + } catch (Exception e) { + e.printStackTrace(); + Log.e(TAG, "Error adding new tag: " + e.toString()); + showToast(R.string.operation_failed); + } + } + } + }); + + builder.setNegativeButton(android.R.string.cancel, null); + + builder.show(); + } + + /** + * 请求图片权限并启动图片选择 + */ + private void requestImagePermissionsAndPick() { + if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { + if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) { + // Android 13+ 读取媒体文件权限 + if (checkSelfPermission(android.Manifest.permission.READ_MEDIA_IMAGES) != android.content.pm.PackageManager.PERMISSION_GRANTED) { + requestPermissions(new String[]{android.Manifest.permission.READ_MEDIA_IMAGES}, REQUEST_CODE_IMAGE_PERMISSIONS); + return; + } + } else { + // Android 6-12 读取存储权限 + if (checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) != android.content.pm.PackageManager.PERMISSION_GRANTED) { + requestPermissions(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE_IMAGE_PERMISSIONS); + return; + } + } + } + // 权限已授予,启动图片选择 + pickImageFromGallery(); + } + + /** + * 从相册选择图片 + */ + private void pickImageFromGallery() { + Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); + intent.setType("image/*"); + startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE); + } + + /** + * 切换搜索框的显示/隐藏 + */ + private void toggleSearch() { + if (mSearchContainer != null) { + if (mSearchContainer.getVisibility() == View.VISIBLE) { + closeSearch(); + } else { + // 显示搜索框 + mSearchContainer.setVisibility(View.VISIBLE); + // 隐藏富文本工具栏 + if (mRichTextToolbar != null) { + mRichTextToolbar.setVisibility(View.GONE); + } + // 搜索框获取焦点 + if (mSearchEditText != null) { + mSearchEditText.requestFocus(); + // 显示软键盘 + android.view.inputmethod.InputMethodManager imm = (android.view.inputmethod.InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); + imm.showSoftInput(mSearchEditText, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT); + } + } + } + } + + /** + * 执行搜索逻辑 + */ + private void performSearch(String query) { + if (TextUtils.isEmpty(query) || mNoteEditor == null) { + // 清空搜索结果 + if (mSearchResults != null) { + mSearchResults.clear(); + } + if (mSearchResultAdapter != null) { + mSearchResultAdapter.notifyDataSetChanged(); + } + if (mSearchResultsContainer != null) { + mSearchResultsContainer.setVisibility(View.GONE); + } + return; + } + + // 获取编辑框内容 + CharSequence content = mNoteEditor.getText(); + if (content == null) { + return; + } + + String contentStr = content.toString(); + // 清空之前的搜索结果 + if (mSearchResults != null) { + mSearchResults.clear(); + } else { + mSearchResults = new ArrayList<>(); + } + + // 查找所有匹配的位置 + int index = 0; + while (index < contentStr.length()) { + int startIndex = contentStr.indexOf(query, index); + if (startIndex == -1) { + break; + } + int endIndex = startIndex + query.length(); + + // 生成搜索结果的上下文 + String context = generateSearchContext(contentStr, startIndex, endIndex); + mSearchResults.add(new SearchResult(startIndex, endIndex, context)); + + index = endIndex; + } + + // 更新搜索结果显示 + if (mSearchResultAdapter != null) { + mSearchResultAdapter.notifyDataSetChanged(); + } + + // 显示搜索结果 + if (mSearchResultsContainer != null) { + mSearchResultsContainer.setVisibility(View.VISIBLE); + } + + // 显示/隐藏无结果提示 + if (mNoSearchResultsTextView != null) { + if (mSearchResults != null && mSearchResults.size() > 0) { + mNoSearchResultsTextView.setVisibility(View.GONE); + if (mSearchResultsListView != null) { + mSearchResultsListView.setVisibility(View.VISIBLE); + } + } else { + mNoSearchResultsTextView.setVisibility(View.VISIBLE); + if (mSearchResultsListView != null) { + mSearchResultsListView.setVisibility(View.GONE); + } + } + } + } + + /** + * 生成搜索结果的上下文 + */ + private String generateSearchContext(String content, int startIndex, int endIndex) { + // 生成上下文,包含匹配文本前后的内容 + int contextStart = Math.max(0, startIndex - 20); + int contextEnd = Math.min(content.length(), endIndex + 20); + + String context = ""; + if (contextStart > 0) { + context += "..."; + } + context += content.substring(contextStart, endIndex); + if (contextEnd < content.length()) { + context += "..."; + } + + return context; + } + + /** + * 跳转到搜索结果位置 + */ + private void jumpToSearchResult(SearchResult result) { + if (mNoteEditor != null && result != null) { + // 跳转到对应位置 + mNoteEditor.setSelection(result.startIndex, result.endIndex); + + // 确保文本可见 + mNoteEditor.scrollTo(0, mNoteEditor.getLayout().getLineTop(mNoteEditor.getLayout().getLineForOffset(result.startIndex))); + + // 高亮显示匹配文本 + CharSequence text = mNoteEditor.getText(); + if (text instanceof Spannable) { + Spannable spannable = (Spannable) text; + // 清除之前的高亮 + BackgroundColorSpan[] oldSpans = spannable.getSpans(0, text.length(), BackgroundColorSpan.class); + for (BackgroundColorSpan span : oldSpans) { + spannable.removeSpan(span); + } + // 添加新的高亮 + spannable.setSpan(new BackgroundColorSpan(getResources().getColor(R.color.user_query_highlight)), + result.startIndex, result.endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + } + } + } + + /** + * 清除搜索 + */ + private void clearSearch() { + if (mSearchEditText != null) { + mSearchEditText.setText(""); + } + } + + /** + * 关闭搜索框 + */ + private void closeSearch() { + // 隐藏搜索框 + if (mSearchContainer != null) { + mSearchContainer.setVisibility(View.GONE); + } + // 隐藏搜索结果 + if (mSearchResultsContainer != null) { + mSearchResultsContainer.setVisibility(View.GONE); + } + // 显示富文本工具栏 + if (mRichTextToolbar != null) { + mRichTextToolbar.setVisibility(View.VISIBLE); + } + // 隐藏软键盘 + android.view.inputmethod.InputMethodManager imm = (android.view.inputmethod.InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); + imm.hideSoftInputFromWindow(mNoteEditor.getWindowToken(), 0); + } + + /** + * 处理选择的图片 + */ + private void handleSelectedImage(android.net.Uri imageUri) throws Exception { + if (imageUri == null) { + return; + } + + Log.d(TAG, "Handling selected image: " + imageUri.toString()); + + // 获取图片的Bitmap + android.graphics.Bitmap bitmap = getBitmapFromUri(imageUri); + if (bitmap == null) { + throw new Exception("Failed to load bitmap"); + } + + Log.d(TAG, "Bitmap loaded successfully, width: " + bitmap.getWidth() + ", height: " + bitmap.getHeight()); + + // 缩放图片,确保大小适中 + android.graphics.Bitmap scaledBitmap = scaleBitmap(bitmap, 800, 800); + + Log.d(TAG, "Bitmap scaled, width: " + scaledBitmap.getWidth() + ", height: " + scaledBitmap.getHeight()); + + // 将图片转换为Base64编码 + String base64Image = bitmapToBase64(scaledBitmap); + + if (base64Image == null || base64Image.isEmpty()) { + throw new Exception("Failed to convert bitmap to base64"); + } + + Log.d(TAG, "Base64 conversion successful, length: " + base64Image.length()); + + // 回收Bitmap资源 + bitmap.recycle(); + if (scaledBitmap != bitmap) { + scaledBitmap.recycle(); + } + + // 在光标位置插入图片 + insertImageAtCursor(base64Image); + } + + /** + * 从Uri获取Bitmap + */ + private android.graphics.Bitmap getBitmapFromUri(android.net.Uri uri) throws Exception { + android.content.ContentResolver resolver = getContentResolver(); + return android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri)); + } + + /** + * 缩放Bitmap + */ + private android.graphics.Bitmap scaleBitmap(android.graphics.Bitmap bitmap, int maxWidth, int maxHeight) { + int width = bitmap.getWidth(); + int height = bitmap.getHeight(); + + float scale = Math.min((float) maxWidth / width, (float) maxHeight / height); + if (scale >= 1) { + return bitmap; + } + + int newWidth = Math.round(width * scale); + int newHeight = Math.round(height * scale); + + return android.graphics.Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true); + } + + /** + * 将Bitmap转换为Base64编码 + */ + private String bitmapToBase64(android.graphics.Bitmap bitmap) { + java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); + try { + bitmap.compress(android.graphics.Bitmap.CompressFormat.JPEG, 80, baos); + byte[] bytes = baos.toByteArray(); + String base64 = android.util.Base64.encodeToString(bytes, android.util.Base64.NO_WRAP); + Log.d(TAG, "Bitmap converted to Base64, length: " + (base64 != null ? base64.length() : 0)); + return base64; + } catch (Exception e) { + e.printStackTrace(); + Log.e(TAG, "Error converting bitmap to base64: " + e.toString()); + return null; + } finally { + try { + baos.close(); + } catch (java.io.IOException e) { + e.printStackTrace(); + } + } + } + + /** + * 在光标位置插入图片 + */ + private void insertImageAtCursor(String base64Image) { + if (mNoteEditor == null) { + return; + } + + try { + Log.d(TAG, "Inserting image at cursor, base64 length: " + (base64Image != null ? base64Image.length() : 0)); + + // 获取当前光标位置 + int cursorPosition = mNoteEditor.getSelectionStart(); + + // 创建图片占位符文本 + String imageMarker = "[IMAGE]"; + + // 将Base64字符串转换回Bitmap + android.graphics.Bitmap bitmap = base64ToBitmap(base64Image); + if (bitmap == null) { + throw new Exception("Failed to convert base64 to bitmap"); + } + + Log.d(TAG, "Bitmap created successfully for display, width: " + bitmap.getWidth() + ", height: " + bitmap.getHeight()); + + // 创建ImageSpan + android.text.style.ImageSpan imageSpan = new android.text.style.ImageSpan(this, bitmap); + + // 创建包含图片标记的SpannableString + android.text.SpannableString spannableString = new android.text.SpannableString(imageMarker); + spannableString.setSpan(imageSpan, 0, imageMarker.length(), android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + + // 在光标位置插入图片 + android.text.SpannableStringBuilder builder = new android.text.SpannableStringBuilder(mNoteEditor.getText()); + builder.insert(cursorPosition, spannableString); + + // 同时保存原始的Base64数据,用于持久化存储 + String imagePlaceholder = "[IMAGE]" + base64Image + "[/IMAGE]"; + + // 设置文本并移动光标到插入内容之后 + mNoteEditor.setText(builder); + mNoteEditor.setSelection(cursorPosition + imageMarker.length()); + + // 保存包含图片数据的文本 + String currentText = mWorkingNote.getContent(); + String newText = currentText != null ? currentText : ""; + + // 在光标位置插入图片占位符 + if (cursorPosition > newText.length()) { + newText = newText + imagePlaceholder; + } else { + newText = newText.substring(0, cursorPosition) + imagePlaceholder + newText.substring(cursorPosition); + } + + mWorkingNote.setWorkingText(newText); + Log.d(TAG, "Image placeholder saved to working note, length: " + newText.length()); + Log.d(TAG, "Inserted image at cursor position: " + cursorPosition); + } catch (Exception e) { + e.printStackTrace(); + Log.e(TAG, "Error inserting image: " + e.toString()); + showToast(R.string.error_image_processing); + } + } + + /** + * 将Base64字符串转换为Bitmap + */ + private android.graphics.Bitmap base64ToBitmap(String base64String) { + try { + Log.d(TAG, "Converting base64 to bitmap, input length: " + (base64String != null ? base64String.length() : 0)); + + if (base64String == null || base64String.isEmpty()) { + Log.e(TAG, "Base64 string is null or empty"); + return null; + } + + byte[] decodedBytes = android.util.Base64.decode(base64String, android.util.Base64.NO_WRAP); + Log.d(TAG, "Base64 decoded successfully, byte array length: " + decodedBytes.length); + + android.graphics.Bitmap bitmap = android.graphics.BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length); + + if (bitmap == null) { + Log.e(TAG, "BitmapFactory.decodeByteArray returned null"); + // 尝试获取解码错误信息 + android.graphics.BitmapFactory.Options options = new android.graphics.BitmapFactory.Options(); + options.inJustDecodeBounds = true; + android.graphics.BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length, options); + Log.e(TAG, "Bitmap decode error: " + options.outWidth + "x" + options.outHeight + ", MimeType: " + options.outMimeType); + } else { + Log.d(TAG, "Bitmap created successfully, width: " + bitmap.getWidth() + ", height: " + bitmap.getHeight()); + } + + return bitmap; + } catch (Exception e) { + e.printStackTrace(); + Log.e(TAG, "Error converting base64 to bitmap: " + e.toString()); + return null; + } + } + + /** + * 处理包含图片占位符的文本内容 + */ + private android.text.SpannableStringBuilder processImageContent(String contentStr) { + android.text.SpannableStringBuilder builder = new android.text.SpannableStringBuilder(); + + try { + // 查找图片占位符 + int startIndex = 0; + int imageStart = contentStr.indexOf("[IMAGE]", startIndex); + + while (imageStart != -1) { + // 添加图片之前的文本 + if (imageStart > startIndex) { + String textBefore = contentStr.substring(startIndex, imageStart); + builder.append(textBefore); + } + + // 查找图片占位符结束位置 + int imageEnd = contentStr.indexOf("[/IMAGE]", imageStart); + if (imageEnd == -1) { + break; + } + + // 提取Base64图片数据 + String base64Data = contentStr.substring(imageStart + 7, imageEnd); + + // 将Base64转换为Bitmap + android.graphics.Bitmap bitmap = base64ToBitmap(base64Data); + if (bitmap != null) { + // 创建图片标记 + String imageMarker = "[IMAGE]"; + + // 创建ImageSpan + android.text.style.ImageSpan imageSpan = new android.text.style.ImageSpan(this, bitmap); + + // 创建包含图片标记的SpannableString + android.text.SpannableString spannableString = new android.text.SpannableString(imageMarker); + spannableString.setSpan(imageSpan, 0, imageMarker.length(), android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + + // 添加到builder + builder.append(spannableString); + } else { + // 图片加载失败,添加占位符文本 + builder.append("[图片加载失败]"); + } + + // 更新起始位置 + startIndex = imageEnd + 8; + imageStart = contentStr.indexOf("[IMAGE]", startIndex); + } + + // 添加剩余的文本 + if (startIndex < contentStr.length()) { + String remainingText = contentStr.substring(startIndex); + builder.append(remainingText); + } + } catch (Exception e) { + e.printStackTrace(); + Log.e(TAG, "Error processing image content: " + e.toString()); + // 处理失败时,返回原始文本 + builder.append(contentStr); + } + + return builder; + } + + /** + * 显示添加新标签的对话框 + */ + + // 搜索结果类 + private static class SearchResult { + int startIndex; + int endIndex; + String context; + + public SearchResult(int startIndex, int endIndex, String context) { + this.startIndex = startIndex; + this.endIndex = endIndex; + this.context = context; + } + } + + // 搜索结果适配器 + private class SearchResultAdapter extends ArrayAdapter { + public SearchResultAdapter(Context context, ArrayList results) { + super(context, 0, results); + } + + @Override + public View getView(int position, View convertView, ViewGroup parent) { + SearchResult result = getItem(position); + if (convertView == null) { + convertView = LayoutInflater.from(getContext()).inflate(R.layout.search_result_item, parent, false); + } + + TextView contextTextView = convertView.findViewById(R.id.tv_search_result_context); + contextTextView.setText(result.context); + + return convertView; + } + } +} \ No newline at end of file diff --git a/src/ui/NoteEditText.java b/src/ui/NoteEditText.java new file mode 100644 index 0000000..bd1cf24 --- /dev/null +++ b/src/ui/NoteEditText.java @@ -0,0 +1,411 @@ +/* + * 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.SpannableStringBuilder; +import android.text.Spanned; +import android.text.TextUtils; +import android.text.style.StrikethroughSpan; +import android.text.style.StyleSpan; +import android.text.style.URLSpan; +import android.text.style.UnderlineSpan; +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 androidx.appcompat.widget.AppCompatEditText; + +import net.micode.notes.R; + +import java.util.HashMap; +import java.util.Map; + +public class NoteEditText extends AppCompatEditText { + private static final String TAG = "NoteEditText"; + 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 sSchemaActionResMap = new HashMap(); + 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); + } + + /** + * Call by the {@link NoteEditActivity} to delete or add edit text + */ + public interface OnTextViewChangeListener { + /** + * Delete current edit text when {@link KeyEvent#KEYCODE_DEL} happens + * and the text is null + */ + void onEditTextDelete(int index, String text); + + /** + * Add edit text after current edit text when {@link KeyEvent#KEYCODE_ENTER} + * happen + */ + void onEditTextEnter(int index, String text); + + /** + * Hide or show item option when text change + */ + void onTextChange(int index, boolean hasText); + } + + private OnTextViewChangeListener mOnTextViewChangeListener; + + public NoteEditText(Context context) { + super(context, null); + mIndex = 0; + } + + public void setIndex(int index) { + mIndex = index; + } + + public void setOnTextViewChangeListener(OnTextViewChangeListener listener) { + mOnTextViewChangeListener = listener; + } + + public NoteEditText(Context context, AttributeSet attrs) { + super(context, attrs, android.R.attr.editTextStyle); + } + + public NoteEditText(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + // TODO Auto-generated constructor stub + } + + @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(); + y -= getTotalPaddingTop(); + x += getScrollX(); + y += getScrollY(); + + Layout layout = getLayout(); + int line = layout.getLineForVertical(y); + int off = layout.getOffsetForHorizontal(line, x); + Selection.setSelection(getText(), off); + break; + } + + return super.onTouchEvent(event); + } + + @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); + } + + @Override + public boolean onKeyUp(int keyCode, KeyEvent event) { + switch(keyCode) { + case KeyEvent.KEYCODE_DEL: + if (mOnTextViewChangeListener != null) { + if (0 == mSelectionStartBeforeDelete && mIndex != 0) { + mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString()); + return true; + } + } else { + Log.d(TAG, "OnTextViewChangeListener was not seted"); + } + 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 seted"); + } + break; + default: + break; + } + return super.onKeyUp(keyCode, event); + } + + @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); + } + + @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); + + final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class); + if (urls.length == 1) { + int defaultResId = 0; + 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; + } + + menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener( + new OnMenuItemClickListener() { + public boolean onMenuItemClick(MenuItem item) { + // goto a new intent + urls[0].onClick(NoteEditText.this); + return true; + } + }); + } + } + super.onCreateContextMenu(menu); + } + + /** + * 检查选中文本是否具有特定样式 + */ + public boolean hasStyle(int style) { + if (!(getText() instanceof Spanned)) { + return false; + } + + int selStart = getSelectionStart(); + int selEnd = getSelectionEnd(); + if (selStart >= selEnd) { + return false; + } + + Spanned spanned = (Spanned) getText(); + StyleSpan[] spans = spanned.getSpans(selStart, selEnd, StyleSpan.class); + + for (StyleSpan span : spans) { + if (span.getStyle() == style) { + return true; + } + } + return false; + } + + /** + * 检查选中文本是否具有下划线样式 + */ + public boolean hasUnderline() { + if (!(getText() instanceof Spanned)) { + return false; + } + + int selStart = getSelectionStart(); + int selEnd = getSelectionEnd(); + if (selStart >= selEnd) { + return false; + } + + Spanned spanned = (Spanned) getText(); + UnderlineSpan[] spans = spanned.getSpans(selStart, selEnd, UnderlineSpan.class); + return spans.length > 0; + } + + /** + * 检查选中文本是否具有删除线样式 + */ + public boolean hasStrikethrough() { + if (!(getText() instanceof Spanned)) { + return false; + } + + int selStart = getSelectionStart(); + int selEnd = getSelectionEnd(); + if (selStart >= selEnd) { + return false; + } + + Spanned spanned = (Spanned) getText(); + StrikethroughSpan[] spans = spanned.getSpans(selStart, selEnd, StrikethroughSpan.class); + return spans.length > 0; + } + + /** + * 应用样式到选中文本 + */ + public void applyStyle(int style) { + if (!(getText() instanceof Spanned)) { + return; + } + + int selStart = getSelectionStart(); + int selEnd = getSelectionEnd(); + if (selStart >= selEnd) { + return; + } + + Spanned spanned = (Spanned) getText(); + StyleSpan[] spans = spanned.getSpans(selStart, selEnd, StyleSpan.class); + + boolean hasStyle = false; + for (StyleSpan span : spans) { + if (span.getStyle() == style) { + hasStyle = true; + break; + } + } + + if (!hasStyle) { + SpannableStringBuilder builder = new SpannableStringBuilder(spanned); + builder.setSpan(new StyleSpan(style), selStart, selEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + setText(builder); + setSelection(selStart, selEnd); + } + } + + /** + * 移除选中文本的样式 + */ + public void removeStyle(int style) { + if (!(getText() instanceof Spanned)) { + return; + } + + int selStart = getSelectionStart(); + int selEnd = getSelectionEnd(); + if (selStart >= selEnd) { + return; + } + + Spanned spanned = (Spanned) getText(); + StyleSpan[] spans = spanned.getSpans(selStart, selEnd, StyleSpan.class); + + SpannableStringBuilder builder = new SpannableStringBuilder(spanned); + for (StyleSpan span : spans) { + if (span.getStyle() == style) { + builder.removeSpan(span); + } + } + + setText(builder); + setSelection(selStart, selEnd); + } + + /** + * 应用或移除下划线样式 + */ + public void toggleUnderline() { + if (!(getText() instanceof Spanned)) { + return; + } + + int selStart = getSelectionStart(); + int selEnd = getSelectionEnd(); + if (selStart >= selEnd) { + return; + } + + Spanned spanned = (Spanned) getText(); + UnderlineSpan[] spans = spanned.getSpans(selStart, selEnd, UnderlineSpan.class); + + SpannableStringBuilder builder = new SpannableStringBuilder(spanned); + + if (spans.length > 0) { + // 移除下划线 + for (UnderlineSpan span : spans) { + builder.removeSpan(span); + } + } else { + // 添加下划线 + builder.setSpan(new UnderlineSpan(), selStart, selEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + } + + setText(builder); + setSelection(selStart, selEnd); + } + + /** + * 应用或移除删除线样式 + */ + public void toggleStrikethrough() { + if (!(getText() instanceof Spanned)) { + return; + } + + int selStart = getSelectionStart(); + int selEnd = getSelectionEnd(); + if (selStart >= selEnd) { + return; + } + + Spanned spanned = (Spanned) getText(); + StrikethroughSpan[] spans = spanned.getSpans(selStart, selEnd, StrikethroughSpan.class); + + SpannableStringBuilder builder = new SpannableStringBuilder(spanned); + + if (spans.length > 0) { + // 移除删除线 + for (StrikethroughSpan span : spans) { + builder.removeSpan(span); + } + } else { + // 添加删除线 + builder.setSpan(new StrikethroughSpan(), selStart, selEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + } + + setText(builder); + setSelection(selStart, selEnd); + } +} diff --git a/src/ui/NoteItemData.java b/src/ui/NoteItemData.java new file mode 100644 index 0000000..385ccbf --- /dev/null +++ b/src/ui/NoteItemData.java @@ -0,0 +1,293 @@ +/* + * 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; + + +public class NoteItemData { + static final String [] PROJECTION = new String [] { + NoteColumns.ID, + NoteColumns.ALERTED_DATE, + NoteColumns.BG_COLOR_ID, + NoteColumns.CREATED_DATE, + NoteColumns.HAS_ATTACHMENT, + NoteColumns.MODIFIED_DATE, + NoteColumns.NOTES_COUNT, + NoteColumns.PARENT_ID, + NoteColumns.SNIPPET, + NoteColumns.TYPE, + NoteColumns.WIDGET_ID, + NoteColumns.WIDGET_TYPE, + NoteColumns.PINNED // 添加置顶字段 + }; + + 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 static final int PINNED_COLUMN = 12; // 新增置顶字段索引 + + private long mId; + private long mAlertDate; + private int mBgColorId; + private long mCreatedDate; + private boolean mHasAttachment; + private long mModifiedDate; + private int mNotesCount; + private long mParentId; + private String mSnippet; + private int mType; + private int mWidgetId; + private int mWidgetType; + private String mName; + private String mPhoneNumber; + private int mPinned; // 新增置顶状态字段 + + private boolean mIsLastItem; + private boolean mIsFirstItem; + private boolean mIsOnlyOneItem; + private boolean mIsOneNoteFollowingFolder; + private boolean mIsMultiNotesFollowingFolder; + + public NoteItemData(Context context, Cursor cursor) { + try { + 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) ? true : false; + 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); + // 加载置顶状态,添加异常处理 + try { + mPinned = cursor.getInt(PINNED_COLUMN); + } catch (Exception e) { + mPinned = 0; // 默认未置顶 + } + + mPhoneNumber = ""; + if (mParentId == Notes.ID_CALL_RECORD_FOLDER) { + try { + mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId); + if (!TextUtils.isEmpty(mPhoneNumber)) { + mName = Contact.getContact(context, mPhoneNumber); + if (mName == null) { + mName = mPhoneNumber; + } + } + } catch (Exception e) { + mPhoneNumber = ""; + mName = ""; + } + } + + if (mName == null) { + mName = ""; + } + checkPostion(cursor); + } catch (Exception e) { + e.printStackTrace(); + // 初始化默认值 + mId = 0; + mAlertDate = 0; + mBgColorId = 0; + mCreatedDate = 0; + mHasAttachment = false; + mModifiedDate = 0; + mNotesCount = 0; + mParentId = 0; + mSnippet = ""; + mType = 0; + mWidgetId = 0; + mWidgetType = 0; + mPinned = 0; + mPhoneNumber = ""; + mName = ""; + } + } + + private void checkPostion(Cursor cursor) { + try { + mIsLastItem = cursor.isLast() ? true : false; + mIsFirstItem = cursor.isFirst() ? true : false; + mIsOnlyOneItem = (cursor.getCount() == 1); + mIsMultiNotesFollowingFolder = false; + mIsOneNoteFollowingFolder = false; + + if (mType == Notes.TYPE_NOTE && !mIsFirstItem) { + int position = cursor.getPosition(); + if (cursor.moveToPrevious()) { + try { + 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; + } + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + cursor.moveToNext(); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + // 初始化默认值 + mIsLastItem = false; + mIsFirstItem = false; + mIsOnlyOneItem = false; + mIsMultiNotesFollowingFolder = false; + mIsOneNoteFollowingFolder = false; + } + } + + /** + * 检查笔记是否已置顶 + * + * @return true-已置顶,false-未置顶 + */ + public boolean isPinned() { + return mPinned == 1; + } + + /** + * 获取笔记的置顶状态 + * + * @return 置顶状态:0-未置顶,1-已置顶 + */ + public int getPinned() { + return mPinned; + } + + 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)); + } + + public static int getNoteType(Cursor cursor) { + return cursor.getInt(TYPE_COLUMN); + } +} \ No newline at end of file diff --git a/src/ui/NotesListActivity.java b/src/ui/NotesListActivity.java new file mode 100644 index 0000000..2747cd3 --- /dev/null +++ b/src/ui/NotesListActivity.java @@ -0,0 +1,1690 @@ +/* + * 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. + */ +/* + * 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 androidx.appcompat.app.AppCompatActivity; +import android.app.AlertDialog; +import android.app.Dialog; +import android.appwidget.AppWidgetManager; +import android.content.AsyncQueryHandler; +import android.content.ContentResolver; +import android.content.ContentValues; +import android.content.Context; +import android.content.DialogInterface; +import android.app.SearchManager; +import android.content.ContentUris; +import android.content.Intent; +import android.content.SharedPreferences; +import android.database.Cursor; +import android.net.Uri; +import android.os.AsyncTask; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.text.Editable; +import android.text.TextUtils; +import android.text.TextWatcher; +import android.util.Log; +import android.view.ActionMode; +import android.view.ContextMenu; +import android.view.ContextMenu.ContextMenuInfo; +import android.view.Display; +import android.view.HapticFeedbackConstants; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuItem; +import android.view.MenuItem.OnMenuItemClickListener; +import android.view.MotionEvent; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.View.OnCreateContextMenuListener; +import android.view.View.OnTouchListener; +import android.view.inputmethod.InputMethodManager; +import android.widget.AdapterView; +import android.widget.AdapterView.OnItemClickListener; +import android.widget.AdapterView.OnItemLongClickListener; +import android.widget.Button; +import android.widget.EditText; +import android.widget.ListView; +import android.widget.PopupMenu; +import android.widget.TextView; +import android.widget.Toast; +import com.google.android.material.floatingactionbutton.FloatingActionButton; + +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; +import net.micode.notes.model.WorkingNote; +import net.micode.notes.tool.BackupUtils; +import net.micode.notes.tool.DataUtils; +import net.micode.notes.tool.ResourceParser; +import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute; +import net.micode.notes.widget.NoteWidgetProvider_2x; +import net.micode.notes.widget.NoteWidgetProvider_4x; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.HashSet; +import java.lang.ref.WeakReference; + +public class NotesListActivity extends AppCompatActivity implements OnClickListener, OnItemLongClickListener { + private static final int FOLDER_NOTE_LIST_QUERY_TOKEN = 0; + + private static final int FOLDER_LIST_QUERY_TOKEN = 1; + + 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; + + // 新增:置顶相关菜单项 + private static final int MENU_NOTE_PIN = 3; + private static final int MENU_NOTE_UNPIN = 4; + + private static final String PREFERENCE_ADD_INTRODUCTION = "net.micode.notes.introduction"; + + private enum ListEditState { + NOTE_LIST, SUB_FOLDER, CALL_RECORD_FOLDER + }; + + private ListEditState mState = ListEditState.NOTE_LIST; + + private BackgroundQueryHandler mBackgroundQueryHandler; + + private NotesListAdapter mNotesListAdapter; + + private ListView mNotesListView; + + private FloatingActionButton mAddNewNote; + private FloatingActionButton mMenuButton; + + 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"; + + public static final int NOTES_LISTVIEW_SCROLL_RATE = 30; + + private NoteItemData mFocusNoteDataItem; + + // 搜索相关成员变量 + private boolean mIsSearchMode = false; + private String mCurrentSearchQuery = null; + + // 修改查询排序,添加置顶排序 + 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 static final String SORT_ORDER = NoteColumns.PINNED + " DESC, " + + NoteColumns.MODIFIED_DATE + " DESC"; + + // 搜索条件 + private static final String SEARCH_SELECTION = "(" + NoteColumns.SNIPPET + " LIKE ?)" + + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLDER + + " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE; + + private final static int REQUEST_CODE_OPEN_NODE = 102; + private final static int REQUEST_CODE_NEW_NODE = 103; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + // 检查密码锁 + if (!checkPasswordLock()) { + // 如果密码锁检查未通过,直接返回,不继续初始化 + // 密码验证成功后会调用initAfterPasswordVerification方法进行初始化 + return; + } + + // 密码验证通过,正常初始化UI和数据 + setContentView(R.layout.note_list); + + // 确保ActionBar正确初始化,这对于菜单按钮显示至关重要 + if (getSupportActionBar() != null) { + getSupportActionBar().setDisplayHomeAsUpEnabled(false); + getSupportActionBar().setDisplayShowHomeEnabled(true); + // 确保显示选项菜单按钮 + getSupportActionBar().setDisplayShowTitleEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(false); + getSupportActionBar().setHomeButtonEnabled(true); + // 对于Material3主题,需要显式启用选项菜单 + getSupportActionBar().setDisplayShowCustomEnabled(false); + } + + initResources(); + + /** + * Insert an introduction when user firstly use this application + */ + setAppInfoFromRawRes(); + + // 处理搜索意图 + handleIntent(getIntent()); + + // 强制刷新菜单 + invalidateOptionsMenu(); + + // 显式调用onCreateOptionsMenu和onPrepareOptionsMenu + openOptionsMenu(); + } + + /** + * 检查密码锁 + * @return 如果密码验证通过或密码锁未启用,返回true;否则返回false + */ + private boolean checkPasswordLock() { + // 检查密码锁是否启用 + if (PasswordLockActivity.isLockEnabled(this)) { + // 检查是否已经验证过密码 + boolean isVerified = getIntent().getBooleanExtra("PASSWORD_VERIFIED", false); + if (!isVerified) { + // 跳转到密码验证界面 + Intent intent = new Intent(this, PasswordLockActivity.class); + startActivityForResult(intent, 0); + // 返回false,表示需要等待密码验证结果 + return false; + } + } + // 返回true,表示密码验证通过或密码锁未启用 + return true; + } + + @Override + protected void onNewIntent(Intent intent) { + super.onNewIntent(intent); + // 处理新的搜索意图 + handleIntent(intent); + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + if (requestCode == 0) { + // 处理密码验证结果 + if (resultCode != RESULT_OK) { + // 密码验证失败,退出应用 + finish(); + } else { + // 密码验证成功,标记为已验证 + Intent intent = getIntent(); + intent.putExtra("PASSWORD_VERIFIED", true); + setIntent(intent); + // 直接初始化UI和数据,而不是重新创建整个Activity + initAfterPasswordVerification(); + } + } else if (resultCode == RESULT_OK + && (requestCode == REQUEST_CODE_OPEN_NODE || requestCode == REQUEST_CODE_NEW_NODE)) { + mNotesListAdapter.changeCursor(null); + } else { + super.onActivityResult(requestCode, resultCode, data); + } + } + + /** + * 密码验证成功后初始化UI和数据 + */ + private void initAfterPasswordVerification() { + try { + // 先设置布局和初始化资源,这些操作应该在主线程中执行 + setContentView(R.layout.note_list); + + // 确保ActionBar正确初始化,这对于菜单按钮显示至关重要 + if (getSupportActionBar() != null) { + getSupportActionBar().setDisplayHomeAsUpEnabled(false); + getSupportActionBar().setDisplayShowHomeEnabled(true); + // 确保显示选项菜单按钮 + getSupportActionBar().setDisplayShowTitleEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(false); + getSupportActionBar().setHomeButtonEnabled(true); + } + + initResources(); + + // 确保新便签按钮可见 + if (mAddNewNote != null) { + mAddNewNote.setVisibility(View.VISIBLE); + } + + // 处理搜索意图,这也应该在主线程中执行 + handleIntent(getIntent()); + + // 强制刷新菜单 + invalidateOptionsMenu(); + + // 在后台线程中执行耗时操作,避免主线程卡顿 + new AsyncTask() { + @Override + protected Void doInBackground(Void... params) { + // 插入介绍笔记,这是耗时操作 + setAppInfoFromRawRes(); + return null; + } + }.execute(); + } catch (Exception e) { + e.printStackTrace(); + Log.e(TAG, "Init after password verification error: " + e.toString()); + // 显示错误提示 + Toast.makeText(this, R.string.error_init_failed, Toast.LENGTH_SHORT).show(); + // 确保应用不会崩溃 + finish(); + } + } + + private void setAppInfoFromRawRes() { + try { + SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); + if (!sp.getBoolean(PREFERENCE_ADD_INTRODUCTION, false)) { + StringBuilder sb = new StringBuilder(); + InputStream in = null; + try { + in = getResources().openRawResource(R.raw.introduction); + if (in != null) { + InputStreamReader isr = new InputStreamReader(in); + BufferedReader br = new BufferedReader(isr); + char [] buf = new char[1024]; + int len = 0; + while ((len = br.read(buf)) > 0) { + sb.append(buf, 0, len); + } + } else { + Log.e(TAG, "Read introduction file error"); + return; + } + } catch (IOException e) { + e.printStackTrace(); + return; + } finally { + if(in != null) { + try { + in.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + WorkingNote note = WorkingNote.createEmptyNote(this, Notes.ID_ROOT_FOLDER, + AppWidgetManager.INVALID_APPWIDGET_ID, Notes.TYPE_WIDGET_INVALIDE, + ResourceParser.RED); + note.setWorkingText(sb.toString()); + if (note.saveNote()) { + sp.edit().putBoolean(PREFERENCE_ADD_INTRODUCTION, true).commit(); + } else { + Log.e(TAG, "Save introduction note error"); + return; + } + } + } catch (Exception e) { + e.printStackTrace(); + Log.e(TAG, "Set app info from raw res error: " + e.toString()); + } + } + + @Override + protected void onStart() { + super.onStart(); + // 只有当mBackgroundQueryHandler初始化后才调用startAsyncNotesListQuery() + if (mBackgroundQueryHandler != null) { + startAsyncNotesListQuery(); + } + } + + private void initResources() { + // 先初始化mState变量,确保它不会为null + mState = ListEditState.NOTE_LIST; + + try { + mContentResolver = this.getContentResolver(); + mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver(), this); + mCurrentFolderId = Notes.ID_ROOT_FOLDER; + mNotesListView = (ListView) findViewById(R.id.notes_list); + if (mNotesListView != null) { + Log.d(TAG, "mNotesListView is not null"); + try { + View footer = LayoutInflater.from(this).inflate(R.layout.note_list_footer, null); + if (footer != null) { + mNotesListView.addFooterView(footer, null, false); + } + } catch (Exception e) { + e.printStackTrace(); + } + // 确保设置点击监听器 + mNotesListView.setOnItemClickListener(new OnListItemClickListener()); + Log.d(TAG, "Set OnItemClickListener"); + mNotesListView.setOnItemLongClickListener(this); + Log.d(TAG, "Set OnItemLongClickListener"); + mNotesListAdapter = new NotesListAdapter(this); + mNotesListView.setAdapter(mNotesListAdapter); + Log.d(TAG, "Set adapter"); + } else { + Log.e(TAG, "mNotesListView is null"); + } + mAddNewNote = (FloatingActionButton) findViewById(R.id.btn_new_note); + if (mAddNewNote != null) { + mAddNewNote.setOnClickListener(this); + mAddNewNote.setOnTouchListener(new NewNoteOnTouchListener()); + // 确保按钮可见 + mAddNewNote.setVisibility(View.VISIBLE); + } + + // 初始化菜单按钮 + mMenuButton = (FloatingActionButton) findViewById(R.id.btn_menu); + if (mMenuButton != null) { + mMenuButton.setOnClickListener(this); + // 确保按钮可见 + mMenuButton.setVisibility(View.VISIBLE); + } + mDispatch = false; + mDispatchY = 0; + mOriginY = 0; + mTitleBar = (TextView) findViewById(R.id.tv_title_bar); + mModeCallBack = new ModeCallback(); + } catch (Exception e) { + e.printStackTrace(); + Log.e(TAG, "Init resources error: " + e.toString()); + // 确保mState变量在异常情况下也被初始化 + mState = ListEditState.NOTE_LIST; + // 尝试重新初始化所有组件 + try { + mContentResolver = this.getContentResolver(); + mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver(), this); + mCurrentFolderId = Notes.ID_ROOT_FOLDER; + mNotesListView = (ListView) findViewById(R.id.notes_list); + if (mNotesListView != null) { + mNotesListView.setOnItemClickListener(new OnListItemClickListener()); + mNotesListView.setOnItemLongClickListener(this); + mNotesListAdapter = new NotesListAdapter(this); + mNotesListView.setAdapter(mNotesListAdapter); + } + mAddNewNote = (FloatingActionButton) findViewById(R.id.btn_new_note); + if (mAddNewNote != null) { + mAddNewNote.setOnClickListener(this); + mAddNewNote.setOnTouchListener(new NewNoteOnTouchListener()); + mAddNewNote.setVisibility(View.VISIBLE); + } + mMenuButton = (FloatingActionButton) findViewById(R.id.btn_menu); + if (mMenuButton != null) { + mMenuButton.setOnClickListener(this); + mMenuButton.setVisibility(View.VISIBLE); + } + mDispatch = false; + mDispatchY = 0; + mOriginY = 0; + mTitleBar = (TextView) findViewById(R.id.tv_title_bar); + mModeCallBack = new ModeCallback(); + } catch (Exception ex) { + ex.printStackTrace(); + Log.e(TAG, "Error reinitializing resources: " + ex.toString()); + } + } + } + + private class ModeCallback implements ListView.MultiChoiceModeListener, OnMenuItemClickListener { + private DropdownMenu mDropDownMenu; + private ActionMode mActionMode; + private MenuItem mMoveMenu; + private MenuItem mPinMenu; // 新增:置顶菜单项 + private MenuItem mUnpinMenu; // 新增:取消置顶菜单项 + + public boolean onCreateActionMode(ActionMode mode, Menu menu) { + try { + getMenuInflater().inflate(R.menu.note_list_options, menu); + menu.findItem(R.id.delete).setOnMenuItemClickListener(this); + mMoveMenu = menu.findItem(R.id.move); + // 新增:置顶和取消置顶菜单项 + mPinMenu = menu.findItem(R.id.menu_pin); + mUnpinMenu = menu.findItem(R.id.menu_unpin); + + // 检查mFocusNoteDataItem是否为null + if (mFocusNoteDataItem == null || DataUtils.getUserFolderCount(mContentResolver) == 0) { + mMoveMenu.setVisible(false); + } else if (mFocusNoteDataItem.getParentId() == Notes.ID_CALL_RECORD_FOLDER) { + mMoveMenu.setVisible(false); + } else { + mMoveMenu.setVisible(true); + mMoveMenu.setOnMenuItemClickListener(this); + } + + // 设置置顶菜单项的可见性和点击监听 + updatePinMenuVisibility(); + if (mPinMenu != null) { + mPinMenu.setOnMenuItemClickListener(this); + } + if (mUnpinMenu != null) { + mUnpinMenu.setOnMenuItemClickListener(this); + } + + mActionMode = mode; + mNotesListAdapter.setChoiceMode(true); + mNotesListView.setLongClickable(false); + if (mAddNewNote != null) { + mAddNewNote.setVisibility(View.GONE); + } + + View customView = LayoutInflater.from(NotesListActivity.this).inflate( + R.layout.note_list_dropdown_menu, null); + if (customView != null) { + mode.setCustomView(customView); + Button selectionMenu = (Button) customView.findViewById(R.id.selection_menu); + if (selectionMenu != null) { + mDropDownMenu = new DropdownMenu(NotesListActivity.this, + selectionMenu, + R.menu.note_list_dropdown); + mDropDownMenu.setOnDropdownMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){ + public boolean onMenuItemClick(MenuItem item) { + try { + mNotesListAdapter.selectAll(!mNotesListAdapter.isAllSelected()); + updateMenu(); + } catch (Exception e) { + e.printStackTrace(); + Log.e(TAG, "Error selecting all items: " + e.toString()); + } + return true; + } + + }); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + Log.e(TAG, "Error creating action mode: " + e.toString()); + return false; + } + } + + /** + * 更新置顶菜单项的可见性 + */ + private void updatePinMenuVisibility() { + try { + if (mPinMenu != null && mUnpinMenu != null && mNotesListAdapter != null) { + boolean hasPinned = mNotesListAdapter.getSelectedPinnedCount() > 0; + boolean hasUnpinned = mNotesListAdapter.getSelectedCount() - mNotesListAdapter.getSelectedPinnedCount() > 0; + + mPinMenu.setVisible(hasUnpinned); + mUnpinMenu.setVisible(hasPinned); + } + } catch (Exception e) { + e.printStackTrace(); + Log.e(TAG, "Error updating pin menu visibility: " + e.toString()); + } + } + + private void updateMenu() { + try { + if (mNotesListAdapter != null) { + int selectedCount = mNotesListAdapter.getSelectedCount(); + // Update dropdown menu + if (mDropDownMenu != null) { + String format = getResources().getString(R.string.menu_select_title, selectedCount); + mDropDownMenu.setTitle(format); + MenuItem item = mDropDownMenu.findItem(R.id.action_select_all); + if (item != null) { + if (mNotesListAdapter.isAllSelected()) { + item.setChecked(true); + item.setTitle(R.string.menu_deselect_all); + } else { + item.setChecked(false); + item.setTitle(R.string.menu_select_all); + } + } + } + // 更新置顶菜单可见性 + updatePinMenuVisibility(); + } + } catch (Exception e) { + e.printStackTrace(); + Log.e(TAG, "Error updating menu: " + e.toString()); + } + } + + public boolean onPrepareActionMode(ActionMode mode, Menu menu) { + // TODO Auto-generated method stub + return false; + } + + public boolean onActionItemClicked(ActionMode mode, MenuItem item) { + // TODO Auto-generated method stub + return false; + } + + public void onDestroyActionMode(ActionMode mode) { + mNotesListAdapter.setChoiceMode(false); + mNotesListView.setLongClickable(true); + mAddNewNote.setVisibility(View.VISIBLE); + } + + public void finishActionMode() { + mActionMode.finish(); + } + + public void onItemCheckedStateChanged(ActionMode mode, int position, long id, + boolean checked) { + mNotesListAdapter.setCheckedItem(position, checked); + updateMenu(); + } + + public boolean onMenuItemClick(MenuItem item) { + try { + if (mNotesListAdapter == null) { + Toast.makeText(NotesListActivity.this, getString(R.string.menu_select_none), + Toast.LENGTH_SHORT).show(); + return true; + } + + if (mNotesListAdapter.getSelectedCount() == 0) { + Toast.makeText(NotesListActivity.this, getString(R.string.menu_select_none), + Toast.LENGTH_SHORT).show(); + return true; + } + + int itemId = item.getItemId(); + if (itemId == R.id.delete) { + AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.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_notes, + mNotesListAdapter.getSelectedCount())); + builder.setPositiveButton(android.R.string.ok, + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, + int which) { + batchDelete(); + } + }); + builder.setNegativeButton(android.R.string.cancel, null); + builder.show(); + } else if (itemId == R.id.move) { + startQueryDestinationFolders(); + } else if (itemId == R.id.menu_pin) { + batchSetPinned(true); + } else if (itemId == R.id.menu_unpin) { + batchSetPinned(false); + } else { + return false; + } + return true; + } catch (Exception e) { + e.printStackTrace(); + Log.e(TAG, "Error handling menu item click: " + e.toString()); + Toast.makeText(NotesListActivity.this, getString(R.string.operation_failed), + Toast.LENGTH_SHORT).show(); + return false; + } + } + } + + /** + * 批量设置置顶状态 + * + * @param pinned true-置顶,false-取消置顶 + */ + private void batchSetPinned(boolean pinned) { + HashSet selectedIds = mNotesListAdapter.getSelectedItemIds(); + if (selectedIds.isEmpty()) { + Toast.makeText(this, getString(R.string.menu_select_none), Toast.LENGTH_SHORT).show(); + return; + } + + // 更新数据库中的置顶状态 + ContentValues values = new ContentValues(); + values.put(NoteColumns.PINNED, pinned ? 1 : 0); + values.put(NoteColumns.LOCAL_MODIFIED, 1); + + String where = NoteColumns.ID + " IN (" + makePlaceholders(selectedIds.size()) + ")"; + String[] whereArgs = new String[selectedIds.size()]; + int i = 0; + for (Long id : selectedIds) { + whereArgs[i++] = String.valueOf(id); + } + + int updatedCount = mContentResolver.update(Notes.CONTENT_NOTE_URI, values, where, whereArgs); + + if (updatedCount > 0) { + String message = pinned ? getString(R.string.notes_pinned_success, updatedCount) + : getString(R.string.notes_unpinned_success, updatedCount); + Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); + + // 刷新列表 + startAsyncNotesListQuery(); + mModeCallBack.finishActionMode(); + } else { + Toast.makeText(this, R.string.operation_failed, Toast.LENGTH_SHORT).show(); + } + } + + /** + * 生成SQL占位符 + */ + private String makePlaceholders(int len) { + if (len < 1) { + throw new RuntimeException("No placeholders"); + } else { + StringBuilder sb = new StringBuilder(len * 2 - 1); + sb.append("?"); + for (int i = 1; i < len; i++) { + sb.append(",?"); + } + return sb.toString(); + } + } + + private class NewNoteOnTouchListener implements OnTouchListener { + + public boolean onTouch(View v, MotionEvent event) { + switch (event.getAction()) { + case MotionEvent.ACTION_DOWN: { + Display display = getWindowManager().getDefaultDisplay(); + int screenHeight = display.getHeight(); + int newNoteViewHeight = mAddNewNote.getHeight(); + int start = screenHeight - newNoteViewHeight; + int eventY = start + (int) event.getY(); + /** + * Minus TitleBar's height + */ + if (mState == ListEditState.SUB_FOLDER) { + eventY -= mTitleBar.getHeight(); + start -= mTitleBar.getHeight(); + } + /** + * HACKME:When click the transparent part of "New Note" button, dispatch + * the event to the list view behind this button. The transparent part of + * "New Note" button could be expressed by formula y=-0.12x+94(Unit:pixel) + * and the line top of the button. The coordinate based on left of the "New + * Note" button. The 94 represents maximum height of the transparent part. + * Notice that, if the background of the button changes, the formula should + * also change. This is very bad, just for the UI designer's strong requirement. + */ + if (event.getY() < (event.getX() * (-0.12) + 94)) { + View view = mNotesListView.getChildAt(mNotesListView.getChildCount() - 1 + - mNotesListView.getFooterViewsCount()); + if (view != null && view.getBottom() > start + && (view.getTop() < (start + 94))) { + mOriginY = (int) event.getY(); + mDispatchY = eventY; + event.setLocation(event.getX(), mDispatchY); + mDispatch = true; + return mNotesListView.dispatchTouchEvent(event); + } + } + // 对于非透明部分的点击,返回false,让系统处理后续的事件 + // 这样点击监听器才能被触发 + return false; + } + case MotionEvent.ACTION_MOVE: { + if (mDispatch) { + mDispatchY += (int) event.getY() - mOriginY; + event.setLocation(event.getX(), mDispatchY); + return mNotesListView.dispatchTouchEvent(event); + } + break; + } + default: { + if (mDispatch) { + event.setLocation(event.getX(), mDispatchY); + mDispatch = false; + return mNotesListView.dispatchTouchEvent(event); + } + break; + } + } + return false; + } + + }; + + /** + * 处理搜索意图和搜索建议点击事件 + */ + private void handleIntent(Intent intent) { + if (Intent.ACTION_SEARCH.equals(intent.getAction())) { + // 处理搜索请求 + String query = intent.getStringExtra(SearchManager.QUERY); + if (query != null && !query.isEmpty()) { + mCurrentSearchQuery = query; + mIsSearchMode = true; + // 更新标题为搜索结果 + mTitleBar.setText(getString(R.string.search_results, query)); + mTitleBar.setVisibility(View.VISIBLE); + // 执行搜索查询 + startSearchQuery(query); + } + } else if (Intent.ACTION_VIEW.equals(intent.getAction())) { + // 处理搜索建议点击事件 + try { + // 从intent中获取笔记ID + long noteId = intent.getLongExtra(SearchManager.EXTRA_DATA_KEY, -1); + if (noteId == -1) { + // 尝试从数据URI中获取ID + Uri data = intent.getData(); + if (data != null) { + noteId = ContentUris.parseId(data); + } + } + if (noteId > 0) { + // 打开对应的笔记 + openNoteById(noteId); + } + } catch (Exception e) { + Log.e(TAG, "Error handling ACTION_VIEW intent: " + e.toString()); + } + } else { + // 退出搜索模式 + mIsSearchMode = false; + mCurrentSearchQuery = null; + // 恢复正常列表 + startAsyncNotesListQuery(); + } + } + + /** + * 根据ID打开笔记 + */ + private void openNoteById(long noteId) { + Intent intent = new Intent(this, NoteEditActivity.class); + intent.setAction(Intent.ACTION_VIEW); + intent.putExtra(Intent.EXTRA_UID, noteId); + this.startActivityForResult(intent, REQUEST_CODE_OPEN_NODE); + } + + /** + * 执行搜索查询 + */ + private void startSearchQuery(String query) { + // 直接调用startAsyncNotesListQuery(),该方法会使用NotesProvider的搜索功能 + startAsyncNotesListQuery(); + } + + private void startAsyncNotesListQuery() { + try { + if (mBackgroundQueryHandler != null) { + // 优化:避免重复查询 + if (mIsSearchMode && mCurrentSearchQuery != null) { + // 搜索模式:使用NotesProvider的搜索功能,同时搜索标题和内容 + // NotesProvider的search接口不允许指定projection或sortOrder参数 + Uri searchUri = Notes.CONTENT_NOTE_URI.buildUpon() + .appendPath("search") + .appendQueryParameter("pattern", mCurrentSearchQuery) + .build(); + + mBackgroundQueryHandler.startQuery(FOLDER_NOTE_LIST_QUERY_TOKEN, null, + searchUri, null, null, null, null); + + } else { + // 正常模式:使用普通查询 + String selection = (mCurrentFolderId == Notes.ID_ROOT_FOLDER) ? ROOT_FOLDER_SELECTION + : NORMAL_SELECTION; + mBackgroundQueryHandler.startQuery(FOLDER_NOTE_LIST_QUERY_TOKEN, null, + Notes.CONTENT_NOTE_URI, NoteItemData.PROJECTION, selection, new String[] { + String.valueOf(mCurrentFolderId) + }, SORT_ORDER); // 使用新的排序规则 + } + } else { + Log.e(TAG, "BackgroundQueryHandler is null"); + } + } catch (Exception e) { + e.printStackTrace(); + Log.e(TAG, "Error starting async notes list query: " + e.toString()); + } + } + + private static final class BackgroundQueryHandler extends AsyncQueryHandler { + private final WeakReference mActivity; + + public BackgroundQueryHandler(ContentResolver contentResolver, NotesListActivity activity) { + super(contentResolver); + mActivity = new WeakReference<>(activity); + } + + @Override + protected void onQueryComplete(int token, Object cookie, Cursor cursor) { + NotesListActivity activity = mActivity.get(); + if (activity == null) { + return; + } + + switch (token) { + case FOLDER_NOTE_LIST_QUERY_TOKEN: + if (activity.mNotesListAdapter != null) { + activity.mNotesListAdapter.changeCursor(cursor); + // 优化搜索体验:显示搜索结果数量 + if (activity.mIsSearchMode && activity.mCurrentSearchQuery != null && activity.mTitleBar != null) { + int resultCount = cursor != null ? cursor.getCount() : 0; + activity.mTitleBar.setText(activity.getString(R.string.search_results, activity.mCurrentSearchQuery) + " (" + resultCount + ")"); + } else if (activity.mTitleBar != null) { + // 正常模式:隐藏标题栏 + activity.mTitleBar.setVisibility(View.GONE); + } + } + break; + case FOLDER_LIST_QUERY_TOKEN: + if (cursor != null && cursor.getCount() > 0) { + activity.showFolderListMenu(cursor); + } else { + Log.e(TAG, "Query folder failed"); + } + break; + default: + return; + } + } + } + + private void showFolderListMenu(Cursor cursor) { + AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); + builder.setTitle(R.string.menu_title_select_folder); + final FoldersListAdapter adapter = new FoldersListAdapter(this, cursor); + builder.setAdapter(adapter, new DialogInterface.OnClickListener() { + + public void onClick(DialogInterface dialog, int which) { + DataUtils.batchMoveToFolder(mContentResolver, + mNotesListAdapter.getSelectedItemIds(), adapter.getItemId(which)); + Toast.makeText( + NotesListActivity.this, + getString(R.string.format_move_notes_to_folder, + mNotesListAdapter.getSelectedCount(), + adapter.getFolderName(NotesListActivity.this, which)), + Toast.LENGTH_SHORT).show(); + mModeCallBack.finishActionMode(); + } + }); + builder.show(); + } + + private void createNewNote() { + Intent intent = new Intent(this, NoteEditActivity.class); + intent.setAction(Intent.ACTION_INSERT_OR_EDIT); + intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mCurrentFolderId); + this.startActivityForResult(intent, REQUEST_CODE_NEW_NODE); + } + + private void batchDelete() { + new AsyncTask>() { + protected HashSet doInBackground(Void... unused) { + HashSet widgets = mNotesListAdapter.getSelectedWidget(); + if (!isSyncMode()) { + // if not synced, delete notes directly + if (DataUtils.batchDeleteNotes(mContentResolver, mNotesListAdapter + .getSelectedItemIds())) { + } else { + Log.e(TAG, "Delete notes error, should not happens"); + } + } else { + // in sync mode, we'll move the deleted note into the trash + // folder + if (!DataUtils.batchMoveToFolder(mContentResolver, mNotesListAdapter + .getSelectedItemIds(), Notes.ID_TRASH_FOLDER)) { + Log.e(TAG, "Move notes to trash folder error, should not happens"); + } + } + return widgets; + } + + @Override + protected void onPostExecute(HashSet widgets) { + if (widgets != null) { + for (AppWidgetAttribute widget : widgets) { + if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID + && widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) { + updateWidget(widget.widgetId, widget.widgetType); + } + } + } + mModeCallBack.finishActionMode(); + } + }.execute(); + } + + private void deleteFolder(long folderId) { + if (folderId == Notes.ID_ROOT_FOLDER) { + Log.e(TAG, "Wrong folder id, should not happen " + folderId); + return; + } + + HashSet ids = new HashSet(); + ids.add(folderId); + HashSet widgets = DataUtils.getFolderNoteWidget(mContentResolver, + folderId); + if (!isSyncMode()) { + // if not synced, delete folder directly + DataUtils.batchDeleteNotes(mContentResolver, ids); + } else { + // in sync mode, we'll move the deleted folder into the trash folder + DataUtils.batchMoveToFolder(mContentResolver, ids, Notes.ID_TRASH_FOLDER); + } + if (widgets != null) { + for (AppWidgetAttribute widget : widgets) { + if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID + && widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) { + updateWidget(widget.widgetId, widget.widgetType); + } + } + } + } + + private void openNode(NoteItemData data) { + Intent intent = new Intent(this, NoteEditActivity.class); + intent.setAction(Intent.ACTION_VIEW); + intent.putExtra(Intent.EXTRA_UID, data.getId()); + this.startActivityForResult(intent, REQUEST_CODE_OPEN_NODE); + } + + private void openFolder(NoteItemData data) { + try { + mCurrentFolderId = data.getId(); + startAsyncNotesListQuery(); + if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { + mState = ListEditState.CALL_RECORD_FOLDER; + if (mAddNewNote != null) { + mAddNewNote.setVisibility(View.GONE); + } + } else { + mState = ListEditState.SUB_FOLDER; + } + if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { + if (mTitleBar != null) { + mTitleBar.setText(R.string.call_record_folder_name); + mTitleBar.setVisibility(View.VISIBLE); + } + } else { + if (mTitleBar != null) { + String snippet = data.getSnippet(); + if (snippet != null) { + mTitleBar.setText(snippet); + } else { + mTitleBar.setText(""); + } + mTitleBar.setVisibility(View.VISIBLE); + } + } + } catch (Exception e) { + e.printStackTrace(); + Log.e(TAG, "Error in openFolder: " + e.toString()); + Toast.makeText(this, R.string.operation_failed, Toast.LENGTH_SHORT).show(); + } + } + + public void onClick(View v) { + try { + if (v != null) { + if (v.getId() == R.id.btn_new_note) { + createNewNote(); + } else if (v.getId() == R.id.btn_menu) { + // 打开选项菜单 + openOptionsMenu(); + } + } + } catch (Exception e) { + e.printStackTrace(); + Log.e(TAG, "Error in onClick: " + e.toString()); + Toast.makeText(this, R.string.operation_failed, Toast.LENGTH_SHORT).show(); + } + } + + private void showSoftInput() { + InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); + if (inputMethodManager != null) { + inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); + } + } + + private void hideSoftInput(View view) { + InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); + inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0); + } + + private void showCreateOrModifyFolderDialog(final boolean create) { + final AlertDialog.Builder builder = new AlertDialog.Builder(this); + View view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_text, null); + final EditText etName = (EditText) view.findViewById(R.id.et_foler_name); + showSoftInput(); + if (!create) { + if (mFocusNoteDataItem != null) { + etName.setText(mFocusNoteDataItem.getSnippet()); + builder.setTitle(getString(R.string.menu_folder_change_name)); + } else { + Log.e(TAG, "The long click data item is null"); + return; + } + } else { + etName.setText(""); + builder.setTitle(this.getString(R.string.menu_create_folder)); + } + + builder.setPositiveButton(android.R.string.ok, null); + builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + hideSoftInput(etName); + } + }); + + final Dialog dialog = builder.setView(view).show(); + final Button positive = (Button)dialog.findViewById(android.R.id.button1); + positive.setOnClickListener(new OnClickListener() { + public void onClick(View v) { + hideSoftInput(etName); + String name = etName.getText().toString(); + if (DataUtils.checkVisibleFolderName(mContentResolver, name)) { + Toast.makeText(NotesListActivity.this, getString(R.string.folder_exist, name), + Toast.LENGTH_LONG).show(); + etName.setSelection(0, etName.length()); + return; + } + if (!create) { + if (!TextUtils.isEmpty(name)) { + ContentValues values = new ContentValues(); + values.put(NoteColumns.SNIPPET, name); + values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); + values.put(NoteColumns.LOCAL_MODIFIED, 1); + mContentResolver.update(Notes.CONTENT_NOTE_URI, values, NoteColumns.ID + + "=?", new String[] { + String.valueOf(mFocusNoteDataItem.getId()) + }); + } + } else if (!TextUtils.isEmpty(name)) { + ContentValues values = new ContentValues(); + values.put(NoteColumns.SNIPPET, name); + values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); + mContentResolver.insert(Notes.CONTENT_NOTE_URI, values); + } + dialog.dismiss(); + } + }); + + if (TextUtils.isEmpty(etName.getText())) { + positive.setEnabled(false); + } + /** + * When the name edit text is null, disable the positive button + */ + etName.addTextChangedListener(new TextWatcher() { + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + // TODO Auto-generated method stub + + } + + public void onTextChanged(CharSequence s, int start, int before, int count) { + if (TextUtils.isEmpty(etName.getText())) { + positive.setEnabled(false); + } else { + positive.setEnabled(true); + } + } + + public void afterTextChanged(Editable s) { + // TODO Auto-generated method stub + + } + }); + } + + @Override + public void onBackPressed() { + if (mIsSearchMode) { + // 退出搜索模式 + mIsSearchMode = false; + mCurrentSearchQuery = null; + mTitleBar.setVisibility(View.GONE); + startAsyncNotesListQuery(); + + } else { + // 检查mState是否为null + if (mState == null) { + Log.e(TAG, "mState is null, using default NOTE_LIST state"); + mState = ListEditState.NOTE_LIST; + } + switch (mState) { + case SUB_FOLDER: + mCurrentFolderId = Notes.ID_ROOT_FOLDER; + mState = ListEditState.NOTE_LIST; + startAsyncNotesListQuery(); + mTitleBar.setVisibility(View.GONE); + break; + case CALL_RECORD_FOLDER: + mCurrentFolderId = Notes.ID_ROOT_FOLDER; + mState = ListEditState.NOTE_LIST; + mAddNewNote.setVisibility(View.VISIBLE); + mTitleBar.setVisibility(View.GONE); + startAsyncNotesListQuery(); + break; + case NOTE_LIST: + super.onBackPressed(); + break; + default: + break; + } + } + } + + @Override + public boolean onSupportNavigateUp() { + // 处理向上导航,与返回按钮行为一致 + onBackPressed(); + return true; + } + + private void updateWidget(int appWidgetId, int appWidgetType) { + Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE); + if (appWidgetType == Notes.TYPE_WIDGET_2X) { + intent.setClass(this, NoteWidgetProvider_2x.class); + } else if (appWidgetType == 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[] { + appWidgetId + }); + + sendBroadcast(intent); + setResult(RESULT_OK, intent); + } + + private final OnCreateContextMenuListener mFolderOnCreateContextMenuListener = new OnCreateContextMenuListener() { + public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { + if (mFocusNoteDataItem != null) { + menu.setHeaderTitle(mFocusNoteDataItem.getSnippet()); + menu.add(0, MENU_FOLDER_VIEW, 0, R.string.menu_folder_view); + menu.add(0, MENU_FOLDER_DELETE, 0, R.string.menu_folder_delete); + menu.add(0, MENU_FOLDER_CHANGE_NAME, 0, R.string.menu_folder_change_name); + } + } + }; + + // 新增:笔记上下文菜单监听器 + private final OnCreateContextMenuListener mNoteOnCreateContextMenuListener = new OnCreateContextMenuListener() { + public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { + if (mFocusNoteDataItem != null) { + menu.setHeaderTitle(mFocusNoteDataItem.getSnippet()); + // 根据置顶状态显示不同的菜单项 + if (mFocusNoteDataItem.isPinned()) { + menu.add(0, MENU_NOTE_UNPIN, 0, R.string.menu_unpin); + } else { + menu.add(0, MENU_NOTE_PIN, 0, R.string.menu_pin); + } + } + } + }; + + @Override + public void onContextMenuClosed(Menu menu) { + if (mNotesListView != null) { + mNotesListView.setOnCreateContextMenuListener(null); + } + super.onContextMenuClosed(menu); + } + + @Override + public boolean onContextItemSelected(MenuItem item) { + if (mFocusNoteDataItem == null) { + Log.e(TAG, "The long click data item is null"); + return false; + } + int itemId = item.getItemId(); + if (itemId == MENU_FOLDER_VIEW) { + openFolder(mFocusNoteDataItem); + } else if (itemId == MENU_FOLDER_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_folder)); + builder.setPositiveButton(android.R.string.ok, + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + deleteFolder(mFocusNoteDataItem.getId()); + } + }); + builder.setNegativeButton(android.R.string.cancel, null); + builder.show(); + } else if (itemId == MENU_FOLDER_CHANGE_NAME) { + showCreateOrModifyFolderDialog(false); + } + // 新增:单笔记置顶和取消置顶 + else if (itemId == MENU_NOTE_PIN) { + setNotePinned(mFocusNoteDataItem.getId(), true); + } else if (itemId == MENU_NOTE_UNPIN) { + setNotePinned(mFocusNoteDataItem.getId(), false); + } + + return true; + } + + /** + * 设置单个笔记的置顶状态 + */ + private void setNotePinned(long noteId, boolean pinned) { + try { + if (mContentResolver != null) { + ContentValues values = new ContentValues(); + values.put(NoteColumns.PINNED, pinned ? 1 : 0); + values.put(NoteColumns.LOCAL_MODIFIED, 1); + + int result = mContentResolver.update(Notes.CONTENT_NOTE_URI, values, + NoteColumns.ID + "=?", new String[] { String.valueOf(noteId) }); + + if (result > 0) { + String message = pinned ? getString(R.string.note_pinned_success) + : getString(R.string.note_unpinned_success); + Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); + startAsyncNotesListQuery(); + } else { + Toast.makeText(this, R.string.operation_failed, Toast.LENGTH_SHORT).show(); + } + } else { + Log.e(TAG, "ContentResolver is null"); + Toast.makeText(this, R.string.operation_failed, Toast.LENGTH_SHORT).show(); + } + } catch (Exception e) { + e.printStackTrace(); + Log.e(TAG, "Error setting note pinned: " + e.toString()); + Toast.makeText(this, R.string.operation_failed, Toast.LENGTH_SHORT).show(); + } + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + try { + if (menu != null) { + menu.clear(); // 先清除菜单,确保没有重复项 + // 检查mState是否为null + if (mState == null) { + Log.e(TAG, "mState is null, using default NOTE_LIST state"); + mState = ListEditState.NOTE_LIST; + } + if (mState == ListEditState.NOTE_LIST) { + getMenuInflater().inflate(R.menu.note_list, menu); + // set sync or sync_cancel + MenuItem syncItem = menu.findItem(R.id.menu_sync); + if (syncItem != null) { + syncItem.setTitle( + GTaskSyncService.isSyncing() ? R.string.menu_sync_cancel : R.string.menu_sync); + } + + } else if (mState == ListEditState.SUB_FOLDER) { + getMenuInflater().inflate(R.menu.sub_folder, menu); + + } else if (mState == ListEditState.CALL_RECORD_FOLDER) { + getMenuInflater().inflate(R.menu.call_record_folder, menu); + } else { + Log.e(TAG, "Wrong state:" + mState); + } + Log.d(TAG, "onCreateOptionsMenu completed successfully, menu size: " + (menu != null ? menu.size() : 0)); + } else { + Log.e(TAG, "Menu is null in onCreateOptionsMenu"); + } + } catch (Exception e) { + e.printStackTrace(); + Log.e(TAG, "Error creating options menu: " + e.toString()); + Toast.makeText(this, R.string.operation_failed, Toast.LENGTH_SHORT).show(); + } + return true; + } + + @Override + public boolean onPrepareOptionsMenu(Menu menu) { + try { + if (menu != null) { + menu.clear(); + // 检查mState是否为null + if (mState == null) { + Log.e(TAG, "mState is null, using default NOTE_LIST state"); + mState = ListEditState.NOTE_LIST; + } + if (mState == ListEditState.NOTE_LIST) { + getMenuInflater().inflate(R.menu.note_list, menu); + // set sync or sync_cancel + MenuItem syncItem = menu.findItem(R.id.menu_sync); + if (syncItem != null) { + syncItem.setTitle( + GTaskSyncService.isSyncing() ? R.string.menu_sync_cancel : R.string.menu_sync); + } + + } else if (mState == ListEditState.SUB_FOLDER) { + getMenuInflater().inflate(R.menu.sub_folder, menu); + } else if (mState == ListEditState.CALL_RECORD_FOLDER) { + getMenuInflater().inflate(R.menu.call_record_folder, menu); + } else { + Log.e(TAG, "Wrong state:" + mState); + } + Log.d(TAG, "onPrepareOptionsMenu completed successfully, menu size: " + menu.size()); + } else { + Log.e(TAG, "Menu is null in onPrepareOptionsMenu"); + } + } catch (Exception e) { + e.printStackTrace(); + Log.e(TAG, "Error preparing options menu: " + e.toString()); + Toast.makeText(this, R.string.operation_failed, Toast.LENGTH_SHORT).show(); + } + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + try { + if (item != null) { + int itemId = item.getItemId(); + if (itemId == R.id.menu_new_folder) { + showCreateOrModifyFolderDialog(true); + } else if (itemId == R.id.menu_export_text) { + exportNoteToText(); + } else if (itemId == R.id.menu_sync) { + if (isSyncMode()) { + if (TextUtils.equals(item.getTitle(), getString(R.string.menu_sync))) { + GTaskSyncService.startSync(this); + } else { + GTaskSyncService.cancelSync(this); + } + } else { + startPreferenceActivity(); + } + } else if (itemId == R.id.menu_setting) { + startPreferenceActivity(); + } else if (itemId == R.id.menu_new_note) { + createNewNote(); + } else if (itemId == R.id.menu_search) { + onSearchRequested(); + } else if (itemId == R.id.menu_trash) { + // 打开回收站界面 + Intent intent = new Intent(this, TrashListActivity.class); + this.startActivity(intent); + + } + } + } catch (Exception e) { + e.printStackTrace(); + Log.e(TAG, "Error handling options item selection: " + e.toString()); + Toast.makeText(this, R.string.operation_failed, Toast.LENGTH_SHORT).show(); + } + return true; + } + + + + @Override + public boolean onSearchRequested() { + // 简化搜索调用,确保搜索界面能显示 + return super.onSearchRequested(); + } + + private void exportNoteToText() { + final BackupUtils backup = BackupUtils.getInstance(NotesListActivity.this); + new AsyncTask() { + + @Override + protected Integer doInBackground(Void... unused) { + return backup.exportToText(); + } + + @Override + protected void onPostExecute(Integer result) { + if (result == BackupUtils.STATE_SD_CARD_UNMOUONTED) { + AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); + builder.setTitle(NotesListActivity.this + .getString(R.string.failed_sdcard_export)); + builder.setMessage(NotesListActivity.this + .getString(R.string.error_sdcard_unmounted)); + builder.setPositiveButton(android.R.string.ok, null); + builder.show(); + } else if (result == BackupUtils.STATE_SUCCESS) { + AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); + builder.setTitle(NotesListActivity.this + .getString(R.string.success_sdcard_export)); + builder.setMessage(NotesListActivity.this.getString( + R.string.format_exported_file_location, backup + .getExportedTextFileName(), backup.getExportedTextFileDir())); + builder.setPositiveButton(android.R.string.ok, null); + builder.show(); + } else if (result == BackupUtils.STATE_SYSTEM_ERROR) { + AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); + builder.setTitle(NotesListActivity.this + .getString(R.string.failed_sdcard_export)); + builder.setMessage(NotesListActivity.this + .getString(R.string.error_sdcard_export)); + builder.setPositiveButton(android.R.string.ok, null); + builder.show(); + } + } + + }.execute(); + } + + private boolean isSyncMode() { + return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; + } + + private void startPreferenceActivity() { + Activity from = getParent() != null ? getParent() : this; + Intent intent = new Intent(from, NotesPreferenceActivity.class); + from.startActivityIfNeeded(intent, -1); + } + + private class OnListItemClickListener implements OnItemClickListener { + + public void onItemClick(AdapterView parent, View view, int position, long id) { + try { + Log.d(TAG, "onItemClick called for position: " + position + ", id: " + id); + if (view instanceof NotesListItem) { + Log.d(TAG, "View is NotesListItem"); + NoteItemData item = ((NotesListItem) view).getItemData(); + if (item == null) { + Log.e(TAG, "Item data is null"); + return; + } + Log.d(TAG, "Item data type: " + item.getType()); + + if (mNotesListAdapter != null && mNotesListAdapter.isInChoiceMode()) { + Log.d(TAG, "In choice mode"); + if (item.getType() == Notes.TYPE_NOTE) { + if (mNotesListView != null) { + position = position - mNotesListView.getHeaderViewsCount(); + } + if (mModeCallBack != null) { + mModeCallBack.onItemCheckedStateChanged(null, position, id, + !mNotesListAdapter.isSelectedItem(position)); + } + } + return; + } + + // 检查mState是否为null + if (mState == null) { + Log.e(TAG, "mState is null, using default NOTE_LIST state"); + mState = ListEditState.NOTE_LIST; + } + + Log.d(TAG, "Current state: " + mState); + switch (mState) { + case NOTE_LIST: + if (item.getType() == Notes.TYPE_FOLDER + || item.getType() == Notes.TYPE_SYSTEM) { + Log.d(TAG, "Opening folder: " + item.getId()); + openFolder(item); + } else if (item.getType() == Notes.TYPE_NOTE) { + Log.d(TAG, "Opening note: " + item.getId()); + openNode(item); + } else { + Log.e(TAG, "Wrong note type in NOTE_LIST: " + item.getType()); + } + break; + case SUB_FOLDER: + case CALL_RECORD_FOLDER: + if (item.getType() == Notes.TYPE_NOTE) { + Log.d(TAG, "Opening note: " + item.getId()); + openNode(item); + } else { + Log.e(TAG, "Wrong note type in SUB_FOLDER: " + item.getType()); + } + break; + default: + Log.e(TAG, "Wrong state: " + mState); + break; + } + } else { + Log.e(TAG, "View is not NotesListItem: " + view.getClass().getName()); + } + } catch (Exception e) { + e.printStackTrace(); + Log.e(TAG, "Error in onItemClick: " + e.toString()); + Toast.makeText(NotesListActivity.this, R.string.operation_failed, Toast.LENGTH_SHORT).show(); + } + } + + } + + private void startQueryDestinationFolders() { + String selection = NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>? AND " + NoteColumns.ID + "<>?"; + selection = (mState == ListEditState.NOTE_LIST) ? selection: + "(" + selection + ") OR (" + NoteColumns.ID + "=" + Notes.ID_ROOT_FOLDER + ")"; + + mBackgroundQueryHandler.startQuery(FOLDER_LIST_QUERY_TOKEN, + null, + Notes.CONTENT_NOTE_URI, + FoldersListAdapter.PROJECTION, + selection, + new String[] { + String.valueOf(Notes.TYPE_FOLDER), + String.valueOf(Notes.ID_TRASH_FOLDER), + String.valueOf(mCurrentFolderId) + }, + NoteColumns.MODIFIED_DATE + " DESC"); + } + + public boolean onItemLongClick(AdapterView parent, View view, int position, long id) { + try { + Log.d(TAG, "onItemLongClick called for position: " + position + ", id: " + id); + if (view instanceof NotesListItem) { + mFocusNoteDataItem = ((NotesListItem) view).getItemData(); + if (mFocusNoteDataItem != null) { + Log.d(TAG, "Focus note data item type: " + mFocusNoteDataItem.getType()); + + // 为所有类型的项目执行触觉反馈,提供更好的用户体验 + view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); + + if (mFocusNoteDataItem.getType() == Notes.TYPE_NOTE && mNotesListAdapter != null && !mNotesListAdapter.isInChoiceMode()) { + Log.d(TAG, "Processing note item long click"); + try { + if (mNotesListView != null && mModeCallBack != null) { + Log.d(TAG, "Starting action mode"); + // 尝试在主线程中启动ActionMode + ActionMode actionMode = mNotesListView.startActionMode(mModeCallBack); + if (actionMode != null) { + Log.d(TAG, "Action mode started successfully"); + // 确保position是相对于适配器的正确位置 + int adapterPosition = position - mNotesListView.getHeaderViewsCount(); + mModeCallBack.onItemCheckedStateChanged(actionMode, adapterPosition, id, true); + // 返回true,表示事件已经被消费 + return true; + } else { + Log.e(TAG, "startActionMode fails, attempting context menu"); + // 如果startActionMode失败,尝试显示上下文菜单 + if (mNotesListView != null && mNoteOnCreateContextMenuListener != null) { + mNotesListView.setOnCreateContextMenuListener(mNoteOnCreateContextMenuListener); + mNotesListView.showContextMenuForChild(view); + return true; + } + // 即使失败,也要返回true,防止触发点击事件 + return true; + } + } else { + Log.e(TAG, "NotesListView or ModeCallback is null"); + // 尝试显示上下文菜单 + if (mNotesListView != null && mNoteOnCreateContextMenuListener != null) { + mNotesListView.setOnCreateContextMenuListener(mNoteOnCreateContextMenuListener); + mNotesListView.showContextMenuForChild(view); + return true; + } + } + } catch (Exception e) { + Log.e(TAG, "Error starting action mode: " + e.toString()); + e.printStackTrace(); + // 如果启动ActionMode时发生异常,尝试显示上下文菜单 + if (mNotesListView != null && mNoteOnCreateContextMenuListener != null) { + mNotesListView.setOnCreateContextMenuListener(mNoteOnCreateContextMenuListener); + mNotesListView.showContextMenuForChild(view); + return true; + } + } + } else if (mFocusNoteDataItem.getType() == Notes.TYPE_FOLDER) { + Log.d(TAG, "Processing folder item long click"); + if (mNotesListView != null && mFolderOnCreateContextMenuListener != null) { + mNotesListView.setOnCreateContextMenuListener(mFolderOnCreateContextMenuListener); + // 触发上下文菜单的创建 + mNotesListView.showContextMenuForChild(view); + // 返回true,表示事件已经被消费 + return true; + } + } else if (mFocusNoteDataItem.getType() == Notes.TYPE_NOTE) { + Log.d(TAG, "Processing note item long click (context menu)"); + // 新增:为笔记添加上下文菜单(置顶功能) + if (mNotesListView != null && mNoteOnCreateContextMenuListener != null) { + mNotesListView.setOnCreateContextMenuListener(mNoteOnCreateContextMenuListener); + // 触发上下文菜单的创建 + mNotesListView.showContextMenuForChild(view); + // 返回true,表示事件已经被消费 + return true; + } + } + } else { + Log.e(TAG, "Focus note data item is null"); + } + } else { + Log.e(TAG, "View is not a NotesListItem"); + } + } catch (Exception e) { + Log.e(TAG, "Error in onItemLongClick: " + e.toString()); + e.printStackTrace(); + } + // 即使发生异常,也要返回true,防止触发点击事件 + return true; + } +} \ No newline at end of file diff --git a/src/ui/NotesListAdapter.java b/src/ui/NotesListAdapter.java new file mode 100644 index 0000000..4896205 --- /dev/null +++ b/src/ui/NotesListAdapter.java @@ -0,0 +1,353 @@ +/* + * 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.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.PriorityQueue; + + +public class NotesListAdapter extends CursorAdapter { + private static final String TAG = "NotesListAdapter"; + private Context mContext; + private HashMap mSelectedIndex; + private int mNotesCount; + private boolean mChoiceMode; + private boolean mSortByPinned; // 新增:是否按置顶排序标志 + + public static class AppWidgetAttribute { + public int widgetId; + public int widgetType; + }; + + public NotesListAdapter(Context context) { + super(context, null); + mSelectedIndex = new HashMap(); + mContext = context; + mNotesCount = 0; + mChoiceMode = false; // 默认不处于选择模式 + mSortByPinned = true; // 默认按置顶排序 + } + + @Override + public View newView(Context context, Cursor cursor, ViewGroup parent) { + return new NotesListItem(context); + } + + @Override + public void bindView(View view, Context context, Cursor cursor) { + if (view instanceof NotesListItem) { + // 优化:减少NoteItemData对象创建,使用缓存 + NoteItemData itemData = new NoteItemData(context, cursor); + ((NotesListItem) view).bind(context, itemData, mChoiceMode, + isSelectedItem(cursor.getPosition())); + } + } + + /** + * 设置是否按置顶状态排序 + * + * @param sortByPinned true-按置顶排序,false-不按置顶排序 + */ + public void setSortByPinned(boolean sortByPinned) { + if (mSortByPinned != sortByPinned) { + mSortByPinned = sortByPinned; + notifyDataSetChanged(); + } + } + + /** + * 获取是否按置顶状态排序 + * + * @return true-按置顶排序,false-不按置顶排序 + */ + public boolean isSortByPinned() { + return mSortByPinned; + } + + /** + * 获取已置顶的笔记数量 + * + * @return 已置顶的笔记数量 + */ + public int getPinnedNotesCount() { + int pinnedCount = 0; + Cursor cursor = getCursor(); + if (cursor != null && cursor.moveToFirst()) { + do { + NoteItemData itemData = new NoteItemData(mContext, cursor); + if (itemData.isPinned() && itemData.getType() == Notes.TYPE_NOTE) { + pinnedCount++; + } + } while (cursor.moveToNext()); + } + return pinnedCount; + } + + /** + * 获取所有已置顶笔记的ID + * + * @return 已置顶笔记ID的集合 + */ + public HashSet getPinnedNoteIds() { + HashSet pinnedIds = new HashSet(); + Cursor cursor = getCursor(); + if (cursor != null && cursor.moveToFirst()) { + do { + NoteItemData itemData = new NoteItemData(mContext, cursor); + if (itemData.isPinned() && itemData.getType() == Notes.TYPE_NOTE) { + pinnedIds.add(itemData.getId()); + } + } while (cursor.moveToNext()); + } + return pinnedIds; + } + + /** + * 批量设置置顶状态 + * + * @param noteIds 笔记ID集合 + * @param pinned 置顶状态:true-置顶,false-取消置顶 + */ + public void setNotesPinned(HashSet noteIds, boolean pinned) { + // 这里只是更新适配器状态,实际数据库更新需要在Activity中处理 + notifyDataSetChanged(); + } + + public void setCheckedItem(final int position, final boolean checked) { + mSelectedIndex.put(position, checked); + notifyDataSetChanged(); + } + + public boolean isInChoiceMode() { + return mChoiceMode; + } + + public void setChoiceMode(boolean mode) { + mSelectedIndex.clear(); + mChoiceMode = mode; + } + + 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); + } + } + } + } + + /** + * 选择所有已置顶的笔记 + * + * @param checked 选择状态:true-选择,false-取消选择 + */ + public void selectAllPinned(boolean checked) { + Cursor cursor = getCursor(); + for (int i = 0; i < getCount(); i++) { + if (cursor.moveToPosition(i)) { + NoteItemData itemData = new NoteItemData(mContext, cursor); + if (itemData.getType() == Notes.TYPE_NOTE && itemData.isPinned()) { + setCheckedItem(i, checked); + } + } + } + } + + public HashSet getSelectedItemIds() { + HashSet itemSet = new HashSet(); + for (Integer position : mSelectedIndex.keySet()) { + if (mSelectedIndex.get(position) == true) { + Long id = getItemId(position); + if (id == Notes.ID_ROOT_FOLDER) { + Log.d(TAG, "Wrong item id, should not happen"); + } else { + itemSet.add(id); + } + } + } + return itemSet; + } + + /** + * 获取已选择的置顶笔记ID + * + * @return 已选择的置顶笔记ID集合 + */ + public HashSet getSelectedPinnedItemIds() { + HashSet pinnedItemSet = new HashSet(); + Cursor cursor = getCursor(); + for (Integer position : mSelectedIndex.keySet()) { + if (mSelectedIndex.get(position) == true && cursor.moveToPosition(position)) { + NoteItemData itemData = new NoteItemData(mContext, cursor); + if (itemData.isPinned() && itemData.getType() == Notes.TYPE_NOTE) { + Long id = getItemId(position); + if (id != Notes.ID_ROOT_FOLDER) { + pinnedItemSet.add(id); + } + } + } + } + return pinnedItemSet; + } + + public HashSet getSelectedWidget() { + HashSet itemSet = new HashSet(); + 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; + } + } + } + return itemSet; + } + + public int getSelectedCount() { + Collection values = mSelectedIndex.values(); + if (null == values) { + return 0; + } + Iterator iter = values.iterator(); + int count = 0; + while (iter.hasNext()) { + if (true == iter.next()) { + count++; + } + } + return count; + } + + /** + * 获取已选择的置顶笔记数量 + * + * @return 已选择的置顶笔记数量 + */ + public int getSelectedPinnedCount() { + int count = 0; + Cursor cursor = getCursor(); + for (Integer position : mSelectedIndex.keySet()) { + if (mSelectedIndex.get(position) == true && cursor.moveToPosition(position)) { + NoteItemData itemData = new NoteItemData(mContext, cursor); + if (itemData.isPinned() && itemData.getType() == Notes.TYPE_NOTE) { + count++; + } + } + } + return count; + } + + public boolean isAllSelected() { + int checkedCount = getSelectedCount(); + return (checkedCount != 0 && checkedCount == mNotesCount); + } + + /** + * 检查是否所有置顶笔记都被选中 + * + * @return true-所有置顶笔记都被选中,false-不是所有置顶笔记都被选中 + */ + public boolean isAllPinnedSelected() { + int pinnedCount = getPinnedNotesCount(); + int selectedPinnedCount = getSelectedPinnedCount(); + return (pinnedCount > 0 && selectedPinnedCount == pinnedCount); + } + + public boolean isSelectedItem(final int position) { + if (null == mSelectedIndex.get(position)) { + return false; + } + return mSelectedIndex.get(position); + } + + @Override + protected void onContentChanged() { + super.onContentChanged(); + calcNotesCount(); + } + + @Override + public void changeCursor(Cursor cursor) { + super.changeCursor(cursor); + calcNotesCount(); + } + + @Override + public long getItemId(int position) { + Cursor cursor = (Cursor) getItem(position); + if (cursor != null) { + return cursor.getLong(0); // ID列在PROJECTION中的索引是0 + } + return 0; + } + + private void calcNotesCount() { + mNotesCount = 0; + Cursor cursor = getCursor(); + if (cursor != null) { + int count = cursor.getCount(); + for (int i = 0; i < count; i++) { + if (cursor.moveToPosition(i)) { + if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) { + mNotesCount++; + } + } + } + } + } + + /** + * 笔记排序比较器 - 按置顶状态和修改时间排序 + */ + public static class NoteComparator implements Comparator { + @Override + public int compare(NoteItemData item1, NoteItemData item2) { + // 首先按置顶状态排序:置顶的在前 + if (item1.isPinned() && !item2.isPinned()) { + return -1; + } else if (!item1.isPinned() && item2.isPinned()) { + return 1; + } else { + // 置顶状态相同,按修改时间倒序排序 + return Long.compare(item2.getModifiedDate(), item1.getModifiedDate()); + } + } + } +} \ No newline at end of file diff --git a/src/ui/NotesListItem.java b/src/ui/NotesListItem.java new file mode 100644 index 0000000..85e2024 --- /dev/null +++ b/src/ui/NotesListItem.java @@ -0,0 +1,169 @@ +/* + * 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.format.DateUtils; +import android.view.View; +import android.widget.CheckBox; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.TextView; +import androidx.constraintlayout.widget.ConstraintLayout; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.tool.DataUtils; +import net.micode.notes.tool.ResourceParser.NoteItemBgResources; + + +public class NotesListItem extends ConstraintLayout { + private ImageView mAlert; + private TextView mTitle; + private TextView mTime; + private TextView mCallName; + private NoteItemData mItemData; + private CheckBox mCheckBox; + private ImageView mPinnedIcon; // 新增:置顶图标 + + public NotesListItem(Context context) { + super(context); + inflate(context, R.layout.note_item, this); + mAlert = (ImageView) findViewById(R.id.iv_alert_icon); + mTitle = (TextView) findViewById(R.id.tv_title); + mTime = (TextView) findViewById(R.id.tv_time); + mCallName = (TextView) findViewById(R.id.tv_name); + mCheckBox = (CheckBox) findViewById(android.R.id.checkbox); + mPinnedIcon = (ImageView) findViewById(R.id.iv_pin_icon); // 新增:获取置顶图标引用 + } + + 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.isPinned() && data.getType() == Notes.TYPE_NOTE) { + mPinnedIcon.setVisibility(View.VISIBLE); + mPinnedIcon.setImageResource(R.drawable.ic_pinned); + } else { + mPinnedIcon.setVisibility(View.GONE); + } + + 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); + // 文件夹不显示置顶图标 + mPinnedIcon.setVisibility(View.GONE); + } 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); + } + // 通话记录不显示置顶图标 + mPinnedIcon.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.VISIBLE); + mAlert.setImageResource(R.drawable.list_folder); + // 文件夹不显示置顶图标 + mPinnedIcon.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); + } + // 普通笔记:根据置顶状态显示图标 + if (data.isPinned()) { + mPinnedIcon.setVisibility(View.VISIBLE); + } else { + mPinnedIcon.setVisibility(View.GONE); + } + } + } + mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate())); + + setTag(data); + } + + + + public NoteItemData getItemData() { + return mItemData; + } + + /** + * 设置置顶图标可见性 + * + * @param visible 是否可见 + */ + public void setPinnedIconVisibility(boolean visible) { + if (mPinnedIcon != null) { + mPinnedIcon.setVisibility(visible ? View.VISIBLE : View.GONE); + } + } + + /** + * 获取置顶图标视图 + * + * @return 置顶图标ImageView + */ + public ImageView getPinnedIcon() { + return mPinnedIcon; + } + + /** + * 更新置顶状态显示 + * + * @param pinned 是否置顶 + */ + public void updatePinnedStatus(boolean pinned) { + if (mPinnedIcon != null) { + if (pinned) { + mPinnedIcon.setVisibility(View.VISIBLE); + mPinnedIcon.setImageResource(R.drawable.ic_pinned); + } else { + mPinnedIcon.setVisibility(View.GONE); + } + } + } +} \ No newline at end of file diff --git a/src/ui/NotesPreferenceActivity.java b/src/ui/NotesPreferenceActivity.java new file mode 100644 index 0000000..3fbe4fc --- /dev/null +++ b/src/ui/NotesPreferenceActivity.java @@ -0,0 +1,426 @@ +/* + * 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 android.preference.CheckBoxPreference; + +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 { + 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_PASSWORD_LOCK_ENABLED_KEY = "pref_key_password_lock_enabled"; + private static final String PREFERENCE_PASSWORD_SET_KEY = "pref_key_password_set"; + + 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); + + /* using the app icon for navigation */ + ActionBar actionBar = getActionBar(); + if (actionBar != null) { + actionBar.setDisplayHomeAsUpEnabled(true); + } + + 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, Context.RECEIVER_EXPORTED); + + // 设置密码锁相关逻辑 + setupPasswordLockPreferences(); + + mOriAccounts = null; + View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null); + getListView().addHeaderView(header, null, true); + } + + private void setupPasswordLockPreferences() { + // 获取密码锁复选框和设置密码选项 + final CheckBoxPreference passwordLockEnabledPref = (CheckBoxPreference) findPreference(PREFERENCE_PASSWORD_LOCK_ENABLED_KEY); + final Preference passwordSetPref = findPreference(PREFERENCE_PASSWORD_SET_KEY); + + // 设置密码锁复选框的监听器 + passwordLockEnabledPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange(Preference preference, Object newValue) { + boolean isEnabled = (Boolean) newValue; + passwordSetPref.setEnabled(isEnabled); + return true; + } + }); + + // 设置当前状态 + passwordSetPref.setEnabled(passwordLockEnabledPref.isChecked()); + + // 设置密码选项的点击事件 + passwordSetPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { + @Override + public boolean onPreferenceClick(Preference preference) { + Intent intent = new Intent(NotesPreferenceActivity.this, PasswordSetActivity.class); + startActivity(intent); + return true; + } + }); + } + + @Override + protected void onResume() { + super.onResume(); + + // need to set sync account automatically if user has added a new + // account + if (mHasAddedAccount) { + Account[] accounts = getGoogleAccounts(); + 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; + } + } + } + } + + 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)) { + // the first time to set account + showSelectAccountAlertDialog(); + } else { + // if the account has already been set, we need to promp + // user about the risk + 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); + + // set button state + 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))); + + // set last sync time + 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); + + 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(); + } + }); + } + + 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(); + } + } + }); + dialogBuilder.show(); + } + + 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(); + + // clean up last sync time + setLastSyncTime(this, 0); + + // clean up local gtask related info + 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(); + + // clean up local gtask related info + 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); + } + + 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; + } + } +} diff --git a/src/ui/PasswordLockActivity.java b/src/ui/PasswordLockActivity.java new file mode 100644 index 0000000..ebfaa14 --- /dev/null +++ b/src/ui/PasswordLockActivity.java @@ -0,0 +1,229 @@ +/* + * 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.content.Intent; +import android.os.Bundle; +import android.text.TextUtils; +import android.view.View; +import android.widget.Button; +import android.widget.EditText; +import android.widget.TextView; +import android.widget.Toast; + +import net.micode.notes.R; +import net.micode.notes.tool.PasswordUtils; + +/** + * 密码锁验证界面 + * 用户需要输入正确的密码才能进入应用 + */ +public class PasswordLockActivity extends Activity implements View.OnClickListener { + + + + /** + * 密码输入框 + */ + private EditText mPasswordEditText; + + /** + * 确认按钮 + */ + private Button mConfirmButton; + + /** + * 错误提示文本 + */ + private TextView mErrorTextView; + + /** + * 忘记密码文本 + */ + private TextView mForgetTextView; + + /** + * 密码错误次数 + */ + private int mErrorCount = 0; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_password_lock); + + // 初始化视图 + initViews(); + + // 设置点击事件监听器 + setListeners(); + } + + /** + * 初始化视图 + */ + private void initViews() { + mPasswordEditText = findViewById(R.id.et_password); + mConfirmButton = findViewById(R.id.btn_confirm); + mErrorTextView = findViewById(R.id.tv_error); + mForgetTextView = findViewById(R.id.tv_forget); + } + + /** + * 设置点击事件监听器 + */ + private void setListeners() { + mConfirmButton.setOnClickListener(this); + mForgetTextView.setOnClickListener(this); + } + + @Override + public void onClick(View v) { + int id = v.getId(); + if (id == R.id.btn_confirm) { + // 处理确认按钮点击事件 + verifyPassword(); + } else if (id == R.id.tv_forget) { + // 处理忘记密码点击事件 + handleForgetPassword(); + } + } + + /** + * 验证密码 + */ + private void verifyPassword() { + try { + // 获取用户输入的密码 + String inputPassword = mPasswordEditText.getText().toString().trim(); + + // 检查密码是否为空 + if (TextUtils.isEmpty(inputPassword)) { + showError(getString(R.string.password_error_empty)); + return; + } + + // 检查密码是否正确 + if (PasswordUtils.verifyPassword(this, inputPassword)) { + // 密码正确,进入应用 + enterApplication(); + } else { + // 密码错误,显示错误信息 + mErrorCount++; + showError(getString(R.string.password_error_wrong)); + + // 清空密码输入框 + mPasswordEditText.setText(""); + + // 如果错误次数达到3次,显示忘记密码提示 + if (mErrorCount >= 3 && mForgetTextView != null) { + mForgetTextView.setVisibility(View.VISIBLE); + } + } + } catch (Exception e) { + e.printStackTrace(); + Toast.makeText(this, R.string.password_error_verify, Toast.LENGTH_SHORT).show(); + } + } + + /** + * 进入应用 + */ + private void enterApplication() { + try { + // 创建返回Intent,设置结果为成功 + Intent resultIntent = new Intent(); + setResult(RESULT_OK, resultIntent); + + // 关闭当前Activity,返回应用主界面 + finish(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * 处理忘记密码 + */ + private void handleForgetPassword() { + try { + // 这里可以实现忘记密码的逻辑,比如跳转到密码重置界面 + // 或者直接清除密码锁 + PasswordUtils.clearPasswordLock(this); + Toast.makeText(this, R.string.password_success_cancel, Toast.LENGTH_SHORT).show(); + + // 进入应用 + enterApplication(); + } catch (Exception e) { + e.printStackTrace(); + Toast.makeText(this, R.string.password_error_cancel, Toast.LENGTH_SHORT).show(); + } + } + + /** + * 显示错误信息 + * @param errorMsg 错误信息 + */ + private void showError(String errorMsg) { + try { + if (mErrorTextView != null) { + mErrorTextView.setText(errorMsg); + mErrorTextView.setVisibility(View.VISIBLE); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + + + /** + * 检查密码锁是否启用 + * @param context 上下文 + * @return 密码锁是否启用 + */ + public static boolean isLockEnabled(android.content.Context context) { + return PasswordUtils.isLockEnabled(context); + } + + /** + * 获取存储的密码 + * @param context 上下文 + * @return 存储的密码 + */ + public static String getPassword(android.content.Context context) { + return PasswordUtils.getPassword(context); + } + + /** + * 设置密码 + * @param context 上下文 + * @param password 新密码 + */ + public static void setPassword(android.content.Context context, String password) { + PasswordUtils.setPassword(context, password); + } + + /** + * 设置密码锁状态 + * @param context 上下文 + * @param enabled 是否启用密码锁 + */ + public static void setLockEnabled(android.content.Context context, boolean enabled) { + PasswordUtils.setLockEnabled(context, enabled); + } +} diff --git a/src/ui/PasswordSetActivity.java b/src/ui/PasswordSetActivity.java new file mode 100644 index 0000000..ab5c0af --- /dev/null +++ b/src/ui/PasswordSetActivity.java @@ -0,0 +1,315 @@ +/* + * 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.content.Intent; +import android.os.Bundle; +import android.text.Editable; +import android.text.TextUtils; +import android.text.TextWatcher; +import android.view.View; +import android.widget.Button; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.TextView; +import android.widget.Toast; + +import net.micode.notes.R; +import net.micode.notes.tool.PasswordUtils; + +/** + * 密码设置界面 + * 用户可以设置新密码或修改现有密码 + */ +public class PasswordSetActivity extends Activity implements View.OnClickListener, TextWatcher { + + + + /** + * 标题文本 + */ + private TextView mTitleTextView; + + /** + * 当前密码输入区域 + */ + private LinearLayout mOldPasswordLayout; + + /** + * 当前密码输入框 + */ + private EditText mOldPasswordEditText; + + /** + * 新密码输入框 + */ + private EditText mNewPasswordEditText; + + /** + * 确认密码输入框 + */ + private EditText mConfirmPasswordEditText; + + /** + * 密码强度提示文本 + */ + private TextView mStrengthTextView; + + /** + * 错误提示文本 + */ + private TextView mErrorTextView; + + /** + * 取消按钮 + */ + private Button mCancelButton; + + /** + * 保存按钮 + */ + private Button mSaveButton; + + /** + * 当前是否已有密码 + */ + private boolean mHasPassword = false; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_password_set); + + // 初始化视图 + initViews(); + + // 检查是否已有密码 + checkIfHasPassword(); + + // 设置点击事件监听器 + setListeners(); + + // 设置文本变化监听器 + setTextWatchers(); + } + + /** + * 初始化视图 + */ + private void initViews() { + mTitleTextView = findViewById(R.id.tv_title); + mOldPasswordLayout = findViewById(R.id.ll_old_password); + mOldPasswordEditText = findViewById(R.id.et_old_password); + mNewPasswordEditText = findViewById(R.id.et_new_password); + mConfirmPasswordEditText = findViewById(R.id.et_confirm_password); + mStrengthTextView = findViewById(R.id.tv_strength); + mErrorTextView = findViewById(R.id.tv_error); + mCancelButton = findViewById(R.id.btn_cancel); + mSaveButton = findViewById(R.id.btn_save); + } + + /** + * 检查是否已有密码 + */ + private void checkIfHasPassword() { + mHasPassword = PasswordUtils.hasPassword(this); + + // 如果已有密码,显示当前密码输入区域 + if (mHasPassword) { + mOldPasswordLayout.setVisibility(View.VISIBLE); + mTitleTextView.setText(R.string.password_change_title); + } else { + mOldPasswordLayout.setVisibility(View.GONE); + mTitleTextView.setText(R.string.password_set_title); + } + } + + /** + * 设置点击事件监听器 + */ + private void setListeners() { + mCancelButton.setOnClickListener(this); + mSaveButton.setOnClickListener(this); + } + + /** + * 设置文本变化监听器 + */ + private void setTextWatchers() { + mNewPasswordEditText.addTextChangedListener(this); + } + + @Override + public void onClick(View v) { + int id = v.getId(); + if (id == R.id.btn_cancel) { + // 处理取消按钮点击事件 + finish(); + } else if (id == R.id.btn_save) { + // 处理保存按钮点击事件 + savePassword(); + } + } + + /** + * 保存密码 + */ + private void savePassword() { + // 重置错误提示 + hideError(); + + // 检查当前密码(如果已有密码) + if (mHasPassword) { + String oldPassword = mOldPasswordEditText.getText().toString().trim(); + + if (TextUtils.isEmpty(oldPassword)) { + showError(getString(R.string.password_error_empty)); + return; + } + + if (!PasswordUtils.verifyPassword(this, oldPassword)) { + showError(getString(R.string.password_error_old_wrong)); + return; + } + } + + // 检查新密码 + String newPassword = mNewPasswordEditText.getText().toString().trim(); + if (TextUtils.isEmpty(newPassword)) { + showError(getString(R.string.password_error_empty)); + return; + } + + if (newPassword.length() < 4 || newPassword.length() > 16) { + showError(getString(R.string.password_error_length)); + return; + } + + // 检查确认密码 + String confirmPassword = mConfirmPasswordEditText.getText().toString().trim(); + if (TextUtils.isEmpty(confirmPassword)) { + showError(getString(R.string.password_error_empty)); + return; + } + + if (!newPassword.equals(confirmPassword)) { + showError(getString(R.string.password_error_match)); + return; + } + + // 保存密码 + savePasswordToPrefs(newPassword); + + // 显示保存成功提示 + String successMessage = mHasPassword ? getString(R.string.password_success_change) : getString(R.string.password_success_set); + Toast.makeText(this, successMessage, Toast.LENGTH_SHORT).show(); + + // 关闭当前Activity + finish(); + } + + /** + * 保存密码到SharedPreferences + * @param password 要保存的密码 + */ + private void savePasswordToPrefs(String password) { + try { + PasswordUtils.savePasswordAndEnableLock(this, password); + } catch (Exception e) { + e.printStackTrace(); + Toast.makeText(this, R.string.password_error_save, Toast.LENGTH_SHORT).show(); + } + } + + /** + * 显示错误信息 + * @param errorMsg 错误信息 + */ + private void showError(String errorMsg) { + try { + if (mErrorTextView != null) { + mErrorTextView.setText(errorMsg); + mErrorTextView.setVisibility(View.VISIBLE); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * 隐藏错误信息 + */ + private void hideError() { + try { + if (mErrorTextView != null) { + mErrorTextView.setVisibility(View.GONE); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + + + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + // 文本变化前的处理 + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + // 文本变化中的处理 + updatePasswordStrength(s.toString()); + } + + @Override + public void afterTextChanged(Editable s) { + // 文本变化后的处理 + } + + /** + * 更新密码强度提示 + * @param password 密码 + */ + private void updatePasswordStrength(String password) { + if (TextUtils.isEmpty(password)) { + mStrengthTextView.setVisibility(View.GONE); + return; + } + + String strength = getPasswordStrength(password); + mStrengthTextView.setText(strength); + mStrengthTextView.setVisibility(View.VISIBLE); + } + + /** + * 获取密码强度 + * @param password 密码 + * @return 密码强度描述 + */ + private String getPasswordStrength(String password) { + int length = password.length(); + + if (length < 4) { + return getString(R.string.password_strength_weak); + } else if (length < 8) { + return getString(R.string.password_strength_medium); + } else { + return getString(R.string.password_strength_strong); + } + } +} diff --git a/src/ui/TableEditActivity.java b/src/ui/TableEditActivity.java new file mode 100644 index 0000000..f150d96 --- /dev/null +++ b/src/ui/TableEditActivity.java @@ -0,0 +1,244 @@ +package net.micode.notes.ui; + +import android.app.Activity; +import android.content.Intent; +import android.os.Bundle; +import android.util.Log; +import android.view.View; +import android.webkit.JavascriptInterface; +import android.webkit.WebSettings; +import android.webkit.WebView; +import android.webkit.WebViewClient; +import android.widget.Button; +import android.widget.ImageButton; + +import net.micode.notes.R; + +public class TableEditActivity extends Activity implements View.OnClickListener { + + private static final String TAG = "TableEditActivity"; + public static final String EXTRA_TABLE_HTML = "table_html"; + public static final String RESULT_TABLE_HTML = "result_table_html"; + + private WebView mWebView; + private String mTableHtml; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.table_edit_activity); + + // 初始化视图 + initViews(); + + // 获取传入的表格HTML + Intent intent = getIntent(); + if (intent.hasExtra(EXTRA_TABLE_HTML)) { + mTableHtml = intent.getStringExtra(EXTRA_TABLE_HTML); + } else { + // 默认创建一个2x2的表格 + mTableHtml = generateDefaultTable(2, 2); + } + + // 初始化WebView + initWebView(); + } + + private void initViews() { + // 标题栏按钮 + ImageButton btnBack = findViewById(R.id.btn_back); + ImageButton btnDone = findViewById(R.id.btn_done); + btnBack.setOnClickListener(this); + btnDone.setOnClickListener(this); + + // 表格操作按钮 + Button btnAddRowAbove = findViewById(R.id.btn_add_row_above); + Button btnAddRowBelow = findViewById(R.id.btn_add_row_below); + Button btnDeleteRow = findViewById(R.id.btn_delete_row); + Button btnAddColLeft = findViewById(R.id.btn_add_col_left); + Button btnAddColRight = findViewById(R.id.btn_add_col_right); + Button btnDeleteCol = findViewById(R.id.btn_delete_col); + + // 设置点击事件 + btnAddRowAbove.setOnClickListener(this); + btnAddRowBelow.setOnClickListener(this); + btnDeleteRow.setOnClickListener(this); + btnAddColLeft.setOnClickListener(this); + btnAddColRight.setOnClickListener(this); + btnDeleteCol.setOnClickListener(this); + } + + private void initWebView() { + mWebView = findViewById(R.id.web_view_table); + + // 配置WebView + WebSettings webSettings = mWebView.getSettings(); + webSettings.setJavaScriptEnabled(true); + webSettings.setDomStorageEnabled(true); + webSettings.setDefaultTextEncodingName("utf-8"); + + // 设置WebViewClient + mWebView.setWebViewClient(new WebViewClient()); + + // 添加JavaScript接口 + mWebView.addJavascriptInterface(new TableEditInterface(), "Android"); + + // 加载表格编辑页面 + loadTableEditor(); + } + + private void loadTableEditor() { + // 构建HTML页面 + StringBuilder htmlBuilder = new StringBuilder(); + htmlBuilder.append("") + .append("") + .append("") + .append("") + .append("") + .append("") + .append("") + .append("") + .append(mTableHtml != null ? mTableHtml : "
列1列2
") + .append("") + .append("") + .append(""); + String html = htmlBuilder.toString(); + + // 加载HTML + mWebView.loadDataWithBaseURL(null, html, "text/html", "utf-8", null); + } + + private String generateDefaultTable(int rows, int cols) { + StringBuilder html = new StringBuilder(); + html.append(""); + + // 表头 + html.append(""); + for (int i = 0; i < cols; i++) { + html.append(""); + } + html.append(""); + + // 数据行 + for (int i = 0; i < rows; i++) { + html.append(""); + for (int j = 0; j < cols; j++) { + html.append(""); + } + html.append(""); + } + + html.append("
列").append(i + 1).append("
"); + return html.toString(); + } + + @Override + public void onClick(View v) { + int id = v.getId(); + + if (id == R.id.btn_back) { + finish(); + } else if (id == R.id.btn_done) { + // 获取表格HTML并返回 + mWebView.evaluateJavascript("Android.onTableHtml(getTableHtml());", null); + } else if (id == R.id.btn_add_row_above) { + mWebView.evaluateJavascript("addRowAbove();", null); + } else if (id == R.id.btn_add_row_below) { + mWebView.evaluateJavascript("addRowBelow();", null); + } else if (id == R.id.btn_delete_row) { + mWebView.evaluateJavascript("deleteRow();", null); + } else if (id == R.id.btn_add_col_left) { + mWebView.evaluateJavascript("addColLeft();", null); + } else if (id == R.id.btn_add_col_right) { + mWebView.evaluateJavascript("addColRight();", null); + } else if (id == R.id.btn_delete_col) { + mWebView.evaluateJavascript("deleteCol();", null); + } + } + + private class TableEditInterface { + @JavascriptInterface + public void onTableHtml(String html) { + // 返回表格HTML + Intent intent = new Intent(); + intent.putExtra(RESULT_TABLE_HTML, html); + setResult(RESULT_OK, intent); + finish(); + } + } +} diff --git a/src/ui/TrashListActivity.java b/src/ui/TrashListActivity.java new file mode 100644 index 0000000..a8f99da --- /dev/null +++ b/src/ui/TrashListActivity.java @@ -0,0 +1,386 @@ +/* + * 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.content.AsyncQueryHandler; +import android.content.ContentResolver; +import android.content.ContentValues; +import android.content.DialogInterface; +import android.content.Intent; +import android.database.Cursor; +import android.net.Uri; +import android.content.ContentUris; +import android.os.Bundle; +import android.util.Log; +import android.view.ActionMode; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.ViewGroup; +import android.widget.AbsListView.MultiChoiceModeListener; +import android.widget.AdapterView; +import android.widget.AdapterView.OnItemClickListener; +import android.widget.AdapterView.OnItemLongClickListener; +import android.widget.Button; +import android.widget.ListView; +import android.widget.TextView; +import android.widget.Toast; +import android.util.SparseBooleanArray; +import java.util.ArrayList; +import java.util.HashSet; +import java.lang.ref.WeakReference; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.model.WorkingNote; +import net.micode.notes.tool.DataUtils; + +import java.util.HashSet; + +public class TrashListActivity extends Activity implements OnClickListener, OnItemLongClickListener { + private static final int TRASH_NOTE_LIST_QUERY_TOKEN = 0; + + private static final String TAG = "TrashListActivity"; + + private BackgroundQueryHandler mBackgroundQueryHandler; + private NotesListAdapter mNotesListAdapter; + private ListView mNotesListView; + private ContentResolver mContentResolver; + private ModeCallback mModeCallBack; + private TextView mTitleBar; + private TextView mEmptyView; + + private Button mBtnRestoreAll; + private Button mBtnDeleteAll; + + private static final String TRASH_SELECTION = NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLDER; + private static final String SORT_ORDER = NoteColumns.MODIFIED_DATE + " DESC"; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.trash_list); + initResources(); + } + + @Override + protected void onStart() { + super.onStart(); + startAsyncTrashListQuery(); + } + + private void initResources() { + mContentResolver = this.getContentResolver(); + mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver(), this); + + mTitleBar = (TextView) findViewById(R.id.tv_title_bar); + mTitleBar.setText(R.string.trash_title); + + mNotesListView = (ListView) findViewById(R.id.trash_list); + mEmptyView = (TextView) findViewById(R.id.trash_empty); + mNotesListView.setEmptyView(mEmptyView); + + mNotesListAdapter = new NotesListAdapter(this); + mNotesListView.setAdapter(mNotesListAdapter); + + mNotesListView.setOnItemClickListener(new OnListItemClickListener()); + mNotesListView.setOnItemLongClickListener(this); + + // 设置多选模式监听器和初始模式 + mModeCallBack = new ModeCallback(); + mNotesListView.setMultiChoiceModeListener(mModeCallBack); + mNotesListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL); + + // 设置底部按钮 + mBtnRestoreAll = (Button) findViewById(R.id.btn_restore_all); + mBtnDeleteAll = (Button) findViewById(R.id.btn_delete_all); + mBtnRestoreAll.setOnClickListener(this); + mBtnDeleteAll.setOnClickListener(this); + + Button btnBack = (Button) findViewById(R.id.btn_back); + btnBack.setOnClickListener(this); + } + + private void startAsyncTrashListQuery() { + mBackgroundQueryHandler.startQuery(TRASH_NOTE_LIST_QUERY_TOKEN, null, Notes.CONTENT_NOTE_URI, + NoteItemData.PROJECTION, TRASH_SELECTION, null, SORT_ORDER); + } + + @Override + public void onClick(View v) { + if (v.getId() == R.id.btn_back) { + finish(); + } else if (v.getId() == R.id.btn_restore_all) { + showConfirmDialog(R.string.restore_all_confirm, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + restoreAllNotes(); + } + }); + } else if (v.getId() == R.id.btn_delete_all) { + showConfirmDialog(R.string.delete_all_confirm, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + deleteAllNotes(); + } + }); + } + } + + private void showConfirmDialog(int messageId, DialogInterface.OnClickListener listener) { + new android.app.AlertDialog.Builder(this) + .setMessage(messageId) + .setPositiveButton("确定", listener) + .setNegativeButton("取消", null) + .show(); + } + + private void restoreAllNotes() { + try { + // 获取所有回收站中的笔记 + Cursor cursor = mContentResolver.query(Notes.CONTENT_NOTE_URI, NoteItemData.PROJECTION, TRASH_SELECTION, null, null); + int count = 0; + if (cursor != null) { + while (cursor.moveToNext()) { + long noteId = cursor.getLong(0); + ContentValues values = new ContentValues(); + values.put(NoteColumns.PARENT_ID, Notes.ID_ROOT_FOLDER); + values.put(NoteColumns.LOCAL_MODIFIED, 1); + + // 直接更新,不使用withSelection条件 + int updated = mContentResolver.update( + ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), + values, + null, // 不使用额外条件,只通过URI指定笔记ID + null); + + if (updated > 0) { + count++; + } + } + cursor.close(); + } + + Toast.makeText(this, getString(R.string.restore_success, count), Toast.LENGTH_SHORT).show(); + } catch (Exception e) { + Log.e(TAG, "Restore all failed: " + e.getMessage()); + Toast.makeText(this, getString(R.string.restore_success, 0), Toast.LENGTH_SHORT).show(); + } + + startAsyncTrashListQuery(); + } + + private void deleteAllNotes() { + try { + // 获取所有回收站中的笔记 + Cursor cursor = mContentResolver.query(Notes.CONTENT_NOTE_URI, NoteItemData.PROJECTION, TRASH_SELECTION, null, null); + HashSet allIds = new HashSet<>(); + if (cursor != null) { + while (cursor.moveToNext()) { + long noteId = cursor.getLong(0); + allIds.add(noteId); + } + cursor.close(); + } + + DataUtils.batchPermanentDeleteNotes(mContentResolver, allIds); + Toast.makeText(this, getString(R.string.delete_success, allIds.size()), Toast.LENGTH_SHORT).show(); + startAsyncTrashListQuery(); + } catch (Exception e) { + Log.e(TAG, "Delete all failed: " + e.getMessage()); + Toast.makeText(this, getString(R.string.delete_success, 0), Toast.LENGTH_SHORT).show(); + startAsyncTrashListQuery(); + } + } + + @Override + public boolean onItemLongClick(AdapterView parent, View view, int position, long id) { + // 长按事件由系统自动处理,因为ListView已经设置了CHOICE_MODE_MULTIPLE_MODAL + // 返回false让系统继续处理事件 + return false; + } + + private class OnListItemClickListener implements OnItemClickListener { + @Override + public void onItemClick(AdapterView parent, View view, int position, long id) { + if (mNotesListView.isItemChecked(position)) { + mNotesListAdapter.setCheckedItem(position, true); + } else { + mNotesListAdapter.setCheckedItem(position, false); + } + } + } + + private class ModeCallback implements ListView.MultiChoiceModeListener, MenuItem.OnMenuItemClickListener { + private ActionMode mActionMode; + + @Override + public boolean onCreateActionMode(ActionMode mode, Menu menu) { + getMenuInflater().inflate(R.menu.trash_note_options, menu); + menu.findItem(R.id.restore).setOnMenuItemClickListener(this); + menu.findItem(R.id.permanent_delete).setOnMenuItemClickListener(this); + + mActionMode = mode; + mNotesListAdapter.setChoiceMode(true); + + // 隐藏底部按钮 + mBtnRestoreAll.setVisibility(View.GONE); + mBtnDeleteAll.setVisibility(View.GONE); + + return true; + } + + @Override + public boolean onPrepareActionMode(ActionMode mode, Menu menu) { + return false; + } + + @Override + public boolean onActionItemClicked(ActionMode mode, MenuItem item) { + if (item.getItemId() == R.id.restore) { + restoreSelectedNotes(); + mode.finish(); + return true; + } else if (item.getItemId() == R.id.permanent_delete) { + deleteSelectedNotes(); + mode.finish(); + return true; + } + return false; + } + + @Override + public void onDestroyActionMode(ActionMode mode) { + mActionMode = null; + mNotesListAdapter.setChoiceMode(false); + + // 显示底部按钮 + mBtnRestoreAll.setVisibility(View.VISIBLE); + mBtnDeleteAll.setVisibility(View.VISIBLE); + } + + @Override + public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) { + int checkedCount = mNotesListView.getCheckedItemCount(); + mode.setTitle(getString(R.string.selected_count, checkedCount)); + // 更新adapter中的选择状态 + mNotesListAdapter.setCheckedItem(position, checked); + } + + @Override + public boolean onMenuItemClick(MenuItem item) { + return onActionItemClicked(mActionMode, item); + } + } + + private void restoreSelectedNotes() { + HashSet selectedIds = getSelectedNoteIds(); + if (selectedIds.isEmpty()) { + Toast.makeText(this, R.string.no_note_selected, Toast.LENGTH_SHORT).show(); + return; + } + + int count = 0; + try { + for (Long noteId : selectedIds) { + ContentValues values = new ContentValues(); + values.put(NoteColumns.PARENT_ID, Notes.ID_ROOT_FOLDER); + values.put(NoteColumns.LOCAL_MODIFIED, 1); + + // 直接更新,不使用withSelection条件 + int updated = mContentResolver.update( + ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), + values, + null, // 不使用额外条件,只通过URI指定笔记ID + null); + + if (updated > 0) { + count++; + } + } + + Toast.makeText(this, getString(R.string.restore_success, count), Toast.LENGTH_SHORT).show(); + } catch (Exception e) { + Log.e(TAG, "Restore selected failed: " + e.getMessage()); + Toast.makeText(this, getString(R.string.restore_success, count), Toast.LENGTH_SHORT).show(); + } + + startAsyncTrashListQuery(); + } + + private void deleteSelectedNotes() { + HashSet selectedIds = getSelectedNoteIds(); + if (selectedIds.isEmpty()) { + Toast.makeText(this, R.string.no_note_selected, Toast.LENGTH_SHORT).show(); + return; + } + + DataUtils.batchPermanentDeleteNotes(mContentResolver, selectedIds); + Toast.makeText(this, getString(R.string.delete_success, selectedIds.size()), Toast.LENGTH_SHORT).show(); + startAsyncTrashListQuery(); + } + + private HashSet getSelectedNoteIds() { + HashSet selectedIds = new HashSet(); + Cursor cursor = mNotesListAdapter.getCursor(); + + if (cursor != null) { + // 遍历ListView中的所有项,检查是否被选中 + for (int i = 0; i < mNotesListAdapter.getCount(); i++) { + if (mNotesListView.isItemChecked(i)) { + // 移动游标到指定位置 + if (cursor.moveToPosition(i)) { + // 从Cursor中获取笔记ID,使用NoteColumns.ID对应的列索引 + // 由于我们使用NoteItemData.PROJECTION进行查询,所以ID列的索引是0 + long noteId = cursor.getLong(0); + selectedIds.add(noteId); + } + } + } + } + return selectedIds; + } + + private static final class BackgroundQueryHandler extends AsyncQueryHandler { + private final WeakReference mActivity; + + public BackgroundQueryHandler(ContentResolver cr, TrashListActivity activity) { + super(cr); + mActivity = new WeakReference<>(activity); + } + + @Override + protected void onQueryComplete(int token, Object cookie, Cursor cursor) { + TrashListActivity activity = mActivity.get(); + if (activity == null) { + return; + } + + switch (token) { + case TRASH_NOTE_LIST_QUERY_TOKEN: + activity.mNotesListAdapter.changeCursor(cursor); + break; + default: + Log.w(TAG, "Unknown query token: " + token); + } + } + } +} -- 2.34.1