編輯:關於 Android 程式設計
自定義 View 是 Android 開發中的基本功。做法並不複雜:繼承 View,然後按需重寫若干方法。方法很多,取決於你想實現什麼效果,本文以一個「跟隨手指移動的圓」為例,說明最起碼需要動到的部分。
package com.example.engineerjspview;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
/**
* 自定義 EngineerJspView
* @author Engineer-Jsp
* @date 2014.10.28
*/
public class EngineerJspView extends View {
public float E_X = 188;
public float E_Y = 188;
Paint paint = new Paint();
public EngineerJspView(Context context) {
super(context);
}
public EngineerJspView(Context context, AttributeSet set) {
super(context, set);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setColor(Color.RED);
canvas.drawCircle(E_X, E_Y, 88, paint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
E_X = event.getX();
E_Y = event.getY();
invalidate(); // 觸發重繪
return false;
}
@Override
protected void onAnimationStart() {
super.onAnimationStart();
}
@Override
protected void onAnimationEnd() {
super.onAnimationEnd();
}
}
幾個重點值得留意:onDraw() 是繪製的入口,所有自定義圖形都在這裡畫;onTouchEvent() 中改動座標後必須呼叫 invalidate() 才會觸發重繪;另外原始碼中 E_X = event.getY() 應為 E_Y = event.getY(),這裡順手修正。
在 XML 中直接使用自定義 View,要用完整類名作為標籤:
<RelativeLayout 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=".MainActivity" >
<com.example.engineerjspview.EngineerJspView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
package com.example.engineerjspview;
import android.os.Bundle;
import android.app.Activity;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

自定義 View 的應用遠不止畫圖形:需要時還可以重寫 onMeasure() 決定測量尺寸、onSizeChanged() 響應尺寸變化、onSaveInstanceState() 保存狀態,或透過自定義 AttributeSet 搭配 attrs.xml 開放自定義屬性給佈局使用。本文只是示範最基本需要重寫的方法。
手機QQ怎麼完全退出 兩種登出方式說明
有時關掉了手機QQ,卻仍然能收到消息,想徹底退出該怎麼做?下面我們一起來看。 手機QQ退出登入教學 方法一:退出QQ程序 第一步:打開手機QQ。 第二步:點擊手機上的【菜
自定義 SurfaceView 結合傳感器:手繪指南針實戰
概述 SurfaceView 是 Android 中極為重要的繪圖容器,它的圖像繪製被放在主線程之外的另一個線程中完成,除了繪圖,還能用來播放視頻。本文就用它來繪製一個會
Android Path 實作貝茲曲線:打造 QQ 風格可拖拽氣泡
這兩天研究了 Path 繪製貝茲曲線的用法,順手做了一個類似 QQ 未讀訊息的可拖拽小氣泡,效果如下: 基本原理 核心就是用 Path 畫出兩段三點的二次貝茲曲線並閉
Android 仿天貓下拉刷新自定義控制項深度解析
一、概述 本控制項以 android-Ultra-Pull-to-Refresh 為基礎,針對其 header 進行客製化擴充。它繼承自 PtrFrameLayout,