Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 自定義 View 全面解析:分類、注意事項與自定義屬性

編輯:關於 Android 程式設計

本文涵蓋以下內容:

* 自定義 View 的分類
* 自定義 View 的注意事項
* 自定義 View 的實現
* 讓自定義 View 支持 wrap_content 和 padding
* 自定義屬性的實現過程

寫自定義 View 的目的是實現更豐富的視覺效果。它同時也是相對硬核的一塊技術,牽涉到 View 層次結構、事件分發機制、測量與繪製流程、彈性滑動以及滑動沖突處理等一系列知識點。

自定義 View 的分類

1.1 繼承 View 重寫 onDraw 方法

主要用於實現不規則的顯示效果,即那種不方便用布局組合拼出來的圖形,無論靜態展示還是動態繪製。這種方式需要自己處理 wrap_content,padding 也要自己兼容。

1.2 繼承 ViewGroup 派生特殊的 Layout

用於實現全新的自定義布局,即除 LinearLayout、RelativeLayout 之外自己定義的一種排列規則。當某種效果很像幾個 View 拼在一起時可以考慮。這種方式稍複雜,需要妥善處理 ViewGroup 的測量與布局兩個過程。

1.3 繼承特定的 View(比如 TextView)

一般用作擴展某個既有 View 的能力。這種方式不需要自己支持 wrap_content 和 padding。

1.4 繼承特定的 ViewGroup(比如 LinearLayout)

同樣適用於「幾個 View 組合」的場景,但測量和布局可以直接沿用父類實現,無需自己寫。與 1.2 相比,1.2 能做的 1.4 大多也能做,只是 1.2 更貼近底層。

自定義 View 的注意事項

2.1 讓 View 支持 wrap_content

直接繼承 View 或 ViewGroup 的控件,若不在 onMeasure 中處理 wrap_content,外部布局中使用 wrap_content 時就得不到預期效果。

2.2 讓 View 支持 padding

直接繼承 View 的控件,若不在 onDraw 中處理 padding,這個屬性就是廢的。直接繼承 ViewGroup 的控件則需要在 onMeasure 和 onLayout 中同時考慮 padding 與子元素 margin 的影響,否則兩者都會失效。

2.3 不要在 View 中使用 Handler

View 內部本身提供了 post 系列方法,足以替代 Handler 的作用。除非你明確需要通過 Handler 發送消息,否則沒必要多引入一層。

2.4 線程與動畫要及時停止

停止時機選在 onDetachedFromWindow。當包含該 View 的 Activity 退出或該 View 被 remove 時,這個方法會被調用;反之 Activity 啟動時會回調 onAttachedToWindow。此外 View 不可見時也應停止線程與動畫,否則容易造成內存洩露。

2.5 滑動嵌套要處理好沖突

================================================

繼承 View 重寫 onDraw 方法

3.1 代碼
public class CircleView extends View {
    private int mColor = Color.RED;
    private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

    public CircleView(Context context) {
        this(context, null);
    }

    public CircleView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CircleView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mPaint.setColor(mColor);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int width = getWidth();
        int height = getHeight();
        int radius = Math.min(width, height) / 2;
        canvas.drawCircle(width / 2, height / 2, radius, mPaint);
    }
}
<LinearLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.peak.app.c_view.CustomViewMainActivity">

    <com.peak.app.c_view.CircleView
        android:layout_width="120dip"
        android:layout_height="120dip"
        android:background="@color/colorPrimaryDark"
        android:padding="40dip" />
</LinearLayout>

這就完成了一個最基礎的自定義 View。按 2.1、2.2 的說法,它應該还不支持 wrap_content 和 padding,下面實測驗證。

3.2 驗證 wrap_content 與 padding

圖一:layout_margin 生效
圖二:padding 不生效
圖三、圖五:wrap_content 不生效

layout_margin 由父容器負責,所以天然支持,不需要我們操心。

3.3 讓 View 支持 wrap_content

失效的原因在於:使用 wrap_content 時 specMode 為 AT_MOST,此模式下尺寸等於 specSize,而 specSize 此時是父容器剩餘的可用空間,於是子 View 就被撐成了父容器的大小。

解法是給 View 指定一組默認寬高,並在 AT_MOST 時使用這組值。默認值怎麼取沒有固定標準,只能依具體需求挑一個合適的量級。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int mWidth = 600;
    int mHeight = 600;
    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);

    if (widthMode == MeasureSpec.AT_MOST && heightMode == MeasureSpec.AT_MOST) {
        setMeasuredDimension(Math.min(mWidth, widthSize), Math.min(mHeight, heightSize));
    } else if (widthMode == MeasureSpec.AT_MOST) {
        setMeasuredDimension(Math.min(mWidth, widthSize), heightSize);
    } else if (heightMode == MeasureSpec.AT_MOST) {
        setMeasuredDimension(widthSize, Math.min(mHeight, heightSize));
    } else {
        setMeasuredDimension(widthSize, heightSize);
    }
}

把布局改成 wrap_content 再測:

android:layout_width="wrap_content"
android:layout_height="wrap_content"

3.4 讓 View 支持 padding

在繪製時把 padding 折算進去就行。先在 onDraw 中重新計算可用寬高:

int width = getWidth() - (paddingLeft + paddingRight);
int height = getHeight() - (paddingTop + paddingBottom);

再把圓心偏移 padding 的量:

canvas.drawCircle(paddingLeft + width / 2, paddingTop + height / 2, radius, mPaint);

完整代碼:

@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);
}
<com.peak.app.c_view.CircleView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimaryDark"
    android:padding="10dip" />

繼承特定的 ViewGroup(比如 LinearLayout)

這種方式主要用於封裝自定義布局,寫起來比較輕鬆,直接看代碼。

// ActionBarView.java
public class ActionBarView extends LinearLayout {
    public static final int KEY_BACK = 111;
    public static final int KEY_CONTENT = 222;

    private Context context = null;
    private ImageView iv_back;
    private TextView tv_context;
    private OnClickListener onClickListener = null;

    public ActionBarView(Context context) {
        this(context, null);
    }

    public ActionBarView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        View contentView = LayoutInflater.from(context).inflate(R.layout.actionbar_layout, this);
        iv_back = (ImageView) contentView.findViewById(R.id.iv_back);
        tv_context = (TextView) contentView.findViewById(R.id.tv_context);
        iv_back.setOnClickListener(new MyOnClickListener(KEY_BACK));
        tv_context.setOnClickListener(new MyOnClickListener(KEY_CONTENT));
    }

    /** 動態設置標題 */
    public void setContent(String str) {
        tv_context.setText(str);
    }

    /** 通過回調接口在外部監聽點擊 */
    private class MyOnClickListener implements android.view.View.OnClickListener {
        private int key = -1;

        private MyOnClickListener(int position) {
            this.key = position;
        }

        @Override
        public void onClick(View v) {
            if (onClickListener != null) {
                onClickListener.onClick(key, v);
            }
        }
    }

    public void setOnClickListener(OnClickListener onClickListener) {
        this.onClickListener = onClickListener;
    }

    public interface OnClickListener {
        void onClick(int key, View v);
    }
}
<!-- actionbar_layout.xml -->
<FrameLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="44dip"
    android:background="@drawable/bg_top">

    <ImageView
        android:id="@+id/iv_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_top_return" />

    <TextView
        android:id="@+id/tv_context"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="center_horizontal"
        android:gravity="center"
        android:text="標題" />
</FrameLayout>

Activity 布局中引用:

<com.peak.app.c_view.ActionBarView
    android:id="@+id/barView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="20dip"
    android:background="@color/colorPrimary"
    android:padding="20dip" />

Activity 中使用:

ActionBarView barView = (ActionBarView) findViewById(R.id.barView);
barView.setContent("自定義 View 標題");
barView.setOnClickListener(new ActionBarView.OnClickListener() {
    @Override
    public void onClick(int key, View v) {
        if (key == ActionBarView.KEY_BACK) {
            Log.i("CustomViewMainActivity", "ActionBarView 點擊返回按鈕");
        }
        if (key == ActionBarView.KEY_CONTENT) {
            Log.i("CustomViewMainActivity", "ActionBarView 點擊標題");
        }
    }
});

圖中藍色區域是 ActionBarView 佔用的範圍,藍色之外由父布局的 padding 決定,藍色與內部白色區域之間的間距則是 ActionBarView 自身的 padding。可見這種方式天然支持 padding,不需要額外處理。

代碼裡用 setContent 動態改標題,當然也可以直接在 xml 中配置——那就需要自定義屬性了,馬上講。

繼承 ViewGroup 派生特殊的 Layout

這種方式相對複雜,日常使用頻率不高,這裡先跳過。

繼承特定的 View

這裡以繼承 EditText 實現「一鍵清空」為例,源碼見附件。

自定義屬性

出於業務需要或單純為了使用方便,我們常常希望能像系統屬性那樣在 xml 裡直接配置。比如 CircleView 的圓圈顏色、ActionBarView 的標題文案。下面以 CircleView 為例。

第一步:在 res/values/ 下新建 attrs 開頭的屬性文件

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CircleView">
        <attr name="circle_color" format="color" />
    </declare-styleable>
</resources>

這裡定義了一個名為 CircleView 的屬性集合(既然是集合,可以放多個屬性),集合中的屬性名是 circle_color,格式為 color。

第二步:在構造方法中解析並應用自定義屬性

public CircleView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);

    // TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CircleView, defStyleAttr, 0);
    // TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleView, defStyleAttr, 0);
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleView);

    mColor = a.getColor(R.styleable.CircleView_circle_color, Color.YELLOW);
    a.recycle();

    mPaint.setColor(mColor);
}

第三步:在布局中使用

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.peak.app.c_view.CustomViewMainActivity">

    <com.peak.app.c_view.CircleView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimaryDark"
        android:padding="10dip"
        app:circle_color="@color/colorAccent" />
</LinearLayout>

這裡有個容易漏掉的細節:必須在根布局中加上命名空間聲明

xmlns:app="https://schemas.android.com/apk/res-auto"

其中 app 是屬性前綴,與下面的 app:circle_color 呼應。這個前綴可以自定義,改成你喜歡的名字也行。

自定義屬性支持的 format 類型:

reference:資源 ID
color:顏色值
boolean:布爾值
dimension:尺寸值
float:浮點值
integer:整型值
string:字符串
fraction:百分比
enum:枚舉值
flag:位或運算,支持多類型

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved