編輯:關於 Android 程式設計
當系統內建的 UI 元件無法滿足產品需求時,我們可以透過繼承 View 來自行打造專屬元件,並按需覆寫關鍵方法。本文將帶你梳理自訂 View 的核心概念、常見可覆寫的方法,以及一個跟手移動小球的完整範例。
自訂 View 的彈性來自於對生命週期與繪製流程的掌控,最常被覆寫的方法大致可分為兩類。
View 提供了三個建構子,分別對應不同的建立方式:
public View(Context context):以程式碼動態建立 View 時使用。public View(Context context, AttributeSet attrs):透過 XML 佈局載入 View 時使用。public View(Context context, AttributeSet attrs, int defStyle):帶有預設樣式的版本。查看原始碼會發現雙參數版本內部其實也是呼叫這個三參數版本,一般情況下我們無須覆寫它。以下是 View 在繪製與互動過程中會觸發的重要回呼:
onFinishInflate():XML 佈局填充並完成界面建構後觸發。onMeasure(int, int):量測 View 本身及其子 View 的尺寸。onLayout(boolean, int, int, int):為子元件配置位置與大小時觸發。onSizeChanged(int, int, int, int):元件尺寸改變時觸發。onDraw(Canvas):元件即將繪製時觸發,是客製繪圖的核心。onKeyDown(int, KeyEvent) / onKeyUp(int, KeyEvent):按鍵按下與放開時觸發。onTrackballEvent(MotionEvent):軌跡球事件發生時觸發。onTouchEvent(MotionEvent):觸控事件發生時觸發。onWindowFocusChanged(boolean):焦點狀態改變時觸發。onAttachedToWindow() / onDetachedFromWindow():元件加入或從視窗分離時觸發。onWindowVisibilityChanged(int):所屬視窗的可見性改變時觸發。1)繼承 View。 可以繼承 View,也可依需求選擇它的子類。
2)覆寫建構子。 一般覆寫前兩個即可。若只以程式碼方式加入,可僅覆寫單參數版本;若只透過 XML 加入,則僅需雙參數版本。為避免出錯,建議單參數與雙參數都一併覆寫。
3)按需覆寫回呼方法。 依實際需求選擇,其中 onDraw(Canvas) 幾乎都會用到。
4)加入 Activity。 完成上述步驟後,可透過「程式碼」或「XML」兩種方式將自訂 View 加入 Activity。
以下先定義自訂 View 類別 CustomView1,在 onDraw 中以畫布繪製圓形:
public class CustomView1 extends View {
public float currentX = 46;
public float currentY = 57;
Paint p;
private void init() {
p = new Paint();
p.setColor(Color.GREEN);
}
public CustomView1(Context context) {
super(context);
init();
}
public CustomView1(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawCircle(currentX, currentY, 20, p);
}
}
public class CustomViewActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_view);
final CustomView1 cs = new CustomView1(this);
RelativeLayout Rlayout = (RelativeLayout) findViewById(R.id.RLayout);
Rlayout.addView(cs);
cs.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
cs.currentX = event.getX();
cs.currentY = event.getY();
cs.invalidate();
return true;
}
});
}
}
此時的 XML 佈局只需準備好承載容器即可:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:id="@+id/RLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".CustomViewActivity" >
</RelativeLayout>
先在佈局中直接宣告自訂 View 的完整類別名稱:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:id="@+id/RLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".CustomViewActivity" >
<com.example.customview.CustomView1
android:id="@+id/cs"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
接著在 Activity 中以 findViewById 取得該 View 並掛上觸控監聽:
public class CustomViewActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_view);
final CustomView1 cs = (CustomView1) findViewById(R.id.cs);
cs.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
cs.currentX = event.getX();
cs.currentY = event.getY();
cs.invalidate();
return true;
}
});
}
}
不妨留意 Logcat 的輸出,對比這兩種引入方式在建構子呼叫上的差異:程式碼方式會觸發單參數建構子,而 XML 方式則會觸發雙參數建構子。
補充:View 的許多子類都擁有獨特屬性,例如 TextView 的 text、color 等。那麼能否也為自訂 View 加上專屬屬性呢?答案是肯定的,我們將於下一篇中介紹。
Android 屬性動畫進階:補充說明與實用技巧
目錄 本文概述、動畫補充說明、屬性動畫的 View 加載方式、TypeEvaluator 的使用、TimeInterpolator、LayoutTransition、Ot
Servlet 讀書筆記:生命週期、Session、轉發重定向與線程安全
環境準備 想編譯 Servlet,先把 Tomcat 的 common/lib 底下的 jsp_api.jar 與 servlet_api.jar 複製到 JDK 的 l
Android Activity 建立、跳轉與資料傳遞完整教學
Activity 的角色 Activity 是 Android 四大元件之一,可理解為應用程式中的一個畫面。使用者看到的每一頁,通常都對應一個 Activity。它負責使
ActionBar 實戰:高仿微信主界面的完整實現
經過前兩篇的學習,相信大家都對 ActionBar 有了較為深刻的理解。唯一的遺憾是之前偏重理論,真正投入項目實戰時能否發揮出來還不好說。本文就把理論與實踐結合,帶大家動