編輯:關於 Android 程式設計
自定義 View 是 Android 開發的必備技能。實作路線大致有三種,而「讓自定義 View 能在 XML 中設定屬性」則是從玩具走向可複用元件關鍵的一步。
public CustomView2(Context context) {
// 純程式碼 new 出來時使用
super(context);
}
public CustomView2(Context context, AttributeSet attrs) {
// 在 XML 中使用時,系統呼叫的是這個
super(context, attrs);
}
public CustomView2(Context context, AttributeSet attrs, int defStyle) {
// 需要指定預設樣式時,由上一個建構子手動轉呼
super(context, attrs, defStyle);
}
其中 attrs 代表該 View 的屬性集合,defStyle 是預設屬性資源集的 id。
在 res/values/attrs.xml 中用 declare-styleable 宣告:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="customview">
<!-- 屬性可以是 string 或資源引用,如 @drawable/img -->
<!-- 支援的型別:string、boolean、integer、float、color、dimension、fraction -->
<!-- 顏色寫法:#rgb / #rrggbb / #argb / #aarrggbb -->
<!-- enum:單選整數值 -->
<attr name="season">
<enum name="spring" value="1" />
<enum name="summer" value="2" />
</attr>
<!-- flag:可用 | 組合成位元 -->
<attr name="flags">
<flag name="spring" value="4" />
<flag name="summer" value="8" />
</attr>
</declare-styleable>
</resources>
<LinearLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:custom="https://schemas.android.com/apk/res/com.stone"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- xmlns:custom 指向 com.stone 套件,對應 declare-styleable 中的屬性 -->
<LinearLayout
android:layout_width="150dp"
android:layout_height="150dp">
<com.stone.view.CustomView1
android:layout_width="wrap_content"
android:layout_height="fill_parent"
custom:score="60%"
custom:rotation="-45"
custom:color="#3f00ff00" />
</LinearLayout>
<com.stone.view.CustomView2
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<!-- 若自定義 view 是內部類別,要用 view 標籤並指定 class 屬性 -->
<view
android:layout_width="wrap_content"
android:layout_height="wrap_content"
class="com.stone.view.CustomView1$Custom1" />
</LinearLayout>
順帶一提,wrap_content 對應的測量模式是 MeasureSpec.AT_MOST,match_parent 則是 MeasureSpec.EXACTLY,這在自訂 onMeasure 時會用到。
public CustomView1(Context context, AttributeSet attrs) {
super(context, attrs);
// 系統會自動在 declare-styleable 的 name 前加上套件前綴
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.customview1);
int color = array.getColor(R.styleable.customview1_color, Color.WHITE);
float rotation = array.getFloat(R.styleable.customview1_rotation, 0f);
float score = array.getFraction(R.styleable.customview1_score, 0, 13, 10);
array.recycle(); // 一定要回收,否則會浪費資源
setBackgroundColor(color);
}
新浪微博如何解除手機綁定?電腦與手機雙端教學
當我們為新浪微博啟用了帳號保護並綁定手機後,帳號安全便與手機號緊密相連。若因換號或其他原因需要解除綁定,該如何操作呢?本文將分別從手機與電腦兩端為你示範。手機端操作1、先
Android 高仿 iOS 滾輪選擇器:WheelView 封裝與省市区三級聯動
最近因為項目需要,整理了一份相對完整的 WheelView 使用方案。用之前看到的一句話來形容,就是站在巨人的肩膀上,做了一些貼近實際項目的調整。三類常見場景——單項選擇
蘑菇 ROM 助手怎麼合併或分割 system.img?圖文操作
蘑菇 ROM 助手可以對 system.img 進行合併與分割,處理高通平台的刷機包時特別用得上。以下是具體的操作方式。 一、操作前的準備 1. 下載並安裝 ROM 助手
完整攻略:將 Eclipse 專案導入 Android Studio 的兩種方式
只要用過 Android Studio,除了從零開始的新專案,幾乎每個人都會遇到同一個難題:手邊那堆 Eclipse 時代的舊程式碼,究竟該怎麼搬進 Android St