一步一步学android之事件篇——触摸事件
触摸事件顾名思义就是触摸手机屏幕触发的事件,当用户触摸添加了触摸事件的View时,就是执行OnTouch()方法进行处理,下面通过一个动态获取坐标的例子来学习OnTouchListener事件,效果如下:
main.xml:
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;}});}}