本文主要是介绍关于OnTouchListener用法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
常常会设置监听器,但是OnTouchListener类处理监听器类TouchListener时总是用错,借此记录下它的常用语法:package com.example.test;import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;public class MainActivity extends Activity {private View myView = null;private final String tag="output";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);this.requestWindowFeature(Window.FEATURE_NO_TITLE);this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);setContentView(R.layout.activity_main);myView = (View)findViewById(R.id.myView);myView.setOnTouchListener(new OnTouchListener() {@Overridepublic boolean onTouch(View V, MotionEvent e) {int x;int y;switch(e.getAction()){case MotionEvent.ACTION_DOWN:x=(int)e.getX();y=(int)e.getY();Log.d(tag,"x="+x+", y="+y);//System.out.println("x="+x+" y="+y);break;case MotionEvent.ACTION_MOVE:x=(int)e.getX();y=(int)e.getY();Log.d(tag,"x="+x+", y="+y);System.out.println("x="+x+" y="+y);break;case MotionEvent.ACTION_UP:x=(int)e.getX();y=(int)e.getY();Log.d(tag,"x="+x+", y="+y);System.out.println("x="+x+" y="+y);break;}// TODO 自动生成的方法存根return false;}});}@Overridepublic 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;}}
在设置监听器时利用匿名监听类覆写public boolean onTouch(View V, MotionEvent e)方法,进行监听的设置,其中监听Touch时,有几种动作要注意,ACTION_DOWN,ACTION_MOVE,ACTION_UP分别指的是屏幕开始触摸,滑动,离开屏幕动作,设置完以后,尤其要注意返回值的作用,具体情况如下:
1.如果返回值为true,那么系统会连续处理触摸事件,处理完一个触摸事件以后,不会执行结束,而是准备执行下一次操作。
2.如果返回值为flase,那么系统只会处理触摸事件一次,处理完后,就以结束为准,不会再触发事件的处理。
这篇关于关于OnTouchListener用法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!