編輯:關於 Android 程式設計
Android 的 UI 由 View(單個元素)與 ViewGroup(元素集合)構成。雖然系統內建了 Button、TextView、RelativeLayout 等豐富組件,但實際開發中難免需要打造量身訂做的視圖。透過繼承 View 或其子類並覆寫 onDraw、onTouchEvent 等方法,就能定義全新的行為。
以下用一個「形狀選擇器」為例:使用者點擊時在方形、圓形、三角形之間切換。
public class ShapeSelectorView extends View {
// 必須提供接收 Context 與 AttributeSet 的構造器,供 UI 建立與編輯實例
public ShapeSelectorView(Context context, AttributeSet attrs) {
super(context, attrs);
}
}
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.codepath.example.customviewdemo.ShapeSelectorView
android:id="@+id/shapeSelector"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
先在 res/values/attrs.xml 宣告:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ShapeSelectorView">
<attr name="shapeColor" format="color" />
<attr name="displayShapeName" format="boolean" />
</declare-styleable>
</resources>
每個屬性都有 name 與 format(如 color、dimension、boolean、integer、float)。定義好後即可透過 res-auto 命名空間使用:
<com.codepath.example.customviewdemo.ShapeSelectorView
app:shapeColor="#7f0000"
app:displayShapeName="true"
android:id="@+id/shapeSelector"
... />
public class ShapeSelectorView extends View {
private int shapeColor;
private boolean displayShapeName;
public ShapeSelectorView(Context context, AttributeSet attrs) {
super(context, attrs);
setupAttributes(attrs);
}
private void setupAttributes(AttributeSet attrs) {
TypedArray a = getContext().getTheme().obtainStyledAttributes(
attrs, R.styleable.ShapeSelectorView, 0, 0);
try {
shapeColor = a.getColor(R.styleable.ShapeSelectorView_shapeColor, Color.BLACK);
displayShapeName = a.getBoolean(R.styleable.ShapeSelectorView_displayShapeName, false);
} finally {
a.recycle(); // TypedArray 為共用物件,必須回收
}
}
}
再補上 getter / setter,屬性變動時呼叫 invalidate() 與 requestLayout() 刷新顯示:
public boolean isDisplayingShapeName() { return displayShapeName; }
public void setDisplayingShapeName(boolean state) {
this.displayShapeName = state; invalidate(); requestLayout();
}
public int getShapeColor() { return shapeColor; }
public void setShapeColor(int color) {
this.shapeColor = color; invalidate(); requestLayout();
}
所有繪圖都在 onDraw 中透過 Canvas 完成:
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawRect(0, 0, shapeWidth, shapeHeight, paintShape);
if (displayShapeName) {
canvas.drawText("Square", shapeWidth + textXOffset, shapeHeight + textXOffset, paintShape);
}
}
private void setupPaint() {
paintShape = new Paint();
paintShape.setStyle(Style.FILL);
paintShape.setColor(shapeColor);
paintShape.setTextSize(30);
}
透過 onMeasure 依內容決定寬高,核心在於理解 MeasureSpec:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int textPadding = 10;
int contentWidth = shapeWidth;
int minw = contentWidth + getPaddingLeft() + getPaddingRight();
int w = resolveSizeAndState(minw, widthMeasureSpec, 0);
int minh = shapeHeight + getPaddingBottom() + getPaddingTop();
if (displayShapeName) minh += textYOffset + textPadding;
int h = resolveSizeAndState(minh, heightMeasureSpec, 0);
setMeasuredDimension(w, h);
}
MeasureSpec 封裝了父佈局對子元素的測量要求,由大小與模式組成,模式有三種:UNSPECIFIED(未指定,子元素可任意大小)、EXACTLY(父元素決定確切大小)、AT_MOST(至多達到指定值)。resolveSizeAndState() 依期望大小與 MeasureSpec 回傳合適值,最後以 setMeasuredDimension() 生效。
在 onTouchEvent 中處理點擊切換:
private String[] shapeValues = { "square", "circle", "triangle" };
private int currentShapeIndex = 0;
@Override
public boolean onTouchEvent(MotionEvent event) {
boolean result = super.onTouchEvent(event);
if (event.getAction() == MotionEvent.ACTION_DOWN) {
currentShapeIndex++;
if (currentShapeIndex > (shapeValues.length - 1)) currentShapeIndex = 0;
postInvalidate();
return true;
}
return result;
}
並在 onDraw 中依索引畫出對應形狀:
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
String shapeSelected = shapeValues[currentShapeIndex];
if (shapeSelected.equals("square")) {
canvas.drawRect(0, 0, shapeWidth, shapeHeight, paintShape);
textXOffset = 0;
} else if (shapeSelected.equals("circle")) {
canvas.drawCircle(shapeWidth / 2, shapeHeight / 2, shapeWidth / 2, paintShape);
textXOffset = 12;
} else if (shapeSelected.equals("triangle")) {
canvas.drawPath(getTrianglePath(), paintShape);
textXOffset = 0;
}
if (displayShapeName) {
canvas.drawText(shapeSelected, 0 + textXOffset, shapeHeight + textYOffset, paintShape);
}
}
當配置改變(如旋轉屏幕)時,實作以下兩個方法即可自動保存與恢復:
@Override
public Parcelable onSaveInstanceState() {
Bundle bundle = new Bundle();
bundle.putParcelable("instanceState", super.onSaveInstanceState());
bundle.putInt("currentShapeIndex", this.currentShapeIndex);
return bundle;
}
@Override
public void onRestoreInstanceState(Parcelable state) {
if (state instanceof Bundle) {
Bundle bundle = (Bundle) state;
this.currentShapeIndex = bundle.getInt("currentShapeIndex");
state = bundle.getParcelable("instanceState");
}
super.onRestoreInstanceState(state);
}
完成這些邏輯後,即使手機配置改變,你的自定義視圖也能自動保存並還原狀態。
Android 安全審計工具 MobiSecLab 上手實測
分析 Android 應用時,本地端有許多工具可以勝任。本文介紹的是另一條路——線上化的惡意軟體檢測與靜態分析平台 MobiSecLab。國內相關介紹不多,但實際使用量並
Android 自定義 View 實戰:merge 根佈局與被忽略的 defStyleAttr
繼承父類、重寫方法,自定義 View 的骨架就算搭起來了。但真正寫進項目裡,往往會踩到一些不明顯的坑。本文整理兩個最常見、也最容易被忽略的問題。 一、XML 佈局的根節
Android 登錄介面實戰:自定義輸入框與驗證碼
登錄介面的常見需求一個完整的登錄介面,通常不只是兩個輸入框。它還需要帳號密碼清空、空值提示、驗證碼校驗,以及清楚的錯誤回饋。自定義 DeletableEditText為了
StepView:打造步驟流程的客製化 View
StepView 是一個用來展示步驟流程的自訂 View,效果如下圖: 這個元件可以呈現類似快遞 App 那樣的步驟流程展示。 1. 首先在 XML 版面中這樣使用: