Search code examples
androidviewgroupmotionevent

In Android, how can I detect max margin when using MotionEvent?


I'm using MotionEvent to drag views around on the Y axis. I don't, however, want the view to be further down than to the end of the screen. Currently it can go way beyond that which is really frustrating.

Relevant code:

public boolean onTouch(View view, MotionEvent event) {
    final int X = (int) event.getRawX();
    final int Y = (int) event.getRawY();
    switch (event.getAction() & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN:
            RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
            _yDelta = Y - lParams.bottomMargin;
            Log.i("Test1231", "ACTION_DOWN");
            break;
        case MotionEvent.ACTION_UP:
            Log.i("Test1231", "ACTION_UP");
            break;
        case MotionEvent.ACTION_POINTER_DOWN:
            Log.i("Test1231", "ACTION_POINTER_DOWN");
            break;
        case MotionEvent.ACTION_POINTER_UP:
            Log.i("Test1231", "ACTION_POINTER_UP");
            break;
        case MotionEvent.ACTION_MOVE:

            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
            layoutParams.bottomMargin = Y - _yDelta;
            view.setLayoutParams(layoutParams);
            Log.i("Test1231", "ACTION_MOVE");
            break;
    }
    _root.invalidate();
    return true;
}

Solution

  • try to "match_parent" the view inside of thr rootview. You should do it before the "switch". And once the pointer is up (ACTION_UP in your case) return everything to wrap_content).