編輯:關於 Android 程式設計
需求很簡單:畫一個圓。以下是最直覺的寫法:
public class CircleView extends View {
private int mColor = Color.RED;
private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
public CircleView(Context context) {
super(context);
init();
}
public CircleView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CircleView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mPaint.setColor(mColor);
}
@Override
protected void onDraw(Canvas canvas) {
int width = getWidth();
int height = getHeight();
int radius = Math.min(width, height) / 2;
canvas.drawCircle(width / 2, height / 2, radius, mPaint);
}
}
對應的 XML:
<com.ryg.chapter_4.ui.CircleView
android:background="#000000"
android:id="@+id/circleView1"
android:layout_height="100dp"
android:layout_margin="20dp"
android:layout_width="match_parent" />
圓是畫得出來,但這個 View 有兩個不容忽視的缺陷:
android:padding 屬性完全無效。在 XML 設了 padding,畫出來卻毫無變化。
使用 wrap_content 等同於 match_parent。把 layout_width 改成 wrap_content,圓不會縮小,反而照樣填滿父容器。
這兩點讓它在真實專案中幾乎無法使用——任何需要留白的版面配置都會失效。
要解決上述問題,必須自己處理測量與 padding。
public class CircleView extends View {
private int mColor = Color.RED;
private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
public CircleView(Context context) {
super(context);
init();
}
public CircleView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CircleView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleView);
mColor = a.getColor(R.styleable.CircleView_circle_color, Color.RED);
a.recycle();
init();
}
private void init() {
mPaint.setColor(mColor);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST) {
setMeasuredDimension(200, 200);
} else if (widthSpecMode == MeasureSpec.AT_MOST) {
setMeasuredDimension(200, heightSpecSize);
} else if (heightSpecMode == MeasureSpec.AT_MOST) {
setMeasuredDimension(widthSpecSize, 200);
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
final int paddingLeft = getPaddingLeft();
final int paddingRight = getPaddingRight();
final int paddingTop = getPaddingTop();
final int paddingBottom = getPaddingBottom();
int width = getWidth() - paddingLeft - paddingRight;
int height = getHeight() - paddingTop - paddingBottom;
int radius = Math.min(width, height) / 2;
canvas.drawCircle(paddingLeft + width / 2, paddingTop + height / 2, radius, mPaint);
}
}
兩個關鍵改動:onMeasure 中針對 AT_MOST(也就是 wrap_content 對應的模式)給出預設尺寸 200;onDraw 中把四邊 padding 從可用區域中扣除,圓心座標也相應加上 paddingLeft / paddingTop 的偏移。
先在 values 下建立 attrs.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CircleView">
<attr name="circle_color" format="color" />
</declare-styleable>
</resources>
這裡定義了一個名為 CircleView 的屬性集合,裡面只有一個 color 格式的屬性 circle_color。
在建構子中解析(前面完整程式碼已包含):
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleView);
mColor = a.getColor(R.styleable.CircleView_circle_color, Color.RED);
a.recycle();
XML 中使用時,記得先宣告 namespace:
<com.ryg.chapter_4.ui.CircleView
xmlns:app="https://schemas.android.com/apk/res-auto"
android:background="#000000"
android:id="@+id/circleView1"
android:layout_height="100dp"
android:layout_margin="20dp"
android:layout_width="wrap_content"
android:padding="20dp"
app:circle_color="@color/light_green" />
namespace 宣告也可以放在根布局上,效果相同。使用方式與系統屬性無異:app:circle_color="@color/light_green"。別忘了 a.recycle(),TypedArray 是需要回收的資源。
margin 屬性可以直接使用,因為它由父容器控制,不需要自己在 onMeasure 中處理。
直接繼承 View 或 ViewGroup 的類別,必須自己處理 wrap_content,否則它就等同 match_parent。
View 要在 onDraw 中處理 padding;ViewGroup 則要在 onMeasure 與 onLayout 中處理 padding 和 margin。
View 中的 post 方法可以取代 handler,它會把 Runnable 排入 View 所屬行程的訊息佇列,語意更貼近 UI 操作。
在 onDetachedFromWindow 中停止動畫,避免 View 被移除後動畫仍在跑造成記憶體洩漏。
存在滑動巢狀關係時,務必處理滑動衝突,例如用 requestDisallowInterceptTouchEvent 協調父子層級的攔截行為。
想寫出漂亮又健壯的自定義 View 並不容易,唯有大量閱讀原始碼、多寫、多測,才能逐步建立手感。自己動手造一個輪子,再拿成熟元件來對比,差距與不足自然浮現。
Android 影像矩陣全解析:ColorMatrix 與 Matrix 的原理與實作
Android 裡有兩個舉足輕重的矩陣類別:ColorMatrix 與 Matrix。前者負責改變 Bitmap 的顏色與透明度,後者則負責平移、縮放與錯切等幾何變換。
Android 入門第二課:Activity 活動的基本用法
前面簡單介紹了 Android 的一些基礎知識作為熱身,接下來要接觸四大元件之一的 Activity(活動)。 Activity 是一種負責維護使用者介面的元件,主要用途
Android AlertDialog 全面實戰:提示框、列表、單選、多選與自定義佈局
對話框是用戶與應用交互最頻繁的載體之一:確認刪除、選擇項、填寫信息、簡單提示,都離不開它。Android 提供的 AlertDialog 通過 Builder 模式把常見
Android 實現文件目錄瀏覽與選擇功能
很多應用都需要「選擇一個文件」的能力:文檔導入、圖片替換、配置文件加載等等。如果每次都要自己寫一套文件瀏覽器,成本不低。本文用最簡潔的方式實現一個可逐級瀏覽目錄、並選中文