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

Android 自定義 View:繼承 View 並重寫 onDraw 等關鍵方法

編輯:關於 Android 程式設計

自定義 View 是 Android 開發中的基本功。做法並不複雜:繼承 View,然後按需重寫若干方法。方法很多,取決於你想實現什麼效果,本文以一個「跟隨手指移動的圓」為例,說明最起碼需要動到的部分。

一、自定義 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 開放自定義屬性給佈局使用。本文只是示範最基本需要重寫的方法。

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