handling touch events in Android when using multiple views/layouts

喜夏-厌秋 提交于 2019-12-24 08:50:02

问题


I'm very new to Android programming, and trying to understand touch events with nested views. To start, here's a description of my app:

I have a relative layout that I've added via the GUI editor. Everything is default. I've also created a class called ClipGrid that extends ScrollView. Nested inside that, I make a HorizontalScrollView. Inside of that, I make a TableLayout and it's rows. The rows contain buttons.

The end result is a grid of buttons. It displays 4x4 at once, but can scroll either direction to display other buttons.

I call it to the screen from my main activity like this: ClipGrid clip_grid = new ClipGrid(this); setContentView(clip_grid);

I did that just for testing purposes, and I think I will have to change it later when I want to add other views to my relativelayout. But I think it might have implications for touch events.

in the end, I want to detect when the grid has been moved and snap the newly viewable 4x4 grid of buttons to the edge of my layout when the user lifts their finger. I'm just not sure how to go about implementing this and any help would be appreciated. Thanks.


回答1:


The way touch events are handled is kind of a cascading effect that starts from the top view and goes down to the lower nested views. Basically, Android will pass the event to each view until true is returned.

The general way you could implement the onTouchEvent event of a View would be:

@Override
public boolean onTouchEvent(MotionEvent event) {
  boolean actionHandled = false;
  final int action = event.getAction();

  switch(action & MotionEventCompat.ACTION_MASK) {
    case MotionEvent.ACTION_DOWN:
      // user first touches view with pointer
      break;
    case MotionEvent.ACTION_MOVE:
      // user is still touching view and moving pointer around
      break;
    case MotionEvent.ACTION_UP:
      // user lifts pointer
      break;
  }

  // if the action was not handled by this touch, send it to other views
  if (!actionHandled) 
     actionHandled |= super.onTouch(v, MotionEvent.event);

  return actionHandled;
}


来源:https://stackoverflow.com/questions/11934932/handling-touch-events-in-android-when-using-multiple-views-layouts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!