編輯:關於 Android 程式設計
本講主題:自定義 View,且要求能夠在佈局檔案中重複使用。
1. 定義自定義屬性;
2. 在構造方法中讀取這些屬性;
3. 重寫 onMeasure(可選,但實務上通常需要,否則只能沿用系統預設);
4. 重寫 onDraw 完成繪製。
關於構造方法:我們重寫了三個構造方法,而佈局檔案 inflate 時調用的是只有兩個參數的那個。所以務必讓所有構造方法都最終委派到三參數版本,並在三參數版本中集中讀取自訂屬性。
關於測量:不重寫 onMeasure 時,系統給的高度與寬度一律是 MATCH_PARENT;即使你在 XML 中寫成 WRAP_CONTENT,最終也會表現成 MATCH_PARENT。
MeasureSpec 的三種 specMode:
EXACTLY:明確指定了具體數值,或者 MATCH_PARENT;
AT_MOST:子佈局被限制在一個最大值內,對應 WRAP_CONTENT;
UNSPECIFIED:子佈局想多大就多大,實務中很少用到。
<RelativeLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:custom="https://schemas.android.com/apk/res/com.example.customview1"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.view.CustomTitleView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
custom:titleText="1314"
custom:titleTextColor="#ff0000"
custom:titleTextSize="50sp" />
</RelativeLayout>
務必引入命名空間 xmlns:custom="https://schemas.android.com/apk/res/項目包名",後面才能使用 custom: 前綴。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomTitleView">
<attr name="titleText" format="string" />
<attr name="titleTextColor" format="color" />
<attr name="titleTextSize" format="dimension" />
</declare-styleable>
</resources>
format 用於聲明該屬性的取值型別,可選值包括:string、color、dimension、integer、enum、reference、float、boolean、fraction、flag。
public class CustomTitleView extends View {
private String mTitleText; // 文本內容
private int mTitleTextColor; // 文本顏色
private int mTitleTextSize; // 文本大小
private Rect mBound; // 文本繪製邊界
private Paint mPaint;
public CustomTitleView(Context context) {
this(context, null);
}
public CustomTitleView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
/** 集中處理自訂屬性 */
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);
// 加個互動:點擊換一組隨機數,順便體驗 postInvalidate
this.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
mTitleText = randomText();
postInvalidate();
}
});
}
/** 生成 4 位不重複隨機數 */
private String randomText() {
Random random = new Random();
Set<Integer> set = new HashSet<Integer>();
while (set.size() < 4) {
set.add(random.nextInt(10));
}
StringBuffer sb = new StringBuffer();
for (Integer i : set) {
sb.append("" + i);
}
return sb.toString();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = 0;
int height = 0;
// 寬度
int specMode = MeasureSpec.getMode(widthMeasureSpec);
int specSize = MeasureSpec.getSize(widthMeasureSpec);
switch (specMode) {
case MeasureSpec.EXACTLY: // 明確指定
width = getPaddingLeft() + getPaddingRight() + specSize;
break;
case MeasureSpec.AT_MOST: // WRAP_CONTENT
width = getPaddingLeft() + getPaddingRight() + mBound.width();
break;
}
// 高度
specMode = MeasureSpec.getMode(heightMeasureSpec);
specSize = MeasureSpec.getSize(heightMeasureSpec);
switch (specMode) {
case MeasureSpec.EXACTLY:
height = getPaddingTop() + getPaddingBottom() + specSize;
break;
case MeasureSpec.AT_MOST:
height = getPaddingTop() + getPaddingBottom() + mBound.height();
break;
}
setMeasuredDimension(width, height);
}
@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);
}
}
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
與直接使用 TextView 相比,這個自定義 View 表面上看不出優勢,所以我在裡面加了一個點擊事件,每次生成一組四位隨機數。沿著這個思路再往 onDraw 裡加些噪點,就能改造成一個驗證碼控件——這才是自定義 View 真正的用武之地:標準控件做不到的呈現方式。
另外注意 onDraw 中文字垂直居中的算法:baseline 需要在中心點再加上文字高度的一半,直接用 getHeight() / 2 會導致視覺偏上。
Activity 生命周期全面解讀
Activity 的生命周期是 Android 開發的必修課。下面通過幾個典型場景,把它的來龍去脈講透。 1. 從打開應用到按後退鍵 打開應用: onCreate() 執
Android 自訂 FlowLayout 實作熱門標籤流式布局
一、概述 在多數 App 裡都見過「熱門標籤」那種會自動換行的流式布局。本文就來動手做一個類似效果的熱門標籤版面(源碼附在最後)。 原理圖: 1. 流式布局的特點與應
高仿微信圖片選擇器:Android 海量圖片的掃描、加載與流暢體驗
一、為什麼要認真對待圖片加載 手機鏡頭的像素輕鬆破千萬,一張照片解釋成 Bitmap 之後所佔的內存往往相當可觀。如果直接把幾千張原圖一股腦塞進列表,閃退與卡頓幾乎是必然
新一代開源 Android 渠道包生成工具 Walle 深度解析
自 Android 7.0(Nougat)推出全新的應用簽名方案 APK Signature Scheme v2 後,以往快速生成渠道包的方式便不再適用。那麼在新簽名方案