編輯:關於 Android 程式設計
有些客製需求要求在首次開機時預置幾筆聯絡人(例如客服專線、公司總機),而且不允許使用者編輯或刪除。以下分兩部分說明:先建立預置資料,再逐一關掉相關的編輯與刪除入口。
針對 GB2、GB3 等版本,只需在 AbstractStartSIMService 類別開頭加上定義:
public static final int INSERT_NUMBER_COUNT = 4; // 預置筆數
public static final String[] defaultNumbers = {
"xxxx", "xxxx", "xxxx", "xxxx"
}; // 預置號碼
public static final String[] defaultNames = {
"xxxxx", "xxxxx", "xxxxx", "xxxxx"
}; // 預置姓名
這三個常數是後續所有判斷的基礎——「哪些聯絡人是預置的」全靠比對這兩個陣列來決定。因此修改數量時務必同步調整陣列內容,否則會出現陣列越界或比對失準。
(1)長按選單:隱藏編輯與刪除
在 onCreateContextMenu() 中,原本這段會加上編輯與刪除項目:
if (addEditAndDelete && simHasImported) {
menu.add(0, MENU_ITEM_EDIT, 0, R.string.menu_editContact);
menu.add(0, MENU_ITEM_DELETE, 0, R.string.menu_deleteContact);
}
在它之前插入判斷,若長按的是預置聯絡人就把旗標關掉:
for (int i = 0; i < AbstractStartSIMService.INSERT_NUMBER_COUNT; i++) {
if (header.equals(AbstractStartSIMService.defaultNames[i])) {
addEditAndDelete = false;
}
}
(2)點擊事件:攔下進入編輯的入口
在 onListItemClick() 的深層 if-else 結構中,找到處理刪除模式的區塊,加入對預置聯絡人的判斷:
if (mMode == MODE_DEFAULT && mDeleteState) {
try {
CheckBox cb = rootLayout.getCheckBox();
contactId = cursor.getInt(
cursor.getColumnIndexOrThrow(Contacts.ID));
String displayName = cursor.getString(
SUMMARY_DISPLAY_NAME_PRIMARY_COLUMN_INDEX);
boolean isDefaultContact = false;
if (!TextUtils.isEmpty(displayName)) {
for (int i = 0; i < AbstractStartSIMService.INSERT_NUMBER_COUNT; i++) {
if (displayName.equals(AbstractStartSIMService.defaultNames[i])) {
isDefaultContact = true;
break;
}
}
}
if (cbPrevState) {
cb.setChecked(false);
if (isDefaultContact) {
cb.setVisibility(View.INVISIBLE);
}
} else {
if (!isDefaultContact) {
cb.setChecked(true);
cb.setVisibility(View.VISIBLE);
indicate = cursor.getInt(
cursor.getColumnIndexOrThrow(RawContacts.INDICATE_PHONE_SIM));
mToBeDeletedContacts.put(contactId, indicate);
long indexInSim = cursor.getLong(
cursor.getColumnIndexOrThrow(Contacts.INDEX_IN_SIM));
mToBeDeletedContactsIndexInSim.put(contactId, indexInSim);
} else {
cb.setChecked(false);
cb.setVisibility(View.INVISIBLE);
}
}
if (mSelected == mAllContacts.size()) {
mSelectAllToDel = true;
if (!isDefaultContact) {
mSelectAllBox.setChecked(mSelectAllToDel);
} else {
mSelectAllBox.setChecked(false);
mSelectAllBox.setVisibility(View.INVISIBLE);
}
mSelectAllButton.setText(mUnSelectText);
}
} catch (Exception e) {
e.printStackTrace();
}
}
這裡做了三件事:預置聯絡人的核選方塊設為 INVISIBLE(不是 GONE,保留佔位以免列表錯位)、不把它加入待刪集合、以及全選時自動把它排除。
(3)查詢完成:把預置項排除於待刪清單
在 onQueryComplete() 中:
if (activity.mDeleteState) {
...
if (tmpCursor.moveToFirst()) {
do {
...
long indexInSim = tmpCursor.getInt(
tmpCursor.getColumnIndexOrThrow(Contacts.INDEX_IN_SIM));
String displayName = tmpCursor.getString(
SUMMARY_DISPLAY_NAME_PRIMARY_COLUMN_INDEX);
boolean isDefaultContact = false;
if (!TextUtils.isEmpty(displayName)) {
for (int i = 0; i < AbstractStartSIMService.INSERT_NUMBER_COUNT; i++) {
if (displayName.equals(AbstractStartSIMService.defaultNames[i])) {
isDefaultContact = true;
}
}
}
if (!isDefaultContact) {
mAllContacts.put(currentID, indicate);
mAllContactsIndexInSim.put(currentID, indexInSim);
}
} while (tmpCursor.moveToNext());
}
}
這一層是防線中最重要的一環:即使 UI 層被繞過,只要資料沒進 mAllContacts,後續的刪除作業就動不到它。
(4)列表綁定:隱藏核選方塊
在 bindView() 中:
if (mMode == MODE_DEFAULT && mDeleteState) {
long currentID = cursor.getLong(SUMMARY_ID_COLUMN_INDEX);
String displayName = cursor.getString(
SUMMARY_DISPLAY_NAME_PRIMARY_COLUMN_INDEX);
CheckBox cb = view.getCheckBox();
if (cb != null) {
cb.setVisibility(View.VISIBLE);
for (int i = 0; i < AbstractStartSIMService.INSERT_NUMBER_COUNT; i++) {
if (displayName.equals(AbstractStartSIMService.defaultNames[i])) {
cb.setVisibility(View.INVISIBLE);
break;
}
}
}
}
(1)移除單筆號碼的刪除選項
在 onCreateContextMenu() 中,把直接加上刪除項目的那一行改為條件式:
int count = 0;
for (int i = 0; i < AbstractStartSIMService.INSERT_NUMBER_COUNT; i++) {
if (entry.data.equals(AbstractStartSIMService.defaultNumbers[i])) {
count++;
}
}
if (count == 0) {
menu.add(0, MENU_ITEM_REMOVE_NUMBER, 0, R.string.menu_remove_number);
}
(2)隱藏編輯與刪除聯絡人
在 onPrepareOptionsMenu() 中,於設定選單可見性的兩行之前插入判斷:
if (hasRawContact) {
for (Entity contactEntity : mEntities) {
for (NamedContentValues subValue : contactEntity.getSubValues()) {
final ContentValues entryValues = subValue.values;
final String mimeType = entryValues.getAsString(Data.MIMETYPE);
final String data = entryValues.getAsString(Data.DATA1);
int count = 0;
for (int i = 0; i < AbstractStartSIMService.INSERT_NUMBER_COUNT; i++) {
if (data.equals(AbstractStartSIMService.defaultNumbers[i])
|| data.equals(AbstractStartSIMService.defaultNames[i])) {
count++;
}
}
if (count != 0) {
addEditAndDelete = false;
}
}
}
}
menu.findItem(R.id.menu_edit).setVisible(addEditAndDelete);
menu.findItem(R.id.menu_delete).setVisible(addEditAndDelete);
如果只擋刪除,使用者仍可以新建一個姓名或號碼與預置項完全相同的聯絡人,之後刪除時就會誤判。因此編輯頁也要加防線。
(1)EditContactActivity.java
開頭引入套件並定義旗標:
import android.provider.ContactsContract.CommonDataKinds.StructuredName; import com.android.contacts.AbstractStartSIMService; import android.widget.Toast; private boolean sameNumberExist = false; private boolean sameNameExist = false;
把 onBackPressed() 裡的儲存呼叫換成帶檢核的版本:
doSaveWithCheckField();
if (sameNumberExist || sameNameExist) {
finish();
}
接著在 doSaveWithCheckField() 中加入比對。姓名在 ContactsContract 中是獨立的一筆 MIME(StructuredName),要另外取出:
ArrayList<ValuesDelta> list = null;
ArrayList<ValuesDelta> listName = null;
if (mState != null && mState.size() > 0) {
...
listName = mState.get(0).getMimeEntries(StructuredName.CONTENT_ITEM_TYPE);
}
String name1 = null;
String name2 = null;
String name = null;
sameNumberExist = false;
sameNameExist = false;
// 先檢核號碼
if (list != null) {
for (ValuesDelta delta : list) {
String num = delta.getAsString(Data.DATA1);
if (!TextUtils.isEmpty(num)) {
for (int i = 0; i < AbstractStartSIMService.INSERT_NUMBER_COUNT; i++) {
if (num.equals(AbstractStartSIMService.defaultNumbers[i])) {
sameNumberExist = true;
break;
}
}
if (!sameNumberExist) {
numberList.add(num);
}
}
}
}
// 號碼沒問題才檢核姓名
if (listName != null && !sameNumberExist) {
for (ValuesDelta delta : listName) {
name1 = delta.getAsString(Data.DATA2);
name2 = delta.getAsString(Data.DATA3);
if (name2 == null && name1 != null) {
name = name1;
} else if (name2 != null && name1 == null) {
name = name2;
} else if (name2 != null && name1 != null) {
name = name2 + " " + name1;
}
if (!TextUtils.isEmpty(name)) {
for (int i = 0; i < AbstractStartSIMService.INSERT_NUMBER_COUNT; i++) {
if (name.equals(AbstractStartSIMService.defaultNames[i])) {
sameNameExist = true;
break;
}
}
}
}
}
bundle.putCharSequenceArrayList(KEY_PHONE_NUMBER, numberList);
if (!hasCheckDuplicatePlugin && !sameNumberExist && !sameNameExist) {
doSaveAction(SAVE_MODE_DEFAULT);
} else {
Toast.makeText(this,
"Can not save a number or name the same as the default contact!",
Toast.LENGTH_LONG).show();
}
這裡有個細節值得注意:Data.DATA2 與 DATA3 分別是名字與姓氏,兩者可能任一為 null,所以要組出完整姓名再比對。只比其中一項會漏判。
(2)EditSimContactActivity.java
引入套件、定義旗標,並多寫一個方法做集中檢核:
import com.android.contacts.AbstractStartSIMService;
import android.widget.Toast;
private boolean hasSameNumber = false;
private boolean hasSameName = false;
private void hasSameNameOrNumberAsDefaultContacts() {
hasSameNumber = false;
hasSameName = false;
updateName = edit_contact_name.getText().toString();
updatephone = edit_phone_numbers.getText().toString();
if (!TextUtils.isEmpty(updatephone)) {
for (int i = 0; i < AbstractStartSIMService.INSERT_NUMBER_COUNT; i++) {
if (updatephone.equals(AbstractStartSIMService.defaultNumbers[i])) {
hasSameNumber = true;
break;
}
}
}
if (!TextUtils.isEmpty(updateName)) {
for (int i = 0; i < AbstractStartSIMService.INSERT_NUMBER_COUNT; i++) {
if (updateName.equals(AbstractStartSIMService.defaultNames[i])) {
hasSameName = true;
break;
}
}
}
}
然後在 onClick() 的完成按鈕分支與 onBackPressed() 中呼叫它:
case R.id.btn_sim1_done: {
btn1.setClickable(false);
hasSameNameOrNumberAsDefaultContacts();
if (!hasSameNumber && !hasSameName) {
doSaveAction(mMode);
} else {
btn1.setClickable(true);
Toast.makeText(this,
"Can not save a number or name the same as the default contact!",
Toast.LENGTH_LONG).show();
}
break;
}
@Override
public void onBackPressed() {
hasSameNameOrNumberAsDefaultContacts();
if (!hasSameNumber && !hasSameName) {
doSaveAction(mMode);
} else {
Toast.makeText(this,
"Can not save a number or name the same as the default contact!",
Toast.LENGTH_LONG).show();
finish();
}
}
上面這一大套改動,本質上是在「用名稱比對來辨識特定資料」。這個做法很脆弱,值得先想清楚再動手。
主要風險有三個。第一,使用者只要把姓名多打一個空白、或在號碼前後加上不易察覺的字元,就能繞過所有檢核,然後你就可以刪掉那筆「不該被刪」的聯絡人了。第二,反過來說,如果使用者本來就有親戚叫「客服專線」這種罕見情況之外的正常姓名恰好與預置項同名,他會莫名無法儲存自己的聯絡人。第三,這套邏輯散落在五、六個檔案裡,任何一處漏改就是漏洞,後續維護成本很高。
更穩健的做法是換一個辨識維度。既然預置聯絡人是你自己寫入的,就在寫入時為它們打上一個只有系統知道的標記——例如在 Data 表的某個自訂欄位寫入旗標,或利用 RAW_CONTACT_ID 記錄下來。後續所有判斷都改用這個 ID 或旗標,而不是比對使用者可見的文字。這樣既不會誤傷正常使用者,也不必在五個檔案裡重複相同的迴圈。
如果確實無法改動資料結構,至少應該把「判斷是否為預置聯絡人」抽成一個共用的靜態方法(例如 AbstractStartSIMService.isDefaultContact(String name, String number)),讓各處呼叫同一份邏輯。這麼改之後,日後調整判斷條件只需動一個地方,不必再翻遍整個聯絡人應用。
【讀書筆記】View 的事件體系:從基礎知識到滑動衝突
一、View 的基礎知識 View 是 Android 中所有視覺元件(原文作「空間」,實為 View)的基類,理解它是掌握事件體系的起點。 1. View 的位置參數
用 ViewFlipper 實現 Android 螢幕動畫切換
ViewFlipper 是一個專門用於「多子視圖輪番展示」的容器。它同一時刻只顯示一個子 View,切換時可以套用進出動畫,配上滑動手勢判斷,就能做出類似幻燈片的翻頁
Android AlertDialog 五種對話框完整實戰:確認、單選、多選、列表與自定義
幾乎每一款 App 都離不開對話框:刪除前的二次確認、性別選擇、興趣勾選、部門挑選,甚至是帶輸入框與圖片的「自定義彈窗」。本文用一個可直接跑起來的示例,把 AlertDi
堅果手機U1流暢度提升法 動畫速度自己調
堅果手機自亮相以來就頗受關注,相信已有不少朋友入手。由於動畫縮放速度的設定不同,滑動介面時的觀感也會有差異,有些人便覺得手機不夠順。下面小編就來介紹堅果U1的流暢度優化方