編輯:關於 Android 程式設計
當標準 Button 無法滿足需求時,繼承 Button 自行繪製是常見解。以下七點是實作自訂按鈕時會用到的關鍵技巧。
直接呼叫 performClick(),內部會觸發 View.OnClickListener,這也是自訂 View 提供「可被點擊」語意的標準做法。
放在 res/drawable 中的 png、gif 等圖形資源,載入時實際都是 BitmapDrawable 物件。若要自繪,應該直接轉型以便調用 drawBitmap():
mIconAccept = (BitmapDrawable) context.getResources()
.getDrawable(R.drawable.latebutton_ok);
圖片實際尺寸可能與資源檔標示的不同,程式碼中應透過下列方法取得真實長寬,而不是寫死數字:
mIconAccept.getIntrinsicWidth() mIconAccept.getIntrinsicHeight()
相對於直接繼承 View 從零繪製,繼承 Button 可以沿用系統的樣式、padding 計算與無障礙屬性,多數情況省事不少。
不必急著自訂 attribute,Android 現成的 android:text 就能勝任。在 XML 中宣告:
<com.friendlocation.LateButton
android:id="@+id/lateButton1"
android:layout_width="300dp"
android:layout_height="36dp"
android:text="查詢" />
並在建構子中讀取。注意 namespace 要寫完整網址,不能只寫 android:
public LateButton(Context context, AttributeSet attrs) {
super(context, attrs);
mText = attrs.getAttributeValue(
"https://schemas.android.com/apk/res/android", "text");
if (mText == null) mText = "Default Text";
}
Layout Editor 預覽時也會呼叫自訂 View 的建構子。若此時去載入資源或做耗時運算,會拖慢預覽甚至讓編輯器報錯。用 isInEditMode() 隔開即可:
public LateButton(Context context, AttributeSet attrs) {
super(context, attrs);
if (!this.isInEditMode()) {
mIconAccept = (BitmapDrawable) context.getResources()
.getDrawable(R.drawable.latebutton_icon);
}
}
若不確定 XML 裡有哪些屬性,可以逐一列印出來除錯:
for (int i = 0; i < attrs.getAttributeCount(); i++) {
String name = attrs.getAttributeName(i);
String value = attrs.getAttributeValue(i);
if (name.equals("text"))
mText = value;
}
這七點合起來,基本涵蓋了一個實用自訂按鈕所需的要素:資源轉型、尺寸取得、屬性解析、編輯模式相容與點擊回饋。
在 Gradle 項目中添加 JNI 生成文件(.so 文件)
對於把項目從 Eclipse 遷移到 Android Studio 的開發者來說,如何正確添加 .jar 文件和 .so 文件,無疑是一個既重要又令人頭疼的問題! 在最新
Android Fragment 完全指南:生命週期、事務管理與 Activity 通訊
Fragment 是 Activity 界面中的一部分,也是一種可獨立描述的行为單元。把多個 Fragment 組進同一個 Activity,就能拼出一個多面板的複合界面
Android 圖片三級緩存設計:記憶體、檔案與網路
為什麼需要圖片緩存在 Android 應用中,圖片往往是最佔用記憶體與網路資源的內容之一。如果每次都從網路重新下載,不僅增加流量消耗,也會讓列表滾動變得卡頓。因此,合理的
Android 安卓 VPN 設置 L2TP 圖解教學
以下以圖文步驟教學如何在 Android 手機上設置 L2TP/IPSec PSK 類型的 VPN。 第一步:打開手機主選單,選擇「設定」,然後選擇「無線和網絡」。 第