編輯:關於 Android 程式設計
自訂 View 是 Android 開發中常見的進階主題。這個範例會建立一個可點擊刷新的隨機驗證碼 View,示範自訂屬性、onMeasure、onDraw 與點擊事件的基本流程。
在 res/values/attrs.xml 中宣告屬性:
<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>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
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>
public CustomTitleView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.CustomTitleView,
defStyle,
0
);
int count = a.getIndexCount();
for (int i = 0; i < count; 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();
}
@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,自訂 View 需要自行計算合適尺寸,否則系統可能會使用預設行為。

可以重寫 onMeasure:
@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(mTitleText, 0, mTitleText.length(), mBound);
width = mBound.width() + getPaddingLeft() + getPaddingRight();
}
if (heightMode == MeasureSpec.EXACTLY) {
height = heightSize;
} else {
mPaint.setTextSize(mTitleTextSize);
mPaint.getTextBounds(mTitleText, 0, mTitleText.length(), mBound);
height = mBound.height() + getPaddingTop() + getPaddingBottom();
}
setMeasuredDimension(width, height);
}
調整後效果:

讓 View 在點擊時重新產生一組隨機數字,並呼叫 postInvalidate() 重新繪製。
this.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mTitleText = randomText();
postInvalidate();
}
});
private String randomText() {
Random random = new Random();
Set<Integer> set = new HashSet<>();
while (set.size() < 4) {
set.add(random.nextInt(10));
}
StringBuilder sb = new StringBuilder();
for (Integer i : set) {
sb.append(i);
}
return sb.toString();
}
點擊後效果:

透過這個範例,可以練習自訂 View 的完整流程。若要進一步做成驗證碼,還可以加入干擾線、隨機點、旋轉文字與顏色變化,讓畫面更豐富。
樂視pro3支持NFC嗎?功能與用途介紹
樂視pro3支持NFC嗎? 答案是支持。根據樂視官方的說法,樂視pro3 搭載的是全功能 NFC,覆蓋讀卡、寫卡、卡模擬以及 P2P 模式等多種應用場景。有了它,公交卡
Android BitmapFactory 二次抽樣:用 inSampleSize 馴服大圖、告別 OOM
在 ViewPager、GridView、ListView 這類需要一次載入大量圖片的場景裡,OOM(內存溢出)幾乎是必經的關卡。早期應用有著 16M 左右的單進程堆上限
Android SweepGradient 詳解:用掃描漸層畫出雷達光波效果
什麼是「掃描渲染」?想想安全軟體裡雷達掃描的那圈光波——顏色繞著一個中心點旋轉漸變,就是 SweepGradient 最典型的應用。 兩種建構方式 以顏色陣列建構
Android Canvas 常用方法完整整理:平移、縮放、旋轉與繪圖 API
Canvas 是 Android 自定義繪圖的核心。靈活掌握它的變換與繪製方法,多數客製圖形都能自己畫出來。以下依主題整理常用 API。 一、什麼是 Canvas 操作