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

Android 自定義 View 實作:天氣趨勢折線圖

編輯:關於 Android 程式設計

先看效果:

控件結構並不複雜:一條折線,最高溫在上、最低溫在下,每個節點標註數值,點擊時回調該天的溫差。真正的工程量在於坐標計算與自定義屬性的封裝。

一、繼承 View 並提供兩個構造函數

public class TrendGraph extends View {
    public TrendGraph(Context context) {
        super(context);              // 代碼中 new 時調用
    }

    public TrendGraph(Context context, AttributeSet attrs) {
        super(context, attrs);       // XML 布局中 inflate 時調用
    }
}

由於控件始終以 match_parent 使用,這裡不重寫 onMeasure 也不會出問題。

二、onDraw 的坐標計算

折線本質就是把一串點連起來,所以關鍵是把每個點的位置算準。這段代碼略顯冗長,但邏輯直白:

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    if (mElements == null || mElements.size() == 0) {
        return;
    }
    double max_up = getMaxUp();
    double min_down = getMinDown();
    canvas.setDrawFilter(mDrawFilter);
    mPaint.setStrokeWidth(lineWeith);

    float width = getWidth();
    float grap = width / mElements.size();          // 每個節點佔用的橫向寬度
    float textSize = mTextPaint.getTextSize();
    int textMargin = circleRadius * 2;
    float margin_top = textSize + 2 * textMargin;
    float height = getHeight() - 2 * margin_top;

    for (int i = 0; i < mElements.size() - 1; i++) {
        float startX = i * grap + grap / 2;
        float stopX = (i + 1) * grap + grap / 2;

        float startY = (float) (max_up - mElements.get(i).getUp()) / (float) (max_up - min_down) * height + margin_top;
        float stopY = (float) (max_up - mElements.get(i + 1).getUp()) / (float) (max_up - min_down) * height + margin_top;
        canvas.drawText((int) mElements.get(i).getUp() + "℃", startX - textSize, startY - textMargin, mTextPaint);
        canvas.drawCircle(startX, startY, circleRadius, mPaint);
        canvas.drawLine(startX, startY, stopX, stopY, mPaint);
        if (i == mElements.size() - 2) {
            canvas.drawText((int) mElements.get(i + 1).getUp() + "℃", stopX - textSize, stopY - textMargin, mTextPaint);
            canvas.drawCircle(stopX, stopY, circleRadius, mPaint);
        }

        // 最低溫折線,文字繪製在節點下方
        startY = (float) (max_up - mElements.get(i).getDown()) / (float) (max_up - min_down) * height + margin_top;
        stopY = (float) (max_up - mElements.get(i + 1).getDown()) / (float) (max_up - min_down) * height + margin_top;
        canvas.drawText((int) mElements.get(i).getDown() + "℃", startX - textSize, startY + textSize + textMargin, mTextPaint);
        canvas.drawCircle(startX, startY, circleRadius, mPaint);
        canvas.drawLine(startX, startY, stopX, stopY, mPaint);
        if (i == mElements.size() - 2) {
            canvas.drawText((int) mElements.get(i + 1).getDown() + "℃", stopX - textSize, stopY + textSize + textMargin, mTextPaint);
            canvas.drawCircle(stopX, stopY, circleRadius, mPaint);
        }
    }
}

三、定義自定義屬性

為了讓使用方能調整線寬、圓點大小、文字尺寸與顏色,需要在 res/values/attr.xml 中聲明:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="TrendGraph">
        <attr name="lineWidth" format="dimension"/>
        <attr name="circleRadius" format="dimension" />
        <attr name="textSize" format="dimension" />
        <attr name="textColor" format="reference" />
    </declare-styleable>
</resources>

format 決定屬性類型:dimension 表示尺寸,可寫 dp、sp、px;reference 表示引用其他資源,例如 @string/app_name。其他可用類型可查閱官方文檔。

解析必須放在帶 AttributeSet 的構造函數中:

public TrendGraph(Context context, AttributeSet attrs) {
    super(context, attrs);
    TypedArray array = getContext().obtainStyledAttributes(attrs, R.styleable.TrendGraph);
    circleRadius = array.getDimensionPixelSize(R.styleable.TrendGraph_circleRadius, 5);
    lineWeith = array.getDimensionPixelSize(R.styleable.TrendGraph_lineWidth, 3);
    mTextPaint.setTextSize(array.getDimensionPixelSize(R.styleable.TrendGraph_textSize, 35));
    mTextPaint.setColor(array.getColor(R.styleable.TrendGraph_textColor, Color.BLACK));
    array.recycle();
}

getDimensionPixelSize 會把 dp/sp 直接換算成像素,省掉手動轉換的麻煩。但要留意:它返回的默認值單位仍然是 px,不是 dp。

使用時在布局中加上命名空間,Android Studio 會自動補全 app 前綴:

xmlns:app=https://schemas.android.com/apk/res-auto
<com.fndroid.byweather.views.TrendGraph
    android:id="@+id/tg"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    app:textColor="@color/colorAccent"
    app:textSize="22sp"
    app:circleRadius="2dp" />

四、加入點擊回調

① 定義接口:

public interface onItemClickListener {
    void onItemClick(View view, Element element);
}

② 在 View 中持有接口並提供 setter:

public class TrendGraph extends View {
    private onItemClickListener mOnItemClickListener;

    public void setOnItemClickListener(onItemClickListener listener) {
        mOnItemClickListener = listener;
    }
}

③ 在 onTouchEvent 中區分點擊與滑動。由於頁面外層套了 NestedScrollView,若不做判斷,滑動時也會觸發點擊,因此需要一個標記位:

@Override
public boolean onTouchEvent(MotionEvent event) {
    int itemWidth = getWidth() / mElements.size();
    boolean isMove = false;
    switch (event.getAction()) {
        case MotionEvent.ACTION_MOVE:
            isMove = true;
            break;
        case MotionEvent.ACTION_UP:
            if (!isMove) {
                int position = (int) (event.getX() / itemWidth);
                if (position >= 0 && position < mElements.size()) {
                    mOnItemClickListener.onItemClick(this, mElements.get(position));
                }
            }
            break;
    }
    return true;
}

④ Activity 中註冊並處理:

historyGraph.setOnItemClickListener(this);

@Override
public void onItemClick(View view, TrendGraph.Element element) {
    int dt = (int) (element.getUp() - element.getDown());
    Snackbar.make(root, "當天溫差為:" + dt + "℃", Snackbar.LENGTH_SHORT).show();
}

小結

自定義 View 的難點通常不在 API,而在坐標體系的推演。把「一屏有多寬、每格多寬、數值如何映射到 Y 軸」這三件事想清楚,其餘的繪製調用都只是堆疊。有疑問歡迎留言交流。

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