触摸事件顾名思义就是触摸手机屏幕触发的事件,当用户触摸添加了触摸事件的View时,就是执行OnTouch()方法进行处理,下面通过一个动态获取坐标的例子来学习OnTouchListener事件,效果如下:

一步一步学android之事件篇——触摸事件一步一步学android之事件篇——触摸事件一步一步学android之事件篇——触摸事件

main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/LinearLayout1"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical">    <TextView        android:id="@+id/show"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:textColor="#ff00ff"        android:textSize="20sp"        android:text="实时显示坐标" /></LinearLayout>


MainActivity.java:

package com.example.onkeylistenerdemo;import android.app.Activity;import android.os.Bundle;import android.util.EventLog.Event;import android.view.MotionEvent;import android.view.View;import android.widget.LinearLayout;import android.widget.TextView;public class MainActivity extends Activity {private TextView show = null;private LinearLayout linearLayout = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initView();}private void initView(){show = (TextView)super.findViewById(R.id.show);linearLayout = (LinearLayout)super.findViewById(R.id.LinearLayout1);linearLayout.setOnTouchListener(new View.OnTouchListener() {@Overridepublic boolean onTouch(View v, MotionEvent event) {// TODO Auto-generated method stubswitch(event.getAction()){case MotionEvent.ACTION_DOWN:System.out.println("---action down-----");show.setText("起始位置为:"+"("+event.getX()+" , "+event.getY()+")");break;case MotionEvent.ACTION_MOVE:System.out.println("---action move-----");show.setText("移动中坐标为:"+"("+event.getX()+" , "+event.getY()+")");break;case MotionEvent.ACTION_UP:System.out.println("---action up-----");show.setText("最后位置为:"+"("+event.getX()+" , "+event.getY()+")");}return true;}});}}


我在代码中加了输出,大家可以在logcat中清楚看见是如何执行的,我这里也不重复说明,今天就到这里了。

更多相关文章

  1. ListView与其中的Button,EditText等Widget的click事件
  2. Android事件分发机制浅分析
  3. Android ViewGroup/View 事件分发机制详解
  4. Android屏幕坐标和LCD坐标的转换
  5. android图片透明度跟缩放大小动画事件
  6. Android事件分发机制深度解析(View篇)
  7. Android事件分发之前做了啥?

随机推荐

  1. Android代码优化——使用Android(安卓)li
  2. 在android的状态栏(statusbar)中增加menu
  3. 十八般武艺!移动应用开发者必备的18款利器
  4. Android(安卓)SoftAp支持 (一)
  5. android 读取assets文件夹下的文件资源
  6. Android开发中后台的Service服务探索
  7. 使用NDK移植开源项目,JNI的使用技巧
  8. Android(安卓)群英传-第五章:Android(安
  9. android drawBitmapMesh and drawVertice
  10. eclipse项目导入android studio 各类问题