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

自定義 View 入門:通過繼承系統控件擴展繪製能力

編輯:關於 Android 程式設計

Android 自定義 View 有幾條路徑:完全從零繼承 View、繼承 View 的子類、或者組合已有控件。這一類最簡單,也最適合入門——繼承一個現成的控件,覆寫 onDraw(),在它原有的繪製基礎上補上自己想要的效果。

思路

關鍵只有一個方法:onDraw(Canvas canvas)。所有繪製指令都通過傳入的 Canvas 完成,而 super.onDraw(canvas) 這一行決定了我們的內容是蓋在原控件之上,還是被它蓋住。

示例:給 TextView 加一層雙色矩形背景

需求很簡單:先鋪一層藍色底,再在中間疊一個黃色矩形,最後讓文字正常顯示在最上層並且在橫向上錯開一點。

自定義 View 的代碼

public class TestView extends TextView {

    public TestView(Context context) {
        super(context);
    }

    public TestView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public TestView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // 先畫底層:整塊區域填藍
        Paint paint1 = new Paint();
        paint1.setColor(getResources().getColor(android.R.color.holo_blue_light));
        paint1.setStyle(Paint.Style.FILL);
        canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), paint1);

        // 再畫第二層:四周留出 10px 邊距的黃色矩形
        Paint paint2 = new Paint();
        paint2.setColor(Color.YELLOW);
        paint2.setStyle(Paint.Style.FILL);
        canvas.drawRect(10, 10,
                getMeasuredWidth() - 10, getMeasuredHeight() - 10, paint2);

        // 水平方向偏移 10px 後再交給父類繪製文字
        // save/restore 必須成對出現,否則平移會污染後續繪製
        canvas.save();
        canvas.translate(10, 0);
        super.onDraw(canvas);
        canvas.restore();
    }
}

幾個細節值得注意。

用 getMeasuredWidth() 而非 getWidth()。在 onDraw 階段,控件的測量已經完成但布局尚未結束,此時 getWidth() 可能還是 0,而 getMeasuredWidth() 是可靠的。

save 與 restore 必須配對。canvas.translate() 會改變 Canvas 的坐標系,如果不 restore,這個偏移會一直生效,後續所有繪製都會跟着偏。

super.onDraw() 的位置決定層疊關係。放在最前面,文字會被矩形蓋住;放在最後面,文字才會浮在最上層。

構造函數至少要有 (Context, AttributeSet)。只寫 TestView(Context) 的話,在 XML 布局裡使用這個控件會直接崩潰——因爲從 XML 加載時,系統調用的是帶 AttributeSet 的那個構造函數。原始示例只寫了一個構造函數,這是一個隱藏的坑。

布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center">

    <com.example.customview.TestView
        android:layout_width="200dp"
        android:layout_height="100dp"
        android:text="我是自定義的 TextView"
        android:textColor="#000000"
        android:textSize="18sp" />

</LinearLayout>

注意自定義 View 在布局中的寫法是完整類名(含包名),而不是簡寫的類名。

Activity 中引用

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

在布局裡聲明就夠了,不需要在代碼裡做任何額外處理。

接下來可以往哪走

這個例子只碰了 onDraw,真實場景裡還會經常需要覆寫:

  • onMeasure():控制測量邏輯,支持 wrap_content 時必須處理
  • onSizeChanged():尺寸變化時重建緩存對象,比在 onDraw 裡 new Paint 高效得多
  • onTouchEvent():處理交互,配合属性動畫做反饋效果
  • invalidate() 與 postInvalidate():前者主線程調用,後者可在子線程調用

另外,把 Paint 對象提到類成員裡、在構造函數中初始化一次,比每次 onDraw 都 new 一批要划算——onDraw 的調用頻率遠比想象中高。

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