0

我想通过一个触摸输入移动位于我的主要活动中的自定义视图,但是由于操作栏的原因,该事件的x/y坐标会偏移。Android自定义视图在移动时偏移

GIF of problem

我试图找到一种方式来否定操作栏到Y的大小的坐标,但似乎没有奏效。我已经从y坐标getRootView().getHeight() - getHeight()减去父视图和我的自定义视图的大小的差异,但值不正确。

任何人都可以指向正确的方向吗?

该自定义视图:

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; 
    } 

} 

我都没有碰过我的MainActivity,但在XML已经添加了activity_main我的自定义视图:

<?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> 

回答

2

使用getX()getY()代替getRawX()getRawY()如果您想要相对于视图的坐标而不是设备屏幕坐标。

+0

我现在觉得很愚蠢。非常感谢。 – Battleroid