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

Android 自定義 ViewGroup(一)——帶箭頭的圓角矩形菜單

編輯:關於 Android 程式設計

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

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

最偷工減料的做法是請 UX 切一張三角形圖片貼上去,但這樣既不體面,不同解析度也不好適配,於是決定自己寫一個 ViewGroup。

其實自定義 ViewGroup 並不難,基本都有固定套路。

一、定義 attrs.xml

先聲明這個自定義 View 有哪些可配置屬性。這裡一共 7 個:箭頭寬度、箭頭高度、箭頭水平偏移、圓角半徑、菜單背景色、陰影色、陰影厚度。

<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>

二、繼承 ViewGroup 並在構造函數中讀取屬性

用 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()

先想高度:要為箭頭和圓角預留空間,所以 maxHeight 初始值加上這兩項;接著遍歷所有可見的 child,用現成的 measureChild() 測量,把高度累加進 maxHeight,同時把上下 margin 算進去;最後再加上上下 padding 和陰影高度,交給 setMeasuredDimension() 生效。

再想寬度:同樣先用 measureChild() 測量所有可見 child,然後比較它們的寬度加上左右 margin,取最大值;再加上左右 padding 與陰影寬度,最後 setMeasuredDimension()。

@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);
}

兩個值得說明的小問題:

1. 為圓角預留高度時,為什麼只留一個半徑而不是上下各一個?純粹是視覺考量。上下各留一個半徑會讓菜單邊框顯得很厚。後面做 onLayout 時會發現,佈局菜單項時會往上移半個半徑,這樣邊框看起來就對稱好看了。

2. Child 的 LayoutParams 為什麼能強轉成 MarginLayoutParams?因為重寫了 generateLayoutParams(),返回我們想要的類型:

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

四、重寫 onLayout()

每個 View 都有 layout() 方法,我們要做的只是把合適的 left / top / right / bottom 傳進去。這裡可以看到,佈局菜單項時往上提了半個半徑,所以 topOffset 只加了半個半徑,右側坐標也只減了半個半徑。

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

五、重寫 dispatchDraw()

ViewGroup 容器本身不需要繪製內容,所以要重寫 dispatchDraw()。如果自定義的是具體的 View,則重寫 onDraw() 即可。

繪製分三步:

1. 畫圓角矩形——直接呼叫 Canvas 的 drawRoundRect();
2. 畫三角箭頭——依配置屬性組出一條 Path,再用 drawPath() 繪製;
3. 畫菜單陰影——本質上是換個顏色、偏移一點再畫一個圓角矩形,並加上模糊。

模糊效果要透過 Paint 的 setMaskFilter() 實現,同時必須關閉該圖層的硬體加速,這一點在 API 文檔裡有明確說明。

另外還要設定源圖與目標圖的重疊模式。陰影要疊在菜單背後,所以選 DST_OVER:

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

    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setColor(mBackgroundColor);
    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 與系統 ViewGroup 有兩個小差異:一是必須寫完整的包名,否則運行時會報找不到組件;二是配置自定義屬性時要另外指定命名空間,避免與預設的 android 命名空間混淆。

<com.xinxin.arrowrectanglemenu.widget.arrowrectangleview
    android:background="@android:color/transparent"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:orientation="vertical"
    android:paddingleft="3dp"
    android:paddingright="3dp"
    android:splitmotionevents="false"
    app:arrow_height="8dp"
    app:arrow_offset="31dp"
    app:arrow_width="16dp"
    app:background_color="#ffb1df83"
    app:radius="5dp"
    app:shadow_color="#66000000"
    app:shadow_thickness="5dp"
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto">

    <linearlayout
        android:id="@+id/cmx_toolbar_menu_turn_off"
        android:layout_height="42dp"
        android:layout_width="wrap_content">
        <textview
            android:clickable="false"
            android:layout_gravity="center_vertical"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:paddingleft="16dp"
            android:paddingright="32dp"
            android:text="Menu Item #1"
            android:textcolor="#FF393F4A"
            android:textsize="16sp">
        </textview>
    </linearlayout>

    <linearlayout
        android:id="@+id/cmx_toolbar_menu_feedback"
        android:layout_height="42dp"
        android:layout_width="wrap_content">
        <textview
            android:clickable="false"
            android:layout_gravity="center_vertical"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:paddingleft="16dp"
            android:paddingright="32dp"
            android:text="Menu Item #2"
            android:textcolor="#FF393F4A"
            android:textsize="16sp">
        </textview>
    </linearlayout>
</com.xinxin.arrowrectanglemenu.widget.arrowrectangleview>

七、在代碼中引用

這一步與引用普通布局沒有差別,只是在建立彈出菜單時指定剛才那個布局文件。

至此,一個自定義 ViewGroup 的完整流程就走過一遍了。後續可能還會寫更複雜的控件,但原理與步驟都是相通的,本文算拋磚引玉。

項目地址:https://github.com/qianxin2016/ArrowRectangleMenu

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