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

自定義 ViewGroup:帶箭頭的圓角矩形彈出菜單

編輯:關於 Android 程式設計

這次要一起做一個帶箭頭的圓角矩形菜單,大概長這樣:

需求:頂部的箭頭要對準菜單錨點,菜單項按下時反色,背景色與按壓色可配置。

最偷工減料的做法是請 UX 給一張三角形圖片貼上去,但這樣有兩個問題:一是不同解析度要準備多套切圖,二是箭頭位置無法精準對齊。所以還是自己寫一個 ViewGroup 比較乾淨。自定義 ViewGroup 其實有固定套路,照著走就行。

步驟一:定義 attrs.xml

先宣告這個控件有哪些可配置屬性。這裡共七個:箭頭寬、箭頭高、箭頭水平偏移、圓角半徑、菜單背景色、陰影色、陰影厚度。

<resources>
    <declare-styleable name="ArrowRectangleView">
        <attr name="arrow_width" format="dimension" />
        <attr name="arrow_height" format="dimension" />
        <attr name="arrow_offset" format="dimension" />
        <attr name="radius" format="dimension" />
        <attr name="background_color" format="color" />
        <attr name="shadow_color" format="color" />
        <attr name="shadow_thickness" format="dimension" />
    </declare-styleable>
</resources>

步驟二:在構造函數中讀取屬性

用 obtainStyledAttributes() 取得 TypedArray,依型別取值。務必記得用完呼叫 recycle(),否則會造成資源浪費:

public class ArrowRectangleView extends ViewGroup {

    public ArrowRectangleView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a = context.getTheme().obtainStyledAttributes(
                attrs, R.styleable.ArrowRectangleView, defStyleAttr, 0);
        for (int i = 0; i < a.getIndexCount(); i++) {
            int attr = a.getIndex(i);
            switch (attr) {
                case R.styleable.ArrowRectangleView_arrow_width:
                    mArrowWidth = a.getDimensionPixelSize(attr, mArrowWidth); break;
                case R.styleable.ArrowRectangleView_arrow_height:
                    mArrowHeight = a.getDimensionPixelSize(attr, mArrowHeight); break;
                case R.styleable.ArrowRectangleView_radius:
                    mRadius = a.getDimensionPixelSize(attr, mRadius); break;
                case R.styleable.ArrowRectangleView_background_color:
                    mBackgroundColor = a.getColor(attr, mBackgroundColor); break;
                case R.styleable.ArrowRectangleView_arrow_offset:
                    mArrowOffset = a.getDimensionPixelSize(attr, mArrowOffset); break;
                case R.styleable.ArrowRectangleView_shadow_color:
                    mShadowColor = a.getColor(attr, mShadowColor); break;
                case R.styleable.ArrowRectangleView_shadow_thickness:
                    mShadowThickness = a.getDimensionPixelSize(attr, mShadowThickness); break;
            }
        }
        a.recycle();
    }
}

步驟三:重寫 onMeasure()

高度方面:先為箭頭與圓角預留空間,再逐一測量可見的 child 並累加高度(含上下 margin),最後加上 padding 與陰影厚度。寬度方面:測量所有可見 child,取「寬度 + 左右 margin」的最大值,再加上 padding 與陰影。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int count = getChildCount();
    int maxWidth = 0;
    // 為箭頭與圓角預留高度
    int maxHeight = mArrowHeight + mRadius;

    for (int i = 0; i < count; i++) {
        final View child = getChildAt(i);
        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
        if (child.getVisibility() != GONE) {
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            maxWidth = Math.max(maxWidth, child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
            maxHeight = maxHeight + child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;
        }
    }

    maxWidth = maxWidth + getPaddingLeft() + getPaddingRight() + mShadowThickness;
    maxHeight = maxHeight + getPaddingTop() + getPaddingBottom() + mShadowThickness;
    setMeasuredDimension(maxWidth, maxHeight);
}

這裡有兩個容易卡住的小問題:

一、為什麼圓角只預留一個半徑,而不是上下各一個?純粹是視覺考量。上下各留一個半徑會讓邊框看起來很厚;在 onLayout() 中把菜單項往上移半個半徑,邊框就自然好看了。

二、child 的 LayoutParams 為什麼能強轉成 MarginLayoutParams?因為我們重寫了 generateLayoutParams(),告訴系統要用哪一種參數型別:

@Override
public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
    return new MarginLayoutParams(getContext(), attrs);
}

步驟四:重寫 onLayout()

把合適的 left/top/right/bottom 傳給每個 child 的 layout() 即可。注意這裡 top 只加了半個半徑,右側座標也減了半個半徑,與前面「往上提半個半徑」的設計呼應:

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    int count = getChildCount();
    int topOffset = t + mArrowHeight + mRadius / 2;
    for (int i = 0; i < count; i++) {
        final View child = getChildAt(i);
        int top = topOffset + i * child.getMeasuredHeight();
        int bottom = top + child.getMeasuredHeight();
        child.layout(l, top, r - mRadius / 2 - mShadowThickness, bottom);
    }
}

步驟五:重寫 dispatchDraw()

因為是容器,本身不需要「畫自己」,但要畫背景,所以重寫 dispatchDraw()(若繼承的是具體 View,則重寫 onDraw())。繪製分三步:

1. 圓角矩形:直接呼叫 drawRoundRect()。

2. 三角箭頭:依配置的偏移與寬高組出 Path,再用 drawPath()。

3. 陰影:換個顏色、位置略微偏移再畫一次圓角矩形,並加上模糊。模糊要靠 Paint.setMaskFilter() 搭配 BlurMaskFilter,而且必須關閉該圖層的硬體加速(API 文件有明確說明)。此外還要設定來源圖與目標圖的疊加模式,陰影要疊在菜單背後,因此選 PorterDuff.Mode.DST_OVER。

@Override
protected void dispatchDraw(Canvas canvas) {
    // 模糊 mask filter 需關閉硬體加速
    setLayerType(View.LAYER_TYPE_SOFTWARE, null);

    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setStyle(Paint.Style.FILL);
    // 陰影疊在菜單背後
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OVER));

    // 1. 圓角矩形
    paint.setColor(mBackgroundColor);
    canvas.drawRoundRect(new RectF(0, mArrowHeight,
                    getMeasuredWidth() - mShadowThickness,
                    getMeasuredHeight() - mShadowThickness),
            mRadius, mRadius, paint);

    // 2. 三角箭頭
    Path path = new Path();
    int startPoint = getMeasuredWidth() - mArrowOffset;
    path.moveTo(startPoint, mArrowHeight);
    path.lineTo(startPoint + mArrowWidth, mArrowHeight);
    path.lineTo(startPoint + mArrowWidth / 2, 0);
    path.close();
    canvas.drawPath(path, paint);

    // 3. 陰影
    if (mShadowThickness > 0) {
        paint.setMaskFilter(new BlurMaskFilter(mShadowThickness, BlurMaskFilter.Blur.OUTER));
        paint.setColor(mShadowColor);
        canvas.drawRoundRect(new RectF(mShadowThickness, mArrowHeight + mShadowThickness,
                        getMeasuredWidth() - mShadowThickness,
                        getMeasuredHeight() - mShadowThickness),
                mRadius, mRadius, paint);
    }

    super.dispatchDraw(canvas);
}

步驟六:在布局中引用

使用自定義 ViewGroup 與系統控制項有兩個小差異:一是必須寫完整的套件名稱,否則執行時會找不到元件;二是配置自定義屬性時要另外指定名字空間(例如 app),避免與 android 混淆。

<?xml version="1.0" encoding="utf-8"?>
<com.xinxin.arrowrectanglemenu.widget.ArrowRectangleView
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:background="@android:color/transparent"
    android:paddingLeft="3dp"
    android:paddingRight="3dp"
    android:splitMotionEvents="false"
    app:arrow_offset="31dp"
    app:arrow_width="16dp"
    app:arrow_height="8dp"
    app:radius="5dp"
    app:background_color="#ffb1df83"
    app:shadow_color="#66000000"
    app:shadow_thickness="5dp">

    <LinearLayout
        android:id="@+id/cmx_toolbar_menu_turn_off"
        android:layout_width="wrap_content"
        android:layout_height="42dp">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:text="Menu Item #1"
            android:textColor="#FF393F4A"
            android:textSize="16sp"
            android:paddingLeft="16dp"
            android:paddingRight="32dp"
            android:clickable="false" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/cmx_toolbar_menu_feedback"
        android:layout_width="wrap_content"
        android:layout_height="42dp">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:text="Menu Item #2"
            android:textColor="#FF393F4A"
            android:textSize="16sp"
            android:paddingLeft="16dp"
            android:paddingRight="32dp"
            android:clickable="false" />
    </LinearLayout>
</com.xinxin.arrowrectanglemenu.widget.ArrowRectangleView>

在程式碼中 inflate 這個布局的方式與一般布局沒有差別,建立彈出菜單時指定它即可。走過這一輪,自定義 ViewGroup 的完整流程(attrs → 屬性解析 → onMeasure → onLayout → dispatchDraw → 引用)就齊了;之後要做更複雜的容器,原理與步驟其實都一樣。

另外提醒:關閉硬體加速會讓這個菜單的渲染走 CPU,若菜單項很多、動畫很頻繁,建議只對陰影那一次繪製使用軟體層,或在 API 18 以上改用 setShadowLayer() 這類更省成本的方案。

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