編輯:關於 Android 程式設計
先看效果:

控件結構並不複雜:一條折線,最高溫在上、最低溫在下,每個節點標註數值,點擊時回調該天的溫差。真正的工程量在於坐標計算與自定義屬性的封裝。
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 也不會出問題。
折線本質就是把一串點連起來,所以關鍵是把每個點的位置算準。這段代碼略顯冗長,但邏輯直白:
@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 軸」這三件事想清楚,其餘的繪製調用都只是堆疊。有疑問歡迎留言交流。
Android 系统联系人全特效实现(上):分组导航与挤压动画(附源码)
记得刚接触 Android 时,我对系统联系人中的特效很感兴趣:它会根据手机中联系人姓氏的首字母进行分组,并在界面最顶端始终显示当前的分组。最让我着迷的是,当后一个分组和
Android 表格版面 TableLayout 範例詳解
一、表格版面 TableLayout TableLayout 以列與行的形式管理子元素,每一行通常是一個 TableRow 物件,也可以是普通的 View;TableRo
Android 自訂軟鍵盤:Keyboard 與 KeyboardView 完整實作教學
翻資料時無意間發現了 android.inputmethodservice.Keyboard 這個類,原來 Android 早就內建了自訂鍵盤的能力,不需要自己拿一堆 B
為什麼Android開發者都愛用Genymotion?速度與真機體驗兼得的模擬器
如果你還在用 Android 原生的 AVD 調試程式,那種「點一下、等三秒」的煎熬大概不必多說。Genymotion 在開發者圈子裡口碑極佳,理由其實非常直白:跑得快、