編輯:關於 Android 程式設計
這篇整理實作「手機安全衛士」第二天會碰到的幾個關鍵技術:自訂可獲焦元件、自訂組合控制項、控制項內部的事件傳遞問題、自訂屬性、自訂對話框,以及密碼的 MD5 加密。都是動手做功能時必然會撞上的細節。
Ctrl + T 可以開啟型別層級圖,直接看出這個類別的所有父類別與子類別,讀源碼時非常順手。Ctrl + D 則是快速刪除整行。
如果多個畫面共用同一套版面風格,不要複製貼上,而是在 styles.xml 中定義一個 style,各處引用即可,能避免大量重複程式碼。
文字要跑起來,ellipsize 設為 marquee 是滾動效果,設為 none 則不動。但要真正滾動,還必須讓元件取得焦點:
android:focusable="true" android:focusableInTouchMode="true"
與其每個地方都寫那兩個屬性,不如做一個自訂元件。流程是:建立一個類別繼承 TextView,重寫其建構子,再重寫 isFocused() 永遠回傳 true。
public class FocusTextView extends TextView {
// 透過 Java 程式碼建立元件時使用
public FocusTextView(Context context) {
super(context);
}
// 由系統呼叫(帶屬性 + 上下文環境)
public FocusTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
// 由系統呼叫(帶屬性 + 上下文環境 + 版面檔中定義的樣式)
public FocusTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
// 重寫取得焦點的方法,由系統呼叫,讓它預設就能獲得焦點
@Override
public boolean isFocused() {
return true;
}
}
三個建構子缺一不可:系統在解析版面檔時,會依屬性的複雜度選擇不同的建構子,少寫一個就會在執行期拋出例外。
使用時,把該類別的全限定名稱當成 XML 標籤名稱,其餘屬性用法與 TextView 完全相同。
GridView 的用法與 ListView 類似:設定列數(例如 3 列)、準備資料(模組名稱與圖片)、搭配一個 Adapter 填充。

一個實務提醒:設定 Adapter 時,版面檔中的元件一定要置中,否則每格內容會歪一邊。
設定圖片可以用 ImageView 的 setBackgroundResource(int id),傳入 R.drawable.xxx 即可。
另外,若只需要畫一條分隔線,直接放一個 <View> 並設定高度與背景色就好,不必特地找圖片。
當某段版面結構會在多處重複出現,應該把它抽成一個類別來管理,之後只要 new 出對應物件就能使用。三個步驟:
RelativeLayout。View.inflate() 把該版面載入進來。
public class SettingItemView extends RelativeLayout {
private TextView tv_des;
private CheckBox cb_box;
public SettingItemView(Context context) {
this(context, null);
}
public SettingItemView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SettingItemView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// xml ---> view:把設定畫面的一個項目轉成 View 物件
// 最後一個參數寫 this,才能把抽出的元件掛到目前這個 ViewGroup 上
View.inflate(context, R.layout.setting_item_view, this);
// 等價寫法:
// View view = View.inflate(context, R.layout.setting_item_view, null);
// this.addView(view);
tv_des = (TextView) findViewById(R.id.tv_des);
cb_box = (CheckBox) findViewById(R.id.cb_box);
}
// CheckBox 是否勾選,決定這個項目是否開啟
public boolean isCheck() {
return cb_box.isChecked();
}
// 切換勾選狀態
public void setCheck(boolean isCheck) {
cb_box.setChecked(isCheck);
}
}
這裡有兩個關鍵點。第一,三個建構子都要呼叫最後一個,確保不論系統怎麼建立物件,初始化邏輯都會執行。第二,View.inflate() 的最後一個參數必須是 this——它的意義是「把版面直接掛到這個 ViewGroup 底下」,而不是回傳一個獨立 View 再由外部 addView。
設定畫面的點擊事件由 SettingActivity 的版面取得,再往下傳給 SettingItemView。問題出在:
SettingItemView 的非 CheckBox 區域 → 由 SettingItemView 自己回應。SettingItemView 的 onClick() 不會被觸發,狀態也就不會切換。這兩條路徑行為不一致,使用者會覺得「點左邊有效、點右邊沒反應」。
解法有兩種:
這裡採用第一種,做法是不讓 CheckBox 回應點擊事件:
// 在 SettingItemView 的建構子中關閉 CheckBox 的可點擊與可獲焦 cb_box.setClickable(false); cb_box.setFocusable(false);
這樣點擊 CheckBox 區域時,事件會穿透到外層,由 SettingItemView 統一處理,兩處行為就一致了。

勾選狀態需要跨啟動保留,這時用 SharedPreferences 最合適。封裝成一個工具類別:
public class SpUtil {
private static SharedPreferences sp;
/**
* 寫入 boolean 至 sp
* @param ctx 上下文環境
* @param key 儲存節點名稱
* @param value 節點的值
*/
public static void putBoolean(Context ctx, String key, boolean value) {
if (sp == null) {
sp = ctx.getSharedPreferences("config", Context.MODE_PRIVATE);
}
sp.edit().putBoolean(key, value).commit();
}
/**
* 從 sp 讀取 boolean
* @param defValue 沒有此節點時的預設值
* @return 預設值或讀取到的結果
*/
public static boolean getBoolean(Context ctx, String key, boolean defValue) {
if (sp == null) {
sp = ctx.getSharedPreferences("config", Context.MODE_PRIVATE);
}
return sp.getBoolean(key, defValue);
}
}
key 會在多處重複使用,字串寫錯不會編譯報錯、卻會造成資料讀不到,因此應該集中管理成常數:
public class ConstantValue {
/** 是否開啟自動更新 */
public static final String OPEN_UPDATE = "open_update";
/** 是否設定密碼 */
public static final String MOBILE_SAFE_PSD = "mobile_safe_psd";
}
在 OnClickListener 內部要呼叫 SpUtil 時,傳入的 Context 不能寫 this:
private void initUpdate() {
final SettingItemView sivUpdate = (SettingItemView) findViewById(R.id.siv_update);
// 取得已儲存的開關狀態,用於顯示
boolean openUpdate = SpUtil.getBoolean(this, ConstantValue.OPEN_UPDATE, false);
sivUpdate.setCheck(openUpdate);
sivUpdate.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 取出目前狀態並反轉
boolean isCheck = sivUpdate.isCheck();
sivUpdate.setCheck(!isCheck);
// 這裡必須用 getApplicationContext(),不能寫 this
SpUtil.putBoolean(getApplicationContext(),
ConstantValue.OPEN_UPDATE, !isCheck);
}
});
}
原因很單純:在匿名內部類別當中,this 指的是這個 OnClickListener 物件,而不是外層的 Activity。若把監聽器抽成獨立類別甚至靜態類別,還會連 Activity 都拿不到,這時就必須用 getApplicationContext() 或改用弱參照持有 Activity。
設定畫面有多個項目,每個的標題、說明文案都不同。硬寫成多個版面檔太笨,正解是自訂屬性。
第一步:看系統怎麼做。SDK 中的 platforms/android-*/data/res/values/attrs.xml 定義了所有內建屬性,照著它的格式寫即可。
第二步:在專案的 res/values/attrs.xml 中宣告。
<declare-styleable name="SettingItemView">
<attr name="destitle" format="string" />
<attr name="deson" format="string" />
<attr name="desoff" format="string" />
</declare-styleable>
第三步:宣告命名空間後使用。Android 之所以能用 android: 屬性,是因為版面檔宣告了 xmlns:android="https://schemas.android.com/apk/res/android",等同於連到系統資源目錄下已定義的屬性。自訂屬性同理,只是命名空間要換成自己的包名:
<com.itheima.mobilesafe.view.SettingItemView
xmlns:mobilesafe="https://schemas.android.com/apk/res/com.itheima.mobilesafe"
android:id="@+id/siv_update"
android:layout_width="match_parent"
android:layout_height="wrap_content"
mobilesafe:destitle="自動更新設定"
mobilesafe:desoff="自動更新已關閉"
mobilesafe:deson="自動更新已開啟" />
第四步:在建構子中讀取。
private void initAttrs(AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SettingItemView);
mDestitle = a.getString(R.styleable.SettingItemView_destitle);
mDeson = a.getString(R.styleable.SettingItemView_deson);
mDesoff = a.getString(R.styleable.SettingItemView_desoff);
a.recycle(); // TypedArray 為共用資源,務必歸還
}
// 依勾選狀態決定要顯示哪一段描述
private void updateDescription(boolean isCheck) {
tv_des.setText(isCheck ? mDeson : mDesoff);
}
所以 setCheck() 除了切換 CheckBox,也必須呼叫 updateDescription(),標題則在建構子中直接設定一次即可。

設定密碼時需要一個自訂樣式的對話框。步驟是:建立 Builder → 建立 AlertDialog → 用 setView() 指定自訂版面。
這裡有個常見的空指標錯誤:如果在 onCreate() 中直接用 findViewById() 找對話框裡的按鈕,會找不到而拋出 NullPointerException。因為 findViewById() 是從目前控制項所屬的版面往下找,而對話框的按鈕在另一個 View 樹上,必須用 view.findViewById()。
/**
* 設定密碼對話框
*/
private void showSetPsdDialog() {
// 因為要自訂對話框的呈現樣式,所以需要 dialog.setView(view)
// view 是由自己編寫的 xml 轉成的 View 物件
Builder builder = new AlertDialog.Builder(this);
final AlertDialog dialog = builder.create();
final View view = View.inflate(this, R.layout.dialog_set_psd, null);
dialog.setView(view);
dialog.show();
Button btSubmit = (Button) view.findViewById(R.id.bt_submit);
Button btCancel = (Button) view.findViewById(R.id.bt_cancel);
btSubmit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
EditText etSetPsd = (EditText) view.findViewById(R.id.et_set_psd);
EditText etConfirmPsd = (EditText) view.findViewById(R.id.et_confirm_psd);
String psd = etSetPsd.getText().toString();
String confirmPsd = etConfirmPsd.getText().toString();
if (!TextUtils.isEmpty(psd) && !TextUtils.isEmpty(confirmPsd)) {
if (psd.equals(confirmPsd)) {
// 進入手機防盜模組,開啟新的 Activity
startActivity(new Intent(getApplicationContext(), TestActivity.class));
dialog.dismiss(); // 跳轉後記得關閉對話框
SpUtil.putString(getApplicationContext(),
ConstantValue.MOBILE_SAFE_PSD, psd);
} else {
ToastUtil.show(getApplicationContext(), "確認密碼錯誤");
}
} else {
ToastUtil.show(getApplicationContext(), "請輸入密碼");
}
}
});
btCancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
TextUtils.isEmpty(str) 是個好用的小工具,同時判斷空字串與 null,可以省下不少 if 判斷。
密碼以明文存進 SharedPreferences 是不合格的。MD5 能把任意字串轉成固定的 32 位十六進位字串,且不可逆。

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Md5Util {
/**
* 給指定字串依 MD5 演算法加密
* @param psd 需要加密的密碼
*/
public static String encoder(String psd) {
try {
// 1. 指定加密演算法類型
MessageDigest digest = MessageDigest.getInstance("MD5");
// 2. 把字串轉為 byte 陣列後進行雜湊運算
byte[] bs = digest.digest(psd.getBytes());
// 3. 遍歷結果,拼成 32 位十六進位字串(固定寫法)
StringBuffer sb = new StringBuffer();
for (byte b : bs) {
int i = b & 0xff; // 轉為無負號整數
String hexString = Integer.toHexString(i); // 轉 16 進位
if (hexString.length() < 2) {
hexString = "0" + hexString; // 不足兩位補 0
}
sb.append(hexString);
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
}
兩個細節值得留意:b & 0xff 是為了把 Java 有號的 byte 轉成 0–255 的無號值,少了這步會產生錯誤結果;補零是因為 Integer.toHexString() 會把 0x0f 輸出成單一字元 f,導致長度不足 32 位。
加鹽(salt):實務上不會直接對密碼做 MD5,而是先拼接一段隨機字串再加密,例如 encoder("123" + "abc")。這樣即使資料庫外洩、攻擊者拿著彩虹表反查,也難以還原原始密碼。
最後必須誠實說明:MD5 已被證明存在碰撞弱點,不適合作為現代密碼儲存的方案。它可以用在「校驗檔案完整性」這類不需要抗碰撞的場景。若 purpose 是保存使用者密碼,應改用 bcrypt、scrypt 或 Argon2 這類專門設計的慢速雜湊函式,並搭配隨機鹽值。
最後補上開頭提到的技巧。把重複的屬性抽成樣式:
<style name="TitleStyle">
<item name="android:gravity">center</item>
<item name="android:textSize">20sp</item>
<item name="android:textColor">#000</item>
<item name="android:padding">10dp</item>
<item name="android:background">#0f0</item>
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
</style>
版面檔中只要寫 style="@style/TitleStyle" 即可套用。UI 微調時只需改一處,不必逐個畫面替換。
Android 入門:TabHost 與 TabWidget 實例解析
本文介紹 Android 的 Tab 控件。Tab 能起到分頁效果,讓單個螢幕容納更豐富的內容,但相對地也會增加開發的複雜度,建議在有真正需要時才使用。 Android
Android 2D 繪圖入門:用 Canvas 與 Paint 畫出你的第一個自定義 View
從自定義 View 開始 在 Android 中,只要想畫出圓形、矩形、文字,甚至更複雜的自訂介面,最基礎的入口就是自定義 View。系統會在合適的時機呼叫 onDraw
Android Activity 的四種 launchMode 啟動模式詳解(standard/singleTop/singleTask/singleInstance)
這次要談的是 Activity 的四種啟動模式,也就是 launchMode 屬性。它決定了一個 Activity 該如何被載入、要不要建立新實例,而這件事在多頁面跳轉的
在 Android Studio 中熟練操作 Git:從啟用到分享
版本控制是開發流程中不可或缺的一環。不論個人還是團隊,把版本控制用順,專案開發會輕意很多。Android Studio 內建了版本控制整合,目前支援 CVS、SVN、Gi