Android獲取點擊屏幕的位置坐標
更新時間:2018年05月26日 08:32:20 作者:carter_yu
這篇文章主要為大家詳細介紹了Android獲取點擊屏幕的位置坐標,具有一定的參考價值,感興趣的小伙伴們可以參考一下
在Android開發(fā)過程中,有時需要獲取觸摸位置的坐標,以便作進一步處理,比如做炫酷的動畫效果,或者響應其他操作。
本文簡單介紹Android中觸屏操作時,觸屏的開始位置、當前位置、結(jié)束位置。
布局:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.com.TouchTest" > <LinearLayout android:id="@+id/ll_touch" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/touch_show_start" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> <TextView android:id="@+id/touch_show" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> </LinearLayout> </RelativeLayout>
Activity中的操作:
public class TouchTest extends Activity implements OnTouchListener { private TextView tvTouchShowStart; private TextView tvTouchShow; private LinearLayout llTouch; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_touch_test); init(); } private void init() { tvTouchShowStart = (TextView) findViewById(R.id.touch_show_start); tvTouchShow = (TextView) findViewById(R.id.touch_show); llTouch = (LinearLayout) findViewById(R.id.ll_touch); llTouch.setOnTouchListener(this); } @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { /** * 點擊的開始位置 */ case MotionEvent.ACTION_DOWN: tvTouchShowStart.setText("起始位置:(" + event.getX() + "," + event.getY()); break; /** * 觸屏實時位置 */ case MotionEvent.ACTION_MOVE: tvTouchShow.setText("實時位置:(" + event.getX() + "," + event.getY()); break; /** * 離開屏幕的位置 */ case MotionEvent.ACTION_UP: tvTouchShow.setText("結(jié)束位置:(" + event.getX() + "," + event.getY()); break; default: break; } /** * 注意返回值 * true:view繼續(xù)響應Touch操作; * false:view不再響應Touch操作,故此處若為false,只能顯示起始位置,不能顯示實時位置和結(jié)束位置 */ return true; } }
效果圖:
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android開發(fā)之ListView的head消失頁面導航欄的漸變出現(xiàn)和隱藏
這篇文章主要介紹了Android開發(fā)之ListView的head消失頁面導航欄的漸變出現(xiàn)和隱藏的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-11-11android 6.0下webview的定位權(quán)限設置方法
今天小編就為大家分享一篇android 6.0下webview的定位權(quán)限設置方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07Android 8.0升級不跳轉(zhuǎn)應用安裝頁面的解決方法
這篇文章主要為大家詳細介紹了Android 8.0升級不跳轉(zhuǎn)應用安裝頁面的解決方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-06-06