Android

[Android] 화면 터치 좌표값 얻기, 파일 입출력

EEEUN 2022. 9. 6. 12:52

화면을 눌렀다가 손을 뗐을 때의 좌표값 출력

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        int action = event.getAction();
        curX = event.getX();  //눌린 곳의 X좌표
        curY = event.getY();  //눌린 곳의 Y좌표

        // 화면을 눌렀다 뗐을 때 좌표값 출력
        if(action == event.ACTION_UP) {
            xyView.setText(curX + ", " + curY);
        }
        return super.dispatchTouchEvent(event);
    }

 

좌표값 파일에 저장(Write)

private void onFileWrite() {
    String contents = xyView.getText().toString() + "\n";

    try {
        if (!dir.exists()) {
            dir.mkdirs();
        }
        if (!file.exists()) {
            Log.d(TAG, "WriteTextFile: 파일이 존재하지 않음");
            file.createNewFile();
        }
        FileWriter writer = new FileWriter(file, true); // 계속 이어서 쓸 수 있음
        writer.write(contents);
        writer.close();
    } catch(IOException e) {
        e.printStackTrace();
    }
}

 

파일에 저장한 좌표값들 출력(Read)

private void onFileRead() {
    try {
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line;
        while ((line = reader.readLine()) != null) {
            Log.d(TAG, "onFileRead: " + line);
        }
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

 

파일에 저장된 좌표값 순서대로 화면 터치 시뮬레이션

private void simulateClick(float x, float y) {
    long downTime = SystemClock.uptimeMillis();
    long eventTime = SystemClock.uptimeMillis();
    MotionEvent.PointerProperties[] properties = new MotionEvent.PointerProperties[1];
    MotionEvent.PointerProperties pp1 = new MotionEvent.PointerProperties();
    pp1.id = 0;
    pp1.toolType = MotionEvent.TOOL_TYPE_FINGER;
    properties[0] = pp1;
    MotionEvent.PointerCoords[] pointerCoords = new MotionEvent.PointerCoords[1];
    MotionEvent.PointerCoords pc1 = new MotionEvent.PointerCoords();
    pc1.x = x;
    pc1.y = y;
    pc1.pressure = 1;
    pc1.size = 1;
    pointerCoords[0] = pc1;
    MotionEvent motionEvent = MotionEvent.obtain(downTime, eventTime,
            MotionEvent.ACTION_DOWN, 1, properties,
            pointerCoords, 0,  0, 1, 1, 0, 0, 0, 0 );
    dispatchTouchEvent(motionEvent);

    motionEvent = MotionEvent.obtain(downTime, eventTime,
            MotionEvent.ACTION_UP, 1, properties,
            pointerCoords, 0,  0, 1, 1, 0, 0, 0, 0 );
    dispatchTouchEvent(motionEvent);

    Log.d(TAG, "simulateClick: x, y " + pc1.x + ", " + pc1.y);
}