首页 > 解决方案 > 如何将每个坐标存储到二维数组 Android

问题描述

Android中有方法onTouchEvent()。我从这种方法中得到xy坐标。我想将每个坐标存储到二维数组中。我该怎么做?有什么建议么 ??

以下是我的代码

 @Override
public boolean onTouchEvent(MotionEvent event) {
    int x = (int) event.getX();
    int y = (int) event.getY();
    switch (event.getAction()){
        case MotionEvent.ACTION_DOWN:
            Log.e("TAG", "Action down :==>>"+ x + "," + y + "");
            return true;
        case MotionEvent.ACTION_MOVE:
            return true;
        case MotionEvent.ACTION_UP:
            Log.e("TAG", "Action up:==>>"+ x + "," + y + "");
            return true;
        case (MotionEvent.ACTION_CANCEL) :
            Log.d("TAG","Action was CANCEL");
            return true;
        case (MotionEvent.ACTION_OUTSIDE) :
            Log.d("TAG","Movement occurred outside bounds ");
            return true;
        default :
            return false;
    }
}

标签: android

解决方案


创建用于存储坐标的 POJO 类

public class CoordinatePoint {
    int x, y;

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

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }
}

现在ArrayList<CoordinatePoint>在您的活动中创建,您可以在其中创建和存储对象。您可以使用 CoordinatePoint 对象的构造函数或设置值xy使用 setter 方法。并使用 getter 方法获取分配的值。

编辑正如@pskink 所建议的,您还可以使用Point / PointF类来实现您想要的功能,而无需创建单独的类。在此处此处查看文档。


推荐阅读