我被要求修改現有代碼作爲在線課程的一部分。目前,該應用程序註冊並顯示屏幕所在位置的x和y座標以及以毫秒爲單位的時間量。如何在Android Touch事件(動作事件)上獲取開始和結束座標?
我想添加獲取開始和結束座標的函數,即手指在拖動時開始和結束的位置。目前註冊的座標似乎只是最後的座標。我如何添加兩組座標(例如,如果我想計算運動事件的距離)?這是代碼的一部分。 感謝您的幫助!
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
Calendar tiempoInicio = null;
Calendar tiempoFinal = null;
@Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int)event.getX();
int y = (int)event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
tiempoInicio = Calendar.getInstance();
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
tiempoFinal = Calendar.getInstance();
Intent intent = new Intent (
AplicacionSencillaActivity.this,
AplicacionSencillaResults.class);
Bundle bundle = new Bundle();
bundle.putLong(
"TIEMPOPRESIONADO",
tiempoFinal.getTimeInMillis() -
tiempoInicio.getTimeInMillis());
bundle.putInt("X", x);
bundle.putInt("Y", y);
intent.putExtras(bundle);
startActivity(intent);
break;
謝謝伊萬!然而,該應用程序仍然只註冊最後的座標。我需要在ACTION_DOWN期間獲取X和getY,正如Geobits在下面所說的那樣?如果是這樣,我應該把代碼放在哪裏? –
是的,我認爲這就是你已經做的:)它的工作方式是你收到屏幕給你的所有事件,這是你的工作,找出發生了什麼。我會使用一個成員來存儲狀態。像'boolean mIsSwiping'。當你收到'ACTION_DOWN'時,將它設置爲'true'並讀取你的起點座標。當你收到'ACTION_UP'時:如果'mIsSwiping'爲'true',那麼讀取結束座標並將'mIsSwiping'設置爲'false',如果不是的話 - 無事可做。 –
看看這個參考:http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.3_r1/android/widget/ScrollView.java#483請注意如何對於'ACTION_DOWN',他們基本上把'mIsBeingDragged'設置爲'true',對於'ACTION_U'P或'ACTION_CANCEL',這取決於孩子的數量,但這是因爲它是'ScrollView',你不能滾動,除非它有一個孩子。將'mIsBeingDragged'設置爲false –