Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 自定義 UI:從 View 繪製圓圈開始

編輯:關於 Android 程式設計

自定義 UI 的兩個方向

在 Android 中實作自定義 UI,通常有兩種路線。若需要完全掌控繪製,可以繼承 View;若只是擴充既有控制項,則可繼承 TextView、Button 或 LinearLayout 等。官方文件中的 Custom Components 與 Creating Custom Views 是很好的起點。

建立自訂 View

以下例子建立 GraphicsView,繼承 View 並使用 Path 畫出圓形輪廓,再用 Paint 設定線條顏色、寬度與樣式。為了支援 Java 與 XML 兩種使用方式,建議實作含 Context、AttributeSet 與 defStyleAttr 的建構子。

繪製流程

在 initView 中初始化 Path 與 Paint,並設定背景。在 draw 方法中呼叫 canvas.drawPath,即可把圖形畫到畫布上。若使用 XML 布局,也可在 LinearLayout 中加入 com.example.apptest.GraphicsView。

後續延伸

掌握基礎繪製後,可進一步加入觸控事件、動畫、屬性解析與 onMeasure 自訂測量。自定義 UI 不只是畫圖,更是對 Android 檢視系統與事件流程的綜合練習。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved