Battleroid Battleroid - 11 days ago 8
Android Question

Android custom view is offset when while moving

I'm trying to move a custom view that is in my main activity with a single touch input, however the x/y coordinates for the event are offset due to the action bar.

GIF of problem

I'm trying to find a way to negate the size of the action bar to the y coordinate but nothing seems to be working. I've subtracting the difference in the parent view and my custom view's size from the y coordinate

getRootView().getHeight() - getHeight()
but the value is incorrect.

Can anyone point me in the right direction?

The custom view:

public class SampleView extends View {

private Paint paint;
private Path path = new Path();

public SampleView(Context context) {
super(context);
init();
}

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

private void init() {
paint = new Paint();
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(10);
}

@Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, paint);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
final int x = (int) event.getRawX();
final int y = (int) event.getRawY();

switch(event.getActionMasked()) {
case MotionEvent.ACTION_DOWN: {
path.moveTo(x, y);
break;
}
case MotionEvent.ACTION_MOVE: {
path.lineTo(x, y);
break;
}
}

invalidate();
return true;
}

}


I haven't touched my MainActivity, but have added in the XML for activity_main my custom view:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.caseyweed.sample.MainActivity">

<com.caseyweed.sample.SampleView
android:layout_width="match_parent"
android:layout_height="match_parent" />

</RelativeLayout>

Answer

Use getX() and getY() instead of getRawX() and getRawY() if you want coordinates relative to the view instead of the device screen coordinates.