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

Android 自定義控件:做一個跟著手指跑的小圓球

編輯:關於 Android 程式設計

自定義 View 最直觀的入門練習,就是畫一個跟手指移動的圓。核心只有兩件事:onDraw 負責畫,onTouchEvent 負責改坐標並請求重繪。

一、自定義 DrawView

package com.example.androidtest0.myView;

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;

public class DrawView extends View {

    public float currentX = 40;
    public float currentY = 50;

    // 定義並創建畫筆
    Paint p = new Paint();

    public DrawView(Context context) {
        super(context);
    }

    public DrawView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        p.setColor(Color.RED);
        canvas.drawCircle(currentX, currentY, 15, p);
    }

    /** 重寫觸摸事件處理方法 */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        currentX = event.getX();
        currentY = event.getY();
        invalidate();       // 通知自己重繪
        return true;
    }
}

invalidate() 會觸發一次 onDraw,這就是「改數據 → 重繪」的閉環。返回 true 表示事件已被消費,後續的 MOVE、UP 才會繼續送進來。

二、兩種掛載方式

方式一:純代碼添加

custom_layout.xml 只留一個容器:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
</LinearLayout>

Activity 中動態 new 出來再 addView:

public class CustomView extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.custom_layout);

        LinearLayout root = (LinearLayout) findViewById(R.id.root);

        final DrawView drawView = new DrawView(this);
        drawView.setMinimumWidth(10);
        drawView.setMinimumHeight(10);

        root.addView(drawView);
    }
}

三、更推薦的方式:寫在布局裡

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/root"
    android:orientation="vertical" >

    <com.example.androidtest0.myView.DrawView
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

此時 Activity 只需 setContentView,系統會自動調用帶 AttributeSet 的構造函數——這也說明了為什麼自定義 View 至少要實現 (Context) 和 (Context, AttributeSet) 兩個構造。

四、延伸思考

  • 如果手指移出控件邊界,坐標會變成負數或超出寬高,圓球會被裁剪。需要限制範圍時,在 onTouchEvent 裡做一次 clamp 即可。
  • 频繁 invalidate() 在滑動時可能造成掉幀,可考慮改用 postInvalidate() 或在 CHANGE 之外的狀態才觸發重繪。
  • 若要支援多点,需要處理 ACTION_POINTER_DOWN 並用 getActionIndex() 取當前手指。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved