本文實例為大家分享了android獲取手指觸摸位置的具體代碼,供大家參考,具體內容如下
手機屏幕事件的處理方法onTouchEvent。該方法在View類中的定義,并且所有的View子類全部重寫了該方法,應用程序可以通過該方法處理手機屏幕的觸摸事件。
其原型是:
1
|
public boolean onTouchEvent(MotionEvent event) |
參數event:參數event為手機屏幕觸摸事件封裝類的對象,其中封裝了該事件的所有信息,例如觸摸的位置、觸摸的類型以及觸摸的時間等。該對象會在用戶觸摸手機屏幕時被創建。
返回值:該方法的返回值機理與鍵盤響應事件的相同,同樣是當已經完整地處理了該事件且不希望其他回調方法再次處理時返回true,否則返回false。
該方法并不像之前介紹過的方法只處理一種事件,一般情況下以下三種情況的事件全部由onTouchEvent方法處理,只是三種情況中的動作值不同。
屏幕被按下:當屏幕被按下時,會自動調用該方法來處理事件,此時MotionEvent.getAction()的值為MotionEvent.ACTION_DOWN,如果在應用程序中需要處理屏幕被按下的事件,只需重新該回調方法,然后在方法中進行動作的判斷即可。
屏幕被抬起:當觸控筆離開屏幕時觸發的事件,該事件同樣需要onTouchEvent方法來捕捉,然后在方法中進行動作判斷。當MotionEvent.getAction()的值為MotionEvent.ACTION_UP時,表示是屏幕被抬起的事件。
在屏幕中拖動:該方法還負責處理觸控筆在屏幕上滑動的事件,同樣是調用MotionEvent.getAction()方法來判斷動作值是否為MotionEvent.ACTION_MOVE再進行處理。
示例代碼如下:
MainActivity.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
package com.example.touchpostionshow; import android.os.Bundle; import android.app.Activity; import android.util.Log; import android.view.Menu; import android.view.MotionEvent; import android.widget.EditText; public class MainActivity extends Activity { public EditText pox,poY,condition; @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_main); pox = (EditText)findViewById(R.id.editText1); poY = (EditText)findViewById(R.id.editText2); condition = (EditText)findViewById(R.id.editText3); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true ; } @Override public boolean onTouchEvent(MotionEvent event) { float x = event.getX(); float y = event.getY(); try { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: pox.setText( "" +x);poY.setText( "" +y);condition.setText( "down" ); break ; case MotionEvent.ACTION_UP:pox.setText( "" +x);poY.setText( "" +y);condition.setText( "up" ); break ; case MotionEvent.ACTION_MOVE:pox.setText( "" +x);poY.setText( "" +y);condition.setText( "move" ); break ; } return true ; } catch (Exception e) { Log.v( "touch" , e.toString()); return false ; } } } |
XML文件中添加三個編輯文本框分別用來顯示坐標的X Y以及手指是按下 抬起還是處于移動。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/hongkangwl/article/details/19162883