本文實(shí)例為大家分享了android獲取手指觸摸位置的具體代碼,供大家參考,具體內(nèi)容如下
手機(jī)屏幕事件的處理方法onTouchEvent。該方法在View類中的定義,并且所有的View子類全部重寫了該方法,應(yīng)用程序可以通過(guò)該方法處理手機(jī)屏幕的觸摸事件。
其原型是:
1
|
public boolean onTouchEvent(MotionEvent event) |
參數(shù)event:參數(shù)event為手機(jī)屏幕觸摸事件封裝類的對(duì)象,其中封裝了該事件的所有信息,例如觸摸的位置、觸摸的類型以及觸摸的時(shí)間等。該對(duì)象會(huì)在用戶觸摸手機(jī)屏幕時(shí)被創(chuàng)建。
返回值:該方法的返回值機(jī)理與鍵盤響應(yīng)事件的相同,同樣是當(dāng)已經(jīng)完整地處理了該事件且不希望其他回調(diào)方法再次處理時(shí)返回true,否則返回false。
該方法并不像之前介紹過(guò)的方法只處理一種事件,一般情況下以下三種情況的事件全部由onTouchEvent方法處理,只是三種情況中的動(dòng)作值不同。
屏幕被按下:當(dāng)屏幕被按下時(shí),會(huì)自動(dòng)調(diào)用該方法來(lái)處理事件,此時(shí)MotionEvent.getAction()的值為MotionEvent.ACTION_DOWN,如果在應(yīng)用程序中需要處理屏幕被按下的事件,只需重新該回調(diào)方法,然后在方法中進(jìn)行動(dòng)作的判斷即可。
屏幕被抬起:當(dāng)觸控筆離開屏幕時(shí)觸發(fā)的事件,該事件同樣需要onTouchEvent方法來(lái)捕捉,然后在方法中進(jìn)行動(dòng)作判斷。當(dāng)MotionEvent.getAction()的值為MotionEvent.ACTION_UP時(shí),表示是屏幕被抬起的事件。
在屏幕中拖動(dòng):該方法還負(fù)責(zé)處理觸控筆在屏幕上滑動(dòng)的事件,同樣是調(diào)用MotionEvent.getAction()方法來(lái)判斷動(dòng)作值是否為MotionEvent.ACTION_MOVE再進(jìn)行處理。
示例代碼如下:
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文件中添加三個(gè)編輯文本框分別用來(lái)顯示坐標(biāo)的X Y以及手指是按下 抬起還是處于移動(dòng)。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/hongkangwl/article/details/19162883