为了展示getX()、getRawX()和getTop()方法的区别,我们写了一个简单的测试Demo,我们写了一个自定义控件(继承ImageView)。
package com.demo.ui;import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.ImageView;public class ImageViewTest extends ImageView {public ImageViewTest(Context context, @Nullable AttributeSet attrs) {super(context, attrs);}@Overridepublic boolean onTouchEvent(MotionEvent event) {int eventaction = event.getAction();switch (eventaction){case MotionEvent.ACTION_DOWN:break;case MotionEvent.ACTION_MOVE:int top, left;float rawx, rawy, x, y;top = getTop();left = getLeft();rawx = event.getRawX();rawy = event.getRawY();x = event.getX();y = event.getY();Log.i("TAG", "getTop() : " + top);Log.i("TAG", "getLeft() : " + left);Log.i("TAG", "getRawX() : " + rawx);Log.i("TAG", "getRawY() : " + rawy);Log.i("TAG", "getX() : " + x);Log.i("TAG", "getY() : " + y);break;case MotionEvent.ACTION_UP:break;}return super.onTouchEvent(event);}
}
当你触摸ImageViewTest控件的时候:
-
getTop()、getLeft()
:当前控件左上角相对于父容器控件的坐标; -
getRawX()、getRawY()
:当前触摸点相对于屏幕的坐标; -
getX()、getY()
:当前触摸点相对于当前控件的坐标;