【问题标题】:Android custom view is offset when while moving移动时Android自定义视图偏移
【发布时间】:2016-11-26 20:11:46
【问题描述】:

我正在尝试通过单次触摸输入来移动位于我的主要活动中的自定义视图,但是由于操作栏,事件的 x/y 坐标发生了偏移。

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,但在我的自定义视图中为 activity_main 添加了 XML:

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

【问题讨论】:

    标签: android android-layout view android-view mobile-development


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-12
      • 1970-01-01
      • 2011-07-19
      • 1970-01-01
      • 2018-06-12
      • 1970-01-01
      • 2018-03-30
      • 2012-02-19
      相关资源
      最近更新 更多