2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Android] 画面上のタップされた位置(座標)を取得する

2
Last updated at Posted at 2018-07-22

概要

静電気を用いたスタンプをアプリ上で押してもらい、タッチされた座標を照合することでスタンプの整合性を確認する場合など、Android端末の画面上でユーザがタップした位置の座標を取得したい場合があります。その場合、ActivityクラスのonTouchEventまたはdispatchTouchEventメソッドをオーバーライドすることで、タップされた位置の座標を複数取得することができます。

用例

Activityクラス
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        this.onTouchEvent(event);

        return super.dispatchTouchEvent(event);
    }

    private void onTouchEvent(MotionEvent motionEvent) {
        // タップされた位置を取得する(指を離さずに動かした場合等は除外)
        if (event.getActionMasked() == MotionEvent.ACTION_DOWN || 
            event.getActionMasked() == MotionEvent.ACTION_POINTER_DOWN) {
            StringBuilder builder = new StringBuilder();
            this.coordinates = new ArrayList<>();
            int count = event.getPointerCount();

            // 複数箇所がタップされた場合に対応
            for (int i = 0; i < count; i++) {
                int x = (int) event.getX(i);
                int y = (int) event.getY(i);
                Logger.d("# X: " + x + ", y: " + y + ", PointerID: " + event.getPointerId(i));
                builder.append("(" + x + "," + y + "),");

                Coordinate coordinate = new Coordinate(x, y);
                this.coordinates.add(coordinate);
            }

            Logger.d("# 座標: " + builder.toString());
        }
    }

Coordinateクラス
public class Coordinate {
    private int x;
    private int y;

    public Coordinate(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }
}
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?