編輯:關於 Android 程式設計
對很多剛入門的 Android 開發者來說,「自定義 View」幾個字聽起來頗有壓力,但它又是從新手走向熟練的必經關卡。下面我把自定義 View 的標準步驟梳理清楚,並用一個可互動的標題控制項作為範例。
整體流程可以濃縮成四步:
1、定義自定義屬性;
2、在 View 的構造方法中讀取這些屬性;
3、重寫 onMeasure(這一步並非絕對必要,但多數場景下繞不開);
4、重寫 onDraw。
先在 res/values/ 下建立 attrs.xml,在其中定義屬性並歸攏成一個樣式集合:
<?xml version="1.0" encoding="utf-8"?> <resources> <attr name="titleText" format="string" /> <attr name="titleTextColor" format="color" /> <attr name="titleTextSize" format="dimension" /> <declare-styleable name="CustomTitleView"> <attr name="titleText" /> <attr name="titleTextColor" /> <attr name="titleTextSize" /> </declare-styleable> </resources>
這裡定義了文字內容、文字顏色、文字大小三個屬性。format 用來約束取值類型,常見的有 string、color、dimension、integer、enum、reference、float、boolean、fraction、flag 等。
接著在佈局中声明並使用這個自定義控制項:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" xmlns:custom="https://schemas.android.com/apk/res/com.example.customview01" android:layout_width="match_parent" android:layout_height="match_parent" > <com.example.customview01.view.CustomTitleView android:layout_width="200dp" android:layout_height="100dp" custom:titleText="3712" custom:titleTextColor="#ff0000" custom:titleTextSize="40sp" /> </RelativeLayout>
務必引入命名空間 xmlns:custom="https://schemas.android.com/apk/res/com.example.customview01",後半段就是專案的 package 路徑。少了這行,自定義屬性無法被識別。
/** 文本 */ private String mTitleText; /** 文本的顏色 */ private int mTitleTextColor; /** 文本的大小 */ private int mTitleTextSize; /** 繪制時控制文本繪制的范圍 */ private Rect mBound; private Paint mPaint; public CustomTitleView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public CustomTitleView(Context context) { this(context, null); } /** 獲得我自定義的樣式屬性 */ public CustomTitleView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomTitleView, defStyle, 0); int n = a.getIndexCount(); for (int i = 0; i < n; i++) { int attr = a.getIndex(i); switch (attr) { case R.styleable.CustomTitleView_titleText: mTitleText = a.getString(attr); break; case R.styleable.CustomTitleView_titleTextColor: mTitleTextColor = a.getColor(attr, Color.BLACK); break; case R.styleable.CustomTitleView_titleTextSize: mTitleTextSize = a.getDimensionPixelSize(attr, (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics())); break; } } a.recycle(); mPaint = new Paint(); mPaint.setTextSize(mTitleTextSize); mBound = new Rect(); mPaint.getTextBounds(mTitleText, 0, mTitleText.length(), mBound); }
這裡重寫了三個構造方法。佈局文件 inflate 時走的是兩參數版本,所以要讓所有構造最終都彙流到三參數版本,屬性讀取也只寫一份。順帶用 Paint.getTextBounds() 提前量出文字的實際佔用區域,後續居中繪製要用到。
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); } @Override protected void onDraw(Canvas canvas) { mPaint.setColor(Color.YELLOW); canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), mPaint); mPaint.setColor(mTitleTextColor); canvas.drawText(mTitleText, getWidth() / 2 - mBound.width() / 2, getHeight() / 2 + mBound.height() / 2, mPaint); }
此時的效果是:

寫死寬高的情況下還看得過去。但只要把佈局裡的寬高改成 wrap_content,結果立刻就跑偏:

原因在於:當你明確指定寬高時,系統測出來的就是你寫的值;而一旦寫成 WRAP_CONTENT 或 MATCH_PARENT,系統給回來的尺寸會等同於 MATCH_PARENT。也就是說,系統並不知道你的內容該佔多大,這件事得自己接手。
動手之前先認識 specMode 的三種取值:
EXACTLY:父容器已經給出確定尺寸,通常對應明確數值或 MATCH_PARENT;
AT_MOST:子 View 不能超過某個上限,一般對應 WRAP_CONTENT;
UNSPECIFIED:父容器不做限制,子 View 想多大就多大,實務上很少出現。
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); int width; int height ; if (widthMode == MeasureSpec.EXACTLY) { width = widthSize; } else { mPaint.setTextSize(mTitleTextSize); mPaint.getTextBounds(mTitle, 0, mTitle.length(), mBounds); float textWidth = mBounds.width(); int desired = (int) (getPaddingLeft() + textWidth + getPaddingRight()); width = desired; } if (heightMode == MeasureSpec.EXACTLY) { height = heightSize; } else { mPaint.setTextSize(mTitleTextSize); mPaint.getTextBounds(mTitle, 0, mTitle.length(), mBounds); float textHeight = mBounds.height(); int desired = (int) (getPaddingTop() + textHeight + getPaddingBottom()); height = desired; } setMeasuredDimension(width, height); }
思路很直白:精確模式聽父容器的,其他模式就按「文字尺寸 + 自身 padding」算一個合適值,最後一定要呼叫 setMeasuredDimension() 把結果交回去。
改回 wrap_content 試試:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" xmlns:custom="https://schemas.android.com/apk/res/com.example.customview01" android:layout_width="match_parent" android:layout_height="match_parent" > <com.example.customview01.view.CustomTitleView android:layout_width="wrap_content" android:layout_height="wrap_content" custom:titleText="3712" android:padding="10dp" custom:titleTextColor="#ff0000" android:layout_centerInParent="true" custom:titleTextSize="40sp" /> </RelativeLayout>
現在的效果是:

寬高終於能隨心設置了。
如果只做到這一步,這個自定義 View 跟 TextView 比起來確實沒什麼優勢。所以再給它掛一個點擊事件,在構造方法裡註冊監聽:
this.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mTitleText = randomText(); postInvalidate(); } });
private String randomText() { Random random = new Random(); Set<Integer> set = new HashSet<Integer>(); while (set.size() < 4) { int randomInt = random.nextInt(10); set.add(randomInt); } StringBuffer sb = new StringBuffer(); for (Integer i : set) { sb.append("" + i); } return sb.toString(); }
運行後的效果:

每點一下就重新生成一個四位隨機數並刷新畫面。有興趣的話,可以在 onDraw 裡再撒點噪點,一個簡易驗證碼控制項就成型了。
源碼下載:Android 自定義 View
以上就是自定義 View 的完整實作脈絡,掌握屬性宣告、構造讀值、onMeasure 與 onDraw 這四個環節,大部分客製控制項都能自己寫出來。
Android - 查看應用(apk)簽名的方法
查看 Android 應用簽名在微博、微信開放平台注冊應用時,往往需要填寫應用(apk)的簽名。此時可以借助 keytool 工具來查詢一個已簽名應用的簽名信息。具體步驟
Android 刮刮卡實作:自訂 View、雙緩衝與 PorterDuff 的組合技
做一個刮刮卡,你會練到哪些技能 刮刮卡是個很好的自訂 View 練習題,因為它把繪圖系統裡最實用的幾塊拼在一起: * 圓角圖片的實作原理 * 雙緩衝技術繪圖 * Bit
仿朋友圈「全文/收起」:RecyclerView 動態文字展開的實作思路
社交類 App 的動態流有個共同難題:貼文長度天差地遠。若全部展開,短貼文下方會留一大片空白;若一律截斷,想看完的人又得點進詳情頁。正解是「超過一定行數才顯示全文」——短
ListView 進階筆記(二):三大優化與常見疑難的破解
上一篇我們介紹了幾種常見 Adapter 的簡單實作與 ListView 的基本用法,這一篇則聚焦在優化手法,以及實作中經常遇到的幾個問題。 優化一:複用 convert