Android 事件触发机制的深入学习

 Android 事件触发机制的深入学习

最近在研究android的事件触发和传播机制,说来很惭愧,web下的事件太熟悉不过了,可在android中却很郁闷,常用的触摸事件都糊里糊涂的,在网上看了半天,也整理一份,供大家参考:

public class CustomDefaultActivity implements OnTouchListener { 
  private GestureDetector gd1; 
  private TableLayout tableLayout; 
 
  @Override 
  protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.custom_default); 
    tableLayout = (TableLayout) findViewById(R.id.tableLayout); 
    gd1 = new GestureDetector(CustomDefaultActivity.this, new MyGesture()); 
    tableLayout.setOnTouchListener(this); 
    tableLayout.setLongClickable(true); 
  } 
 
  @Override 
  public boolean dispatchTouchEvent(MotionEvent event) { 
    Log.e("-----------------------------------------------------------------------", 
      "dispatchTouchEvent"); 
 
    if (gd1.onTouchEvent(event)) { 
      event.setAction(MotionEvent.ACTION_CANCEL); 
    } 
 
    return super.dispatchTouchEvent(event); 
  } 
 
  @Override 
  public boolean onTouch(View arg0, MotionEvent arg1) { 
    Log.e("-------", "onTouch"); 
 
    return gd1.onTouchEvent(arg1); 
  } 
 
  public class MyGesture implements OnGestureListener { 
    @Override 
    public boolean onDown(MotionEvent arg0) { 
      Log.e("-------", 
        "onDown, 按下时触发[" + arg0.getX() + "," + arg0.getY() + "]"); 
 
      return true; 
    } 
 
    @Override 
    public void onLongPress(MotionEvent arg0) { 
      Log.e("-------", "onLongPress,长时间按住时触发"); 
    } 
 
    @Override 
    public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2, 
      float arg3) { 
      Log.e("-------", 
        "onScroll,滑动拖动事件[" + arg0.getX() + "," + arg0.getY() + "]=[" + 
        arg1.getX() + "," + arg1.getY() + "]"); 
 
      return true; 
    } 
 
    @Override 
    public boolean onFling(MotionEvent arg0, MotionEvent arg1, float arg2, 
      float arg3) { 
      Log.e("-------", "onFling, 滑动甩出事件"); 
 
      return true; 
    } 
 
    @Override 
    public void onShowPress(MotionEvent arg0) { 
      Log.e("-------", "onShowPress,down事件发生,而move或up还没发生前触发该事件"); 
    } 
 
    @Override 
    public boolean onSingleTapUp(MotionEvent arg0) { 
      Log.e("-------", "onSingleTapUp 释放事件"); 
 
      return true; 
    } 
  } 
} 

监控触摸事件,主要是实现OnGestureListener类,并重写其中的几个方法,以监听事件发生。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!