觸摸事件學習系列文章詳見:
《Android Touch事件學習系列匯總》
還是回到onTouchEvent方法傳遞的參數MotionEvent類,其對象有四個方法可以擷取當前手指在螢幕上的位置資訊,但是一個是相對位址一個是絕對位址,以下具體看下區別。
一、Android Touch事件rawX,rawY與x,y的區別MotionEvent有四個方法getRawX(), event.getRawY(), getX(),getY(), 為什麼同樣是x,y軸幹嘛非得用兩個變數呢?
先來看下:
從可以看出來
rawX 和 rawY分別是中間觸摸點以螢幕左上方為0,0的相對位置,rawX = 223 說明裡觸摸點離螢幕最左側的距離是223
x 和 y 分別是觸摸點以灰色地區左上方為0,0的相對位置,x = 96 說明是觸摸點離灰色地區最左側的距離是96
rawX , rawY 相對於螢幕的座標
x,y 相對於當前控制項的座標
rawX, X 向右移動都是增大,向左移動都是減小
rawY, Y 向下移動都是增大,向上移動都是減小
二、對應代碼1. 中間的灰色地區是一個自訂TextView,用於監聽Touch事件,裡面有一個LogListener介面,用於在Actvity中即時Touch位置輸出資訊
public class CustomTextView extends TextView {private LogListener mLogListener;public CustomTextView(Context context) {super(context);}public CustomTextView(Context context, AttributeSet attrs) {super(context, attrs);}public CustomTextView(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);}public void setLogListener(LogListener pListener) {mLogListener = pListener;}@Overridepublic boolean onTouchEvent(MotionEvent event) {int action = event.getAction();switch (action) {case MotionEvent.ACTION_MOVE:float rawX = event.getRawX();float rawY = event.getRawY();float x = event.getX();float y = event.getY();if (mLogListener != null) {mLogListener.output("rawX = " + rawX + "\n rawY = " + rawY+ "\n x = " + x+ "\n Y = " + y);}break;}return true;}/** * 用於在Actvity中即時Touch位置輸出資訊 */public interface LogListener {public void output(String pOutput);}}
2. 在AndroidManifast.xml中配置布局
3. Activity中載入視圖,控制顯示touch位置資訊
public class TouchDemoActivity extends Activity {private TextView mOutput;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);mOutput = (TextView) findViewById(R.id.output);mOutput.setText("rawX = 0 \n rawY = 0 \n x = 0 \n Y = 0");CustomTextView customTextView = (CustomTextView) findViewById(R.id.custom_textview);customTextView.setLogListener(new CustomLogListener());}/** * 用於擷取TouchEvent中位置資訊 */private class CustomLogListener implements LogListener {@Overridepublic void output(String pOutput) {mOutput.setText( pOutput );}}}
下載
例子下載