Example usage for android.view View onTouchEvent

List of usage examples for android.view View onTouchEvent

Introduction

In this page you can find the example usage for android.view View onTouchEvent.

Prototype

public boolean onTouchEvent(MotionEvent event) 

Source Link

Document

Implement this method to handle touch screen motion events.

Usage

From source file:com.fortysevendeg.swipelistview.ExpandableSwipeListViewTouchListener.java

/**
 * @see android.view.View.OnTouchListener#onTouch(android.view.View, android.view.MotionEvent)
 *///  www  .  j  a  va2 s.  com
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
    if (!isSwipeEnabled()) {
        return false;
    }

    if (viewWidth < 2) {
        viewWidth = swipeListView.getWidth();
    }

    switch (MotionEventCompat.getActionMasked(motionEvent)) {
    case MotionEvent.ACTION_DOWN: {
        if (paused && downPosition != ListView.INVALID_POSITION) {
            return false;
        }
        swipeCurrentAction = SwipeListView.SWIPE_ACTION_NONE;

        int childCount = swipeListView.getChildCount();
        int[] listViewCoords = new int[2];
        swipeListView.getLocationOnScreen(listViewCoords);
        int x = (int) motionEvent.getRawX() - listViewCoords[0];
        int y = (int) motionEvent.getRawY() - listViewCoords[1];
        View child;
        for (int i = 0; i < childCount; i++) {
            child = swipeListView.getChildAt(i);

            child.getHitRect(rect);

            int childPosition = swipeListView.getPositionForView(child);

            // dont allow swiping if this is on the header or footer or IGNORE_ITEM_VIEW_TYPE or enabled is false on the adapter
            boolean allowSwipe = swipeListView.getAdapter().isEnabled(childPosition)
                    && swipeListView.getAdapter().getItemViewType(childPosition) >= 0;

            if (allowSwipe && rect.contains(x, y)) {

                //verify if it is a group:
                if (child.findViewById(swipeGroupView) != null) {
                    return false;
                }

                setParentView(child);
                setFrontView(child.findViewById(swipeFrontView));

                downX = motionEvent.getRawX();
                downPosition = childPosition - swipeListView.getHeaderViewsCount();

                frontView.setClickable(!opened.get(downPosition));
                frontView.setLongClickable(!opened.get(downPosition));

                velocityTracker = VelocityTracker.obtain();
                velocityTracker.addMovement(motionEvent);
                if (swipeBackView > 0) {
                    setBackView(child.findViewById(swipeBackView));
                }
                break;
            }
        }
        view.onTouchEvent(motionEvent);
        return true;
    }

    case MotionEvent.ACTION_UP: {
        if (velocityTracker == null || !swiping || downPosition == ListView.INVALID_POSITION) {
            break;
        }

        float deltaX = motionEvent.getRawX() - downX;
        velocityTracker.addMovement(motionEvent);
        velocityTracker.computeCurrentVelocity(1000);
        float velocityX = Math.abs(velocityTracker.getXVelocity());
        if (!opened.get(downPosition)) {
            if (swipeMode == SwipeListView.SWIPE_MODE_LEFT && velocityTracker.getXVelocity() > 0) {
                velocityX = 0;
            }
            if (swipeMode == SwipeListView.SWIPE_MODE_RIGHT && velocityTracker.getXVelocity() < 0) {
                velocityX = 0;
            }
        }
        float velocityY = Math.abs(velocityTracker.getYVelocity());
        boolean swap = false;
        boolean swapRight = false;
        if (minFlingVelocity <= velocityX && velocityX <= maxFlingVelocity && velocityY * 2 < velocityX) {
            swapRight = velocityTracker.getXVelocity() > 0;
            if (SwipeListView.DEBUG) {
                Log.d(SwipeListView.TAG, "swapRight: " + swapRight + " - swipingRight: " + swipingRight);
            }
            if (swapRight != swipingRight && swipeActionLeft != swipeActionRight) {
                swap = false;
            } else if (opened.get(downPosition) && openedRight.get(downPosition) && swapRight) {
                swap = false;
            } else if (opened.get(downPosition) && !openedRight.get(downPosition) && !swapRight) {
                swap = false;
            } else {
                swap = true;
            }
        } else if (Math.abs(deltaX) > viewWidth / 2) {
            swap = true;
            swapRight = deltaX > 0;
            /* Fix for the bug with left being allowed (with drag position) even when it is disabled */
            if (swapRight && swipeMode == SwipeListView.SWIPE_MODE_LEFT) {
                swap = false;
            } else if (!swapRight && swipeMode == SwipeListView.SWIPE_MODE_RIGHT) {
                swap = false;
            }
            /* ------------------------------ */
        }

        generateAnimate(frontView, swap, swapRight, downPosition);
        if (swipeCurrentAction == SwipeListView.SWIPE_ACTION_CHOICE) {
            swapChoiceState(downPosition);
        }

        velocityTracker.recycle();
        velocityTracker = null;
        downX = 0;
        // change clickable front view
        //                if (swap) {
        //                    frontView.setClickable(opened.get(downPosition));
        //                    frontView.setLongClickable(opened.get(downPosition));
        //                }
        swiping = false;
        break;
    }

    case MotionEvent.ACTION_MOVE: {
        if (velocityTracker == null || paused || downPosition == ListView.INVALID_POSITION) {
            break;
        }

        velocityTracker.addMovement(motionEvent);
        velocityTracker.computeCurrentVelocity(1000);
        float velocityX = Math.abs(velocityTracker.getXVelocity());
        float velocityY = Math.abs(velocityTracker.getYVelocity());

        float deltaX = motionEvent.getRawX() - downX;
        float deltaMode = Math.abs(deltaX);

        int swipeMode = this.swipeMode;
        int changeSwipeMode = swipeListView.changeSwipeMode(downPosition);
        if (changeSwipeMode >= 0) {
            swipeMode = changeSwipeMode;
        }

        if (swipeMode == SwipeListView.SWIPE_MODE_NONE) {
            deltaMode = 0;
        } else if (swipeMode != SwipeListView.SWIPE_MODE_BOTH) {
            if (opened.get(downPosition)) {
                if (swipeMode == SwipeListView.SWIPE_MODE_LEFT && deltaX < 0) {
                    deltaMode = 0;
                } else if (swipeMode == SwipeListView.SWIPE_MODE_RIGHT && deltaX > 0) {
                    deltaMode = 0;
                }
            } else {
                if (swipeMode == SwipeListView.SWIPE_MODE_LEFT && deltaX > 0) {
                    deltaMode = 0;
                } else if (swipeMode == SwipeListView.SWIPE_MODE_RIGHT && deltaX < 0) {
                    deltaMode = 0;
                }
            }
        }
        if (deltaMode > slop && swipeCurrentAction == SwipeListView.SWIPE_ACTION_NONE
                && velocityY < velocityX) {
            swiping = true;
            swipingRight = (deltaX > 0);
            if (SwipeListView.DEBUG) {
                Log.d(SwipeListView.TAG, "deltaX: " + deltaX + " - swipingRight: " + swipingRight);
            }
            if (opened.get(downPosition)) {
                swipeListView.onStartClose(downPosition, swipingRight);
                swipeCurrentAction = SwipeListView.SWIPE_ACTION_REVEAL;
            } else {
                if (swipingRight && swipeActionRight == SwipeListView.SWIPE_ACTION_DISMISS) {
                    swipeCurrentAction = SwipeListView.SWIPE_ACTION_DISMISS;
                } else if (!swipingRight && swipeActionLeft == SwipeListView.SWIPE_ACTION_DISMISS) {
                    swipeCurrentAction = SwipeListView.SWIPE_ACTION_DISMISS;
                } else if (swipingRight && swipeActionRight == SwipeListView.SWIPE_ACTION_CHOICE) {
                    swipeCurrentAction = SwipeListView.SWIPE_ACTION_CHOICE;
                } else if (!swipingRight && swipeActionLeft == SwipeListView.SWIPE_ACTION_CHOICE) {
                    swipeCurrentAction = SwipeListView.SWIPE_ACTION_CHOICE;
                } else {
                    swipeCurrentAction = SwipeListView.SWIPE_ACTION_REVEAL;
                }
                swipeListView.onStartOpen(downPosition, swipeCurrentAction, swipingRight);
            }
            swipeListView.requestDisallowInterceptTouchEvent(true);
            MotionEvent cancelEvent = MotionEvent.obtain(motionEvent);
            cancelEvent.setAction(MotionEvent.ACTION_CANCEL | (MotionEventCompat
                    .getActionIndex(motionEvent) << MotionEventCompat.ACTION_POINTER_INDEX_SHIFT));
            swipeListView.onTouchEvent(cancelEvent);
            if (swipeCurrentAction == SwipeListView.SWIPE_ACTION_CHOICE) {
                backView.setVisibility(View.GONE);
            }
        }

        if (swiping && downPosition != ListView.INVALID_POSITION) {
            if (opened.get(downPosition)) {
                deltaX += openedRight.get(downPosition) ? viewWidth - rightOffset : -viewWidth + leftOffset;
            }
            move(deltaX);
            return true;
        }
        break;
    }
    }
    return false;
}

From source file:il.co.globes.android.swipeListView.SwipeListViewTouchListener.java

/**
 * @see View.OnTouchListener#onTouch(android.view.View,
 *      android.view.MotionEvent)/*from  w w w  .  j a  v  a  2s  .c o  m*/
 */
// @Override
// public boolean onTouch(View view, MotionEvent motionEvent)
// {
// if (!isSwipeEnabled())
// {
// return false;
// }
//
// if (viewWidth < 2)
// {
// viewWidth = swipeListView.getWidth();
// }
//
// switch (MotionEventCompat.getActionMasked(motionEvent))
// {
// case MotionEvent.ACTION_DOWN :
// {
// if (paused && downPosition != ListView.INVALID_POSITION)
// {
// return false;
// }
// swipeCurrentAction = SwipeListView.SWIPE_ACTION_NONE;
//
// int childCount = swipeListView.getChildCount();
// int[] listViewCoords = new int[2];
// swipeListView.getLocationOnScreen(listViewCoords);
// int x = (int) motionEvent.getRawX() - listViewCoords[0];
// int y = (int) motionEvent.getRawY() - listViewCoords[1];
// View child;
// for (int i = 0; i < childCount; i++)
// {
// child = swipeListView.getChildAt(i);
// child.getHitRect(rect);
//
// int childPosition = swipeListView.getPositionForView(child);
//
// // dont allow swiping if this is on the header or footer or
// // IGNORE_ITEM_VIEW_TYPE or enabled is false on the adapter
// boolean allowSwipe = swipeListView.getAdapter().isEnabled(childPosition)
// && swipeListView.getAdapter().getItemViewType(childPosition) >= 0;
//
// if (allowSwipe && rect.contains(x, y))
// {
// setParentView(child);
// setFrontView(child.findViewById(swipeFrontView));
//
// downX = motionEvent.getRawX();
// downPosition = childPosition;
//
// frontView.setClickable(!opened.get(downPosition));
// frontView.setLongClickable(!opened.get(downPosition));
//
// velocityTracker = VelocityTracker.obtain();
// velocityTracker.addMovement(motionEvent);
// if (swipeBackView > 0)
// {
// setBackView(child.findViewById(swipeBackView));
// }
// break;
// }
// }
// view.onTouchEvent(motionEvent);
// return true;
// }
//
// case MotionEvent.ACTION_UP :
// {
// if (velocityTracker == null || !swiping || downPosition ==
// ListView.INVALID_POSITION)
// {
// break;
// }
//
// float deltaX = motionEvent.getRawX() - downX;
// velocityTracker.addMovement(motionEvent);
// velocityTracker.computeCurrentVelocity(1000);
// float velocityX = Math.abs(velocityTracker.getXVelocity());
// if (!opened.get(downPosition))
// {
// if (swipeMode == SwipeListView.SWIPE_MODE_LEFT &&
// velocityTracker.getXVelocity() > 0)
// {
// velocityX = 0;
// }
// if (swipeMode == SwipeListView.SWIPE_MODE_RIGHT &&
// velocityTracker.getXVelocity() < 0)
// {
// velocityX = 0;
// }
// }
// float velocityY = Math.abs(velocityTracker.getYVelocity());
// boolean swap = false;
// boolean swapRight = false;
// if (minFlingVelocity <= velocityX && velocityX <= maxFlingVelocity &&
// velocityY * 2 < velocityX)
// {
// swapRight = velocityTracker.getXVelocity() > 0;
// Log.d("SwipeListView", "swapRight: " + swapRight + " - swipingRight: " +
// swipingRight);
// if (swapRight != swipingRight && swipeActionLeft != swipeActionRight)
// {
// swap = false;
// }
// else if (opened.get(downPosition) && openedRight.get(downPosition) &&
// swapRight)
// {
// swap = false;
// }
// else if (opened.get(downPosition) && !openedRight.get(downPosition) &&
// !swapRight)
// {
// swap = false;
// }
// else
// {
// swap = true;
// }
// }
// else if (Math.abs(deltaX) > viewWidth / 2)
// {
// swap = true;
// swapRight = deltaX > 0;
// }
// generateAnimate(frontView, swap, swapRight, downPosition);
// if (swipeCurrentAction == SwipeListView.SWIPE_ACTION_CHOICE)
// {
// swapChoiceState(downPosition);
// }
//
// velocityTracker.recycle();
// velocityTracker = null;
// downX = 0;
// // change clickable front view
// // if (swap) {
// // frontView.setClickable(opened.get(downPosition));
// // frontView.setLongClickable(opened.get(downPosition));
// // }
// swiping = false;
// break;
// }
//
// case MotionEvent.ACTION_MOVE :
// {
// if (velocityTracker == null || paused || downPosition ==
// ListView.INVALID_POSITION)
// {
// break;
// }
//
// velocityTracker.addMovement(motionEvent);
// velocityTracker.computeCurrentVelocity(1000);
// float velocityX = Math.abs(velocityTracker.getXVelocity());
// float velocityY = Math.abs(velocityTracker.getYVelocity());
//
// float deltaX = motionEvent.getRawX() - downX;
// float deltaMode = Math.abs(deltaX);
//
// int swipeMode = this.swipeMode;
// int changeSwipeMode = swipeListView.changeSwipeMode(downPosition);
// if (changeSwipeMode >= 0)
// {
// swipeMode = changeSwipeMode;
// }
//
// if (swipeMode == SwipeListView.SWIPE_MODE_NONE)
// {
// deltaMode = 0;
// }
// else if (swipeMode != SwipeListView.SWIPE_MODE_BOTH)
// {
// if (opened.get(downPosition))
// {
// if (swipeMode == SwipeListView.SWIPE_MODE_LEFT && deltaX < 0)
// {
// deltaMode = 0;
// }
// else if (swipeMode == SwipeListView.SWIPE_MODE_RIGHT && deltaX > 0)
// {
// deltaMode = 0;
// }
// }
// else
// {
// if (swipeMode == SwipeListView.SWIPE_MODE_LEFT && deltaX > 0)
// {
// deltaMode = 0;
// }
// else if (swipeMode == SwipeListView.SWIPE_MODE_RIGHT && deltaX < 0)
// {
// deltaMode = 0;
// }
// }
// }
// if (deltaMode > slop && swipeCurrentAction ==
// SwipeListView.SWIPE_ACTION_NONE && velocityY < velocityX)
// {
// swiping = true;
// swipingRight = (deltaX > 0);
// Log.d("SwipeListView", "deltaX: " + deltaX + " - swipingRight: " +
// swipingRight);
// if (opened.get(downPosition))
// {
// swipeListView.onStartClose(downPosition, swipingRight);
// swipeCurrentAction = SwipeListView.SWIPE_ACTION_REVEAL;
// }
// else
// {
// if (swipingRight && swipeActionRight ==
// SwipeListView.SWIPE_ACTION_DISMISS)
// {
// swipeCurrentAction = SwipeListView.SWIPE_ACTION_DISMISS;
// }
// else if (!swipingRight && swipeActionLeft ==
// SwipeListView.SWIPE_ACTION_DISMISS)
// {
// swipeCurrentAction = SwipeListView.SWIPE_ACTION_DISMISS;
// }
// else if (swipingRight && swipeActionRight ==
// SwipeListView.SWIPE_ACTION_CHOICE)
// {
// swipeCurrentAction = SwipeListView.SWIPE_ACTION_CHOICE;
// }
// else if (!swipingRight && swipeActionLeft ==
// SwipeListView.SWIPE_ACTION_CHOICE)
// {
// swipeCurrentAction = SwipeListView.SWIPE_ACTION_CHOICE;
// }
// else
// {
// swipeCurrentAction = SwipeListView.SWIPE_ACTION_REVEAL;
// }
// swipeListView.onStartOpen(downPosition, swipeCurrentAction,
// swipingRight);
// }
// swipeListView.requestDisallowInterceptTouchEvent(true);
// MotionEvent cancelEvent = MotionEvent.obtain(motionEvent);
// cancelEvent.setAction(MotionEvent.ACTION_CANCEL
// | (MotionEventCompat.getActionIndex(motionEvent) <<
// MotionEventCompat.ACTION_POINTER_INDEX_SHIFT));
// swipeListView.onTouchEvent(cancelEvent);
// if (swipeCurrentAction == SwipeListView.SWIPE_ACTION_CHOICE)
// {
// backView.setVisibility(View.GONE);
// }
// }
//
// if (swiping && downPosition != ListView.INVALID_POSITION)
// {
// if (opened.get(downPosition))
// {
// deltaX += openedRight.get(downPosition) ? viewWidth - rightOffset :
// -viewWidth + leftOffset;
// }
// move(deltaX);
// return true;
// }
// break;
// }
// }
// return false;
// }
//

@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
    if (!isSwipeEnabled()) {
        return false;
    }

    if (viewWidth < 2) {
        viewWidth = swipeListView.getWidth();
    }

    switch (MotionEventCompat.getActionMasked(motionEvent)) {
    case MotionEvent.ACTION_DOWN: {
        if (paused && downPosition != ListView.INVALID_POSITION) {
            return false;
        }
        swipeCurrentAction = SwipeListView.SWIPE_ACTION_NONE;

        int childCount = swipeListView.getChildCount();
        int[] listViewCoords = new int[2];
        swipeListView.getLocationOnScreen(listViewCoords);
        int x = (int) motionEvent.getRawX() - listViewCoords[0];
        int y = (int) motionEvent.getRawY() - listViewCoords[1];
        View child;
        for (int i = 0; i < childCount; i++) {
            child = swipeListView.getChildAt(i);
            child.getHitRect(rect);

            int childPosition = swipeListView.getPositionForView(child);

            // dont allow swiping if this is on the header or footer or
            // IGNORE_ITEM_VIEW_TYPE or enabled is false on the adapter
            boolean allowSwipe = swipeListView.getAdapter().isEnabled(childPosition)
                    && swipeListView.getAdapter().getItemViewType(childPosition) >= 0;

            if (allowSwipe && rect.contains(x, y)) {
                setParentView(child);
                setFrontView(child.findViewById(swipeFrontView));

                downX = motionEvent.getRawX();
                downPosition = childPosition;

                frontView.setClickable(!opened.get(downPosition));
                frontView.setLongClickable(!opened.get(downPosition));

                velocityTracker = VelocityTracker.obtain();
                velocityTracker.addMovement(motionEvent);
                if (swipeBackView > 0) {
                    setBackView(child.findViewById(swipeBackView));
                }
                break;
            }
        }
        view.onTouchEvent(motionEvent);
        return true;
    }

    case MotionEvent.ACTION_UP: {
        if (velocityTracker == null || !swiping || downPosition == ListView.INVALID_POSITION) {
            break;
        }

        float deltaX = motionEvent.getRawX() - downX;
        velocityTracker.addMovement(motionEvent);
        velocityTracker.computeCurrentVelocity(1000);
        float velocityX = Math.abs(velocityTracker.getXVelocity());
        if (!opened.get(downPosition)) {
            if (swipeMode == SwipeListView.SWIPE_MODE_LEFT && velocityTracker.getXVelocity() > 0) {
                velocityX = 0;
            }
            if (swipeMode == SwipeListView.SWIPE_MODE_RIGHT && velocityTracker.getXVelocity() < 0) {
                velocityX = 0;
            }
        }
        float velocityY = Math.abs(velocityTracker.getYVelocity());
        boolean swap = false;
        boolean swapRight = false;
        if (minFlingVelocity <= velocityX && velocityX <= maxFlingVelocity && velocityY * 2 < velocityX) {
            swapRight = velocityTracker.getXVelocity() > 0;
            Log.d("SwipeListView", "swapRight: " + swapRight + " - swipingRight: " + swipingRight);
            if (swapRight != swipingRight && swipeActionLeft != swipeActionRight) {
                swap = false;
            } else if (opened.get(downPosition) && openedRight.get(downPosition) && swapRight) {
                swap = false;
            } else if (opened.get(downPosition) && !openedRight.get(downPosition) && !swapRight) {
                swap = false;
            } else {
                swap = true;
            }
        } else if (Math.abs(deltaX) > viewWidth / 2) {
            swap = true;
            swapRight = deltaX > 0;
        }
        generateAnimate(frontView, swap, swapRight, downPosition);
        if (swipeCurrentAction == SwipeListView.SWIPE_ACTION_CHOICE) {
            swapChoiceState(downPosition);
        }

        velocityTracker.recycle();
        velocityTracker = null;
        downX = 0;
        // change clickable front view
        // if (swap) {
        // frontView.setClickable(opened.get(downPosition));
        // frontView.setLongClickable(opened.get(downPosition));
        // }
        swiping = false;
        break;
    }

    case MotionEvent.ACTION_MOVE: {
        if (velocityTracker == null || paused || downPosition == ListView.INVALID_POSITION) {
            break;
        }

        velocityTracker.addMovement(motionEvent);
        velocityTracker.computeCurrentVelocity(1000);
        float velocityX = Math.abs(velocityTracker.getXVelocity());
        float velocityY = Math.abs(velocityTracker.getYVelocity());

        float deltaX = motionEvent.getRawX() - downX;
        float deltaMode = Math.abs(deltaX);

        int swipeMode = this.swipeMode;
        int changeSwipeMode = swipeListView.changeSwipeMode(downPosition);
        if (changeSwipeMode >= 0) {
            swipeMode = changeSwipeMode;
        }

        if (swipeMode == SwipeListView.SWIPE_MODE_NONE) {
            deltaMode = 0;
        } else if (swipeMode != SwipeListView.SWIPE_MODE_BOTH) {
            if (opened.get(downPosition)) {
                if (swipeMode == SwipeListView.SWIPE_MODE_LEFT && deltaX < 0) {
                    deltaMode = 0;
                } else if (swipeMode == SwipeListView.SWIPE_MODE_RIGHT && deltaX > 0) {
                    deltaMode = 0;
                }
            } else {
                if (swipeMode == SwipeListView.SWIPE_MODE_LEFT && deltaX > 0) {
                    deltaMode = 0;
                } else if (swipeMode == SwipeListView.SWIPE_MODE_RIGHT && deltaX < 0) {
                    deltaMode = 0;
                }
            }
        }
        if (deltaMode > slop && swipeCurrentAction == SwipeListView.SWIPE_ACTION_NONE
                && velocityY < velocityX) {
            swiping = true;
            swipingRight = (deltaX > 0);
            Log.d("SwipeListView", "deltaX: " + deltaX + " - swipingRight: " + swipingRight);
            if (opened.get(downPosition)) {
                swipeListView.onStartClose(downPosition, swipingRight);
                swipeCurrentAction = SwipeListView.SWIPE_ACTION_REVEAL;
            } else {
                if (swipingRight && swipeActionRight == SwipeListView.SWIPE_ACTION_DISMISS) {
                    swipeCurrentAction = SwipeListView.SWIPE_ACTION_DISMISS;
                } else if (!swipingRight && swipeActionLeft == SwipeListView.SWIPE_ACTION_DISMISS) {
                    swipeCurrentAction = SwipeListView.SWIPE_ACTION_DISMISS;
                } else if (swipingRight && swipeActionRight == SwipeListView.SWIPE_ACTION_CHOICE) {
                    swipeCurrentAction = SwipeListView.SWIPE_ACTION_CHOICE;
                } else if (!swipingRight && swipeActionLeft == SwipeListView.SWIPE_ACTION_CHOICE) {
                    swipeCurrentAction = SwipeListView.SWIPE_ACTION_CHOICE;
                } else {
                    swipeCurrentAction = SwipeListView.SWIPE_ACTION_REVEAL;
                }
                swipeListView.onStartOpen(downPosition, swipeCurrentAction, swipingRight);
            }
            swipeListView.requestDisallowInterceptTouchEvent(true);
            MotionEvent cancelEvent = MotionEvent.obtain(motionEvent);
            cancelEvent.setAction(MotionEvent.ACTION_CANCEL | (MotionEventCompat
                    .getActionIndex(motionEvent) << MotionEventCompat.ACTION_POINTER_INDEX_SHIFT));
            swipeListView.onTouchEvent(cancelEvent);
            if (swipeCurrentAction == SwipeListView.SWIPE_ACTION_CHOICE) {
                backView.setVisibility(View.GONE);
            }
        }

        if (swiping && downPosition != ListView.INVALID_POSITION) {
            if (opened.get(downPosition)) {
                deltaX += openedRight.get(downPosition) ? viewWidth - rightOffset : -viewWidth + leftOffset;
            }
            move(deltaX);
            return true;
        }
        break;
    }
    }

    closeOtherOpenedItems();
    view.onTouchEvent(motionEvent);
    return true;

    // return false;
}

From source file:com.xpread.swipelistview.SwipeListViewTouchListener.java

/**
 * @see View.OnTouchListener#onTouch(android.view.View,
 *      android.view.MotionEvent)/*from  ww  w  . java 2s .  c  om*/
 */
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {

    if (!isSwipeEnabled()) {
        return false;
    }

    if (viewWidth < 2) {
        viewWidth = swipeListView.getWidth();
    }

    switch (MotionEventCompat.getActionMasked(motionEvent)) {
    case MotionEvent.ACTION_DOWN: {
        if (paused && downPosition != ListView.INVALID_POSITION) {
            return false;
        }

        swipeCurrentAction = SwipeListView.SWIPE_ACTION_NONE;

        int childCount = swipeListView.getChildCount();
        int[] listViewCoords = new int[2];
        swipeListView.getLocationOnScreen(listViewCoords);
        int x = (int) motionEvent.getRawX() - listViewCoords[0];
        int y = (int) motionEvent.getRawY() - listViewCoords[1];
        View child;
        for (int i = 0; i < childCount; i++) {
            child = swipeListView.getChildAt(i);
            child.getHitRect(rect);

            int childPosition = swipeListView.getPositionForView(child);

            // dont allow swiping if this is on the header or footer or
            // IGNORE_ITEM_VIEW_TYPE or enabled is false on the adapter
            boolean allowSwipe = swipeListView.getAdapter().isEnabled(childPosition)
                    && swipeListView.getAdapter().getItemViewType(childPosition) >= 0;

            if (allowSwipe && rect.contains(x, y)) {
                setParentView(child);

                setFrontView(child.findViewById(swipeFrontView), childPosition);
                boolean result = downPosition == SwipeListView.INVALID_POSITION;

                downPosition = childPosition;

                frontView.setClickable(true);
                frontView.setLongClickable(!opened.get(downPosition));

                changeSwipeMode = swipeListView.changeSwipeMode(downPosition);

                if (changeSwipeMode == SwipeListView.SWIPE_MODE_LEFT) {
                    right2Open.set(downPosition, false);
                } else if (changeSwipeMode == SwipeListView.SWIPE_MODE_RIGHT) {
                    right2Open.set(downPosition, true);
                }

                if (swipeBackView > 0) {
                    setBackView(child.findViewById(swipeBackView));
                }
                if (result) {
                    velocityTracker = VelocityTracker.obtain();
                    velocityTracker.addMovement(motionEvent);
                    downX = motionEvent.getRawX();
                }
                break;
            }
        }
        view.onTouchEvent(motionEvent);
        return true;
    }

    case MotionEvent.ACTION_UP: {
        if (velocityTracker == null || !swiping || downPosition == ListView.INVALID_POSITION) {
            break;
        }

        float deltaX = motionEvent.getRawX() - downX;
        velocityTracker.addMovement(motionEvent);
        velocityTracker.computeCurrentVelocity(1000);
        float velocityX = Math.abs(velocityTracker.getXVelocity());
        if (!opened.get(downPosition)) {
            if (swipeMode == SwipeListView.SWIPE_MODE_LEFT && velocityTracker.getXVelocity() > 0) {
                velocityX = 0;
            }
            if (swipeMode == SwipeListView.SWIPE_MODE_RIGHT && velocityTracker.getXVelocity() < 0) {
                velocityX = 0;
            }
        }
        float velocityY = Math.abs(velocityTracker.getYVelocity());
        boolean swap = false;
        boolean swapRight = false;
        if (minFlingVelocity <= velocityX && velocityX <= maxFlingVelocity && velocityY * 2 < velocityX) {
            swapRight = velocityTracker.getXVelocity() > 0;
            if (SwipeListView.DEBUG) {
                Log.d(SwipeListView.TAG, "swapRight: " + swapRight + " - swipingRight: " + swipingRight);
            }
            if (swapRight != swipingRight && swipeActionLeft != swipeActionRight) {
                swap = false;
            } else if (opened.get(downPosition) && openedRight.get(downPosition) && swapRight) {
                swap = false;
            } else if (opened.get(downPosition) && !openedRight.get(downPosition) && !swapRight) {
                swap = false;
            } else {
                int swipeMode = swipeListView.changeSwipeMode(downPosition);
                if (!opened.get(downPosition) && swipeMode == SwipeListView.SWIPE_MODE_RIGHT && !swapRight) {
                    swap = false;
                } else if (!opened.get(downPosition) && swipeMode == SwipeListView.SWIPE_MODE_LEFT
                        && swapRight) {
                    swap = false;
                } else {
                    swap = true;
                }

            }

        } else if (Math.abs(deltaX) > viewWidth / 2) {
            swap = true;
            swapRight = deltaX > 0;
        }

        initPos = true;
        generateAnimate(frontView, swap, swapRight, downPosition);
        if (swipeCurrentAction == SwipeListView.SWIPE_ACTION_CHOICE) {
            swapChoiceState(downPosition);
        }

        velocityTracker.recycle();
        velocityTracker = null;
        downX = 0;

        swiping = false;
        break;
    }

    case MotionEvent.ACTION_MOVE: {
        if (velocityTracker == null || paused || downPosition == ListView.INVALID_POSITION) {
            break;
        }

        velocityTracker.addMovement(motionEvent);
        velocityTracker.computeCurrentVelocity(1000);
        float velocityX = Math.abs(velocityTracker.getXVelocity());
        float velocityY = Math.abs(velocityTracker.getYVelocity());

        float deltaX = motionEvent.getRawX() - downX;
        float deltaMode = Math.abs(deltaX);

        int swipeMode = this.swipeMode;

        if (changeSwipeMode >= 0) {
            swipeMode = changeSwipeMode;
        }

        if (swipeMode == SwipeListView.SWIPE_MODE_NONE) {
            deltaMode = 0;
        } else if (swipeMode != SwipeListView.SWIPE_MODE_BOTH) {
            if (opened.get(downPosition)) {
                if (swipeMode == SwipeListView.SWIPE_MODE_LEFT && deltaX < 0) {
                    deltaMode = 0;
                } else if (swipeMode == SwipeListView.SWIPE_MODE_RIGHT && deltaX > 0) {
                    deltaMode = 0;
                }
            } else {
                if (swipeMode == SwipeListView.SWIPE_MODE_LEFT && deltaX > 0) {
                    deltaMode = 0;
                } else if (swipeMode == SwipeListView.SWIPE_MODE_RIGHT && deltaX < 0) {
                    deltaMode = 0;
                }
            }
        }
        if (deltaMode > slop && swipeCurrentAction == SwipeListView.SWIPE_ACTION_NONE
                && velocityY < velocityX) {
            swiping = true;
            swipingRight = (deltaX > 0);
            if (SwipeListView.DEBUG) {
                Log.d(SwipeListView.TAG, "deltaX: " + deltaX + " - swipingRight: " + swipingRight);
            }
            if (opened.get(downPosition)) {
                swipeListView.onStartClose(downPosition, swipingRight);
                swipeCurrentAction = SwipeListView.SWIPE_ACTION_REVEAL;
            } else {
                if (swipingRight && swipeActionRight == SwipeListView.SWIPE_ACTION_DISMISS) {
                    swipeCurrentAction = SwipeListView.SWIPE_ACTION_DISMISS;
                } else if (!swipingRight && swipeActionLeft == SwipeListView.SWIPE_ACTION_DISMISS) {
                    swipeCurrentAction = SwipeListView.SWIPE_ACTION_DISMISS;
                } else if (swipingRight && swipeActionRight == SwipeListView.SWIPE_ACTION_CHOICE) {
                    swipeCurrentAction = SwipeListView.SWIPE_ACTION_CHOICE;
                } else if (!swipingRight && swipeActionLeft == SwipeListView.SWIPE_ACTION_CHOICE) {
                    swipeCurrentAction = SwipeListView.SWIPE_ACTION_CHOICE;
                } else {
                    swipeCurrentAction = SwipeListView.SWIPE_ACTION_REVEAL;
                }
                swipeListView.onStartOpen(downPosition, swipeCurrentAction, swipingRight);
            }
            swipeListView.requestDisallowInterceptTouchEvent(true);
            MotionEvent cancelEvent = MotionEvent.obtain(motionEvent);
            cancelEvent.setAction(MotionEvent.ACTION_CANCEL | (MotionEventCompat
                    .getActionIndex(motionEvent) << MotionEventCompat.ACTION_POINTER_INDEX_SHIFT));
            swipeListView.onTouchEvent(cancelEvent);
            if (swipeCurrentAction == SwipeListView.SWIPE_ACTION_CHOICE) {
                backView.setVisibility(View.GONE);
            }
        }

        if (swiping && downPosition != ListView.INVALID_POSITION) {
            if (opened.get(downPosition)) {
                deltaX += openedRight.get(downPosition) ? viewWidth - rightOffset : -viewWidth + leftOffset;
            }
            move(deltaX);
        }

        return velocityY < velocityX;
    }
    }
    return false;
}

From source file:cz.metaverse.android.bilingualreader.helper.BookPanelOnTouchListener.java

/**
 * The entry method for any touch-related event.
 * @param view The WebView where the swipe took place
 * @param event The MotionEvent of the swipe
 *///from   w  w w  . j a  v a 2  s. c om
@Override
public boolean onTouch(View view, MotionEvent event) {
    // Provide data to the GestureDetector.
    gestureDetector.onTouchEvent(event);

    /*
     * Handle Double Tap Swipe in real time.
     *  This handling isn't in onDoubleTapEvent() because that method has a limit how many times
     *  it gets called after which it isn't called at all until the user lifts the finger in which
     *  case it gets called one last time. That is not workable for on-the-fly resizing of panels.
     */
    if (isDoubleTapSwipe) {
        float absDiffX = Math.abs(doubleTapOriginX - event.getX());
        float absDiffY = Math.abs(doubleTapOriginY - event.getY());

        // If the swipe was over predefined threshold value high and it was higher than wider,
        // or if the swipe was over predefined threshold value wide and it was wider than higher.
        if (doubleTapSwipeEscapedBounds ||
        // Bounds for PORTRAIT orientation.
                (absDiffY > threshold_swipe_up_or_down_change_panel_size_px && absDiffY > absDiffX
                        && doubleTapSwipe_orientation == Configuration.ORIENTATION_PORTRAIT)
                ||
                // Bounds for LANDSCAPE orientation.
                (absDiffX > threshold_swipe_left_right_change_panel_size_px && absDiffX > absDiffY
                        && doubleTapSwipe_orientation != Configuration.ORIENTATION_PORTRAIT)) {

            if (!doubleTapSwipeEscapedBounds) {
                // This is the first time doubleTapSwipe escaped it's bounds
                // - we're officially in the set-panels-size mode.
                doubleTapSwipeEscapedBounds = true;

                // Find out and save the relevant dimensions of our view/display
                Window window = activity.getWindow();

                if (doubleTapSwipe_orientation == Configuration.ORIENTATION_PORTRAIT) {
                    doubleTapSwipe_contentStartsAtHeight = window.findViewById(Window.ID_ANDROID_CONTENT)
                            .getTop();
                    doubleTapSwipe_viewHeight = window.getDecorView().getHeight();
                } else {
                    doubleTapSwipe_contentStartsAtHeight = window.findViewById(Window.ID_ANDROID_CONTENT)
                            .getLeft();
                    doubleTapSwipe_viewHeight = window.getDecorView().getWidth();
                }
            }

            // Compute the panels weight
            float useCoordinate = (doubleTapSwipe_orientation == Configuration.ORIENTATION_PORTRAIT)
                    ? event.getRawY()
                    : event.getRawX();

            newPanelsWeight = (useCoordinate - doubleTapSwipe_contentStartsAtHeight)
                    / (doubleTapSwipe_viewHeight - doubleTapSwipe_contentStartsAtHeight);

            // If the weight is close to 0.5, let it stick to it.
            if (Math.abs(0.5 - newPanelsWeight) < PANEL_RESIZE_SNAP_WEIGHT_AROUND_HALF) {
                newPanelsWeight = 0.5f;
            }

            // Assure that the weight is between the allowed minimum and maximum.
            newPanelsWeight = Func.minMaxRange(Func.PANEL_WEIGHT_MIN, newPanelsWeight, Func.PANEL_WEIGHT_MAX);

            // Change relative panel size on the fly.
            governor.changePanelsWeight(newPanelsWeight);

            //Log.v(LOG, "[" + panelPosition + "] doubleTapSwipe " + newPanelsWeight);
            //+ " = (" + event.getRawY() + " - " + contentViewTop + ") / " + (height - contentViewTop));
        }
    }

    /*
     * Handle ACTION_UP event for scrolling, because onScroll (almost?) never gets
     * called with the last MotionEvent.ACTION_UP.
     * Don't forget to mirror any changes made here in the onScroll() method as well, to be safe.
     */
    if (MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_UP) {
        Log.d(LOG, "[" + panelPosition + "] OnTouchListener --> onTouch ACTION_UP - scrollY: "
                + webView.getScrollY());

        // Only if it's not DoubleTapSwipe, that is handled separately.
        if (!isDoubleTapSwipe) {
            // Evaluate if the scroll that has just ended constitutes some gesture.
            handleScrollEnd(event);
        }
    }

    // Modify the event so that it is passed on in a state where the X coordinate hasn't changed at all.
    // This prevents the "over scroll glow effect" on pages that have some (hidden) horizontal scroll.
    //  -- Disabled because it causes the wrong scroll position to be loaded after opening a page
    //     sometimes (but not every time), for some unknown reason.
    //event.setLocation(touchOriginX, event.getY());

    view.performClick(); // Android system mandates we pass the baton to the onClick listener now.

    return view.onTouchEvent(event);
}

From source file:org.telegram.ui.Components.ChatActivityEnterView.java

public ChatActivityEnterView(Activity context, SizeNotifierFrameLayout parent, ChatActivity fragment,
        final boolean isChat) {
    super(context);

    dotPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    dotPaint.setColor(Theme.getColor(Theme.key_chat_emojiPanelNewTrending));
    setFocusable(true);//from   w w  w. j a  v  a 2s . com
    setFocusableInTouchMode(true);
    setWillNotDraw(false);

    NotificationCenter.getInstance().addObserver(this, NotificationCenter.recordStarted);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.recordStartError);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.recordStopped);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.recordProgressChanged);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.closeChats);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioDidSent);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.emojiDidLoaded);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioRouteChanged);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioDidReset);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioProgressDidChanged);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.featuredStickersDidLoaded);
    parentActivity = context;
    parentFragment = fragment;
    sizeNotifierLayout = parent;
    sizeNotifierLayout.setDelegate(this);
    SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig",
            Activity.MODE_PRIVATE);
    sendByEnter = preferences.getBoolean("send_by_enter", false);

    textFieldContainer = new LinearLayout(context);
    textFieldContainer.setOrientation(LinearLayout.HORIZONTAL);
    addView(textFieldContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT,
            Gravity.LEFT | Gravity.TOP, 0, 2, 0, 0));

    FrameLayout frameLayout = new FrameLayout(context);
    textFieldContainer.addView(frameLayout, LayoutHelper.createLinear(0, LayoutHelper.WRAP_CONTENT, 1.0f));

    emojiButton = new ImageView(context) {
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            if (attachLayout != null && (emojiView == null || emojiView.getVisibility() != VISIBLE)
                    && !StickersQuery.getUnreadStickerSets().isEmpty() && dotPaint != null) {
                int x = canvas.getWidth() / 2 + AndroidUtilities.dp(4 + 5);
                int y = canvas.getHeight() / 2 - AndroidUtilities.dp(13 - 5);
                canvas.drawCircle(x, y, AndroidUtilities.dp(5), dotPaint);
            }
        }
    };
    emojiButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelIcons),
            PorterDuff.Mode.MULTIPLY));
    emojiButton.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
    emojiButton.setPadding(0, AndroidUtilities.dp(1), 0, 0);
    //        if (Build.VERSION.SDK_INT >= 21) {
    //            emojiButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.INPUT_FIELD_SELECTOR_COLOR));
    //        }
    setEmojiButtonImage();
    frameLayout.addView(emojiButton,
            LayoutHelper.createFrame(48, 48, Gravity.BOTTOM | Gravity.LEFT, 3, 0, 0, 0));
    emojiButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            if (!isPopupShowing() || currentPopupContentType != 0) {
                showPopup(1, 0);
                emojiView.onOpen(messageEditText.length() > 0
                        && !messageEditText.getText().toString().startsWith("@gif"));
            } else {
                openKeyboardInternal();
                removeGifFromInputField();
            }
        }
    });

    messageEditText = new EditTextCaption(context) {
        @Override
        public InputConnection onCreateInputConnection(EditorInfo editorInfo) {
            final InputConnection ic = super.onCreateInputConnection(editorInfo);
            EditorInfoCompat.setContentMimeTypes(editorInfo,
                    new String[] { "image/gif", "image/*", "image/jpg", "image/png" });

            final InputConnectionCompat.OnCommitContentListener callback = new InputConnectionCompat.OnCommitContentListener() {
                @Override
                public boolean onCommitContent(InputContentInfoCompat inputContentInfo, int flags,
                        Bundle opts) {
                    if (BuildCompat.isAtLeastNMR1()
                            && (flags & InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION) != 0) {
                        try {
                            inputContentInfo.requestPermission();
                        } catch (Exception e) {
                            return false;
                        }
                    }
                    ClipDescription description = inputContentInfo.getDescription();
                    if (description.hasMimeType("image/gif")) {
                        SendMessagesHelper.prepareSendingDocument(null, null, inputContentInfo.getContentUri(),
                                "image/gif", dialog_id, replyingMessageObject, inputContentInfo);
                    } else {
                        SendMessagesHelper.prepareSendingPhoto(null, inputContentInfo.getContentUri(),
                                dialog_id, replyingMessageObject, null, null, inputContentInfo);
                    }
                    if (delegate != null) {
                        delegate.onMessageSend(null);
                    }
                    return true;
                }
            };
            return InputConnectionCompat.createWrapper(ic, editorInfo, callback);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (isPopupShowing() && event.getAction() == MotionEvent.ACTION_DOWN) {
                showPopup(AndroidUtilities.usingHardwareInput ? 0 : 2, 0);
                openKeyboardInternal();
            }
            try {
                return super.onTouchEvent(event);
            } catch (Exception e) {
                FileLog.e(e);
            }
            return false;
        }
    };
    updateFieldHint();
    messageEditText.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
    messageEditText.setInputType(messageEditText.getInputType() | EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES
            | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE);
    messageEditText.setSingleLine(false);
    messageEditText.setMaxLines(4);
    messageEditText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
    messageEditText.setGravity(Gravity.BOTTOM);
    messageEditText.setPadding(0, AndroidUtilities.dp(11), 0, AndroidUtilities.dp(12));
    messageEditText.setBackgroundDrawable(null);
    messageEditText.setTextColor(Theme.getColor(Theme.key_chat_messagePanelText));
    messageEditText.setHintColor(Theme.getColor(Theme.key_chat_messagePanelHint));
    messageEditText.setHintTextColor(Theme.getColor(Theme.key_chat_messagePanelHint));
    frameLayout.addView(messageEditText, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM, 52, 0, isChat ? 50 : 2, 0));
    messageEditText.setOnKeyListener(new OnKeyListener() {

        boolean ctrlPressed = false;

        @Override
        public boolean onKey(View view, int i, KeyEvent keyEvent) {
            if (i == KeyEvent.KEYCODE_BACK && !keyboardVisible && isPopupShowing()) {
                if (keyEvent.getAction() == 1) {
                    if (currentPopupContentType == 1 && botButtonsMessageObject != null) {
                        SharedPreferences preferences = ApplicationLoader.applicationContext
                                .getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
                        preferences.edit().putInt("hidekeyboard_" + dialog_id, botButtonsMessageObject.getId())
                                .commit();
                    }
                    showPopup(0, 0);
                    removeGifFromInputField();
                }
                return true;
            } else if (i == KeyEvent.KEYCODE_ENTER && (ctrlPressed || sendByEnter)
                    && keyEvent.getAction() == KeyEvent.ACTION_DOWN && editingMessageObject == null) {
                sendMessage();
                return true;
            } else if (i == KeyEvent.KEYCODE_CTRL_LEFT || i == KeyEvent.KEYCODE_CTRL_RIGHT) {
                ctrlPressed = keyEvent.getAction() == KeyEvent.ACTION_DOWN;
                return true;
            }
            return false;
        }
    });
    messageEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {

        boolean ctrlPressed = false;

        @Override
        public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
            if (i == EditorInfo.IME_ACTION_SEND) {
                sendMessage();
                return true;
            } else if (keyEvent != null && i == EditorInfo.IME_NULL) {
                if ((ctrlPressed || sendByEnter) && keyEvent.getAction() == KeyEvent.ACTION_DOWN
                        && editingMessageObject == null) {
                    sendMessage();
                    return true;
                } else if (i == KeyEvent.KEYCODE_CTRL_LEFT || i == KeyEvent.KEYCODE_CTRL_RIGHT) {
                    ctrlPressed = keyEvent.getAction() == KeyEvent.ACTION_DOWN;
                    return true;
                }
            }
            return false;
        }
    });
    messageEditText.addTextChangedListener(new TextWatcher() {
        boolean processChange = false;

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
            if (innerTextChange == 1) {
                return;
            }
            checkSendButton(true);
            CharSequence message = AndroidUtilities.getTrimmedString(charSequence.toString());
            if (delegate != null) {
                if (!ignoreTextChange) {
                    if (count > 2 || charSequence == null || charSequence.length() == 0) {
                        messageWebPageSearch = true;
                    }
                    delegate.onTextChanged(charSequence, before > count + 1 || (count - before) > 2);
                }
            }
            if (innerTextChange != 2 && before != count && (count - before) > 1) {
                processChange = true;
            }
            if (editingMessageObject == null && !canWriteToChannel && message.length() != 0
                    && lastTypingTimeSend < System.currentTimeMillis() - 5000 && !ignoreTextChange) {
                int currentTime = ConnectionsManager.getInstance().getCurrentTime();
                TLRPC.User currentUser = null;
                if ((int) dialog_id > 0) {
                    currentUser = MessagesController.getInstance().getUser((int) dialog_id);
                }
                if (currentUser != null && (currentUser.id == UserConfig.getClientUserId()
                        || currentUser.status != null && currentUser.status.expires < currentTime
                                && !MessagesController.getInstance().onlinePrivacy
                                        .containsKey(currentUser.id))) {
                    return;
                }
                lastTypingTimeSend = System.currentTimeMillis();
                if (delegate != null) {
                    delegate.needSendTyping();
                }
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (innerTextChange != 0) {
                return;
            }
            if (sendByEnter && editable.length() > 0 && editable.charAt(editable.length() - 1) == '\n'
                    && editingMessageObject == null) {
                sendMessage();
            }
            if (processChange) {
                ImageSpan[] spans = editable.getSpans(0, editable.length(), ImageSpan.class);
                for (int i = 0; i < spans.length; i++) {
                    editable.removeSpan(spans[i]);
                }
                Emoji.replaceEmoji(editable, messageEditText.getPaint().getFontMetricsInt(),
                        AndroidUtilities.dp(20), false);
                processChange = false;
            }
        }
    });

    if (isChat) {
        attachLayout = new LinearLayout(context);
        attachLayout.setOrientation(LinearLayout.HORIZONTAL);
        attachLayout.setEnabled(false);
        attachLayout.setPivotX(AndroidUtilities.dp(48));
        frameLayout.addView(attachLayout,
                LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 48, Gravity.BOTTOM | Gravity.RIGHT));

        botButton = new ImageView(context);
        botButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelIcons),
                PorterDuff.Mode.MULTIPLY));
        botButton.setImageResource(R.drawable.bot_keyboard2);
        botButton.setScaleType(ImageView.ScaleType.CENTER);
        botButton.setVisibility(GONE);
        //            if (Build.VERSION.SDK_INT >= 21) {
        //                botButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.INPUT_FIELD_SELECTOR_COLOR));
        //            }
        attachLayout.addView(botButton, LayoutHelper.createLinear(48, 48));
        botButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (botReplyMarkup != null) {
                    if (!isPopupShowing() || currentPopupContentType != 1) {
                        showPopup(1, 1);
                        SharedPreferences preferences = ApplicationLoader.applicationContext
                                .getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
                        preferences.edit().remove("hidekeyboard_" + dialog_id).commit();
                    } else {
                        if (currentPopupContentType == 1 && botButtonsMessageObject != null) {
                            SharedPreferences preferences = ApplicationLoader.applicationContext
                                    .getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
                            preferences.edit()
                                    .putInt("hidekeyboard_" + dialog_id, botButtonsMessageObject.getId())
                                    .commit();
                        }
                        openKeyboardInternal();
                    }
                } else if (hasBotCommands) {
                    setFieldText("/");
                    messageEditText.requestFocus();
                    openKeyboard();
                }
            }
        });

        notifyButton = new ImageView(context);
        notifyButton.setImageResource(silent ? R.drawable.notify_members_off : R.drawable.notify_members_on);
        notifyButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelIcons),
                PorterDuff.Mode.MULTIPLY));
        notifyButton.setScaleType(ImageView.ScaleType.CENTER);
        notifyButton.setVisibility(canWriteToChannel ? VISIBLE : GONE);
        //            if (Build.VERSION.SDK_INT >= 21) {
        //                notifyButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.INPUT_FIELD_SELECTOR_COLOR));
        //            }
        attachLayout.addView(notifyButton, LayoutHelper.createLinear(48, 48));
        notifyButton.setOnClickListener(new OnClickListener() {

            private Toast visibleToast;

            @Override
            public void onClick(View v) {
                silent = !silent;
                notifyButton.setImageResource(
                        silent ? R.drawable.notify_members_off : R.drawable.notify_members_on);
                ApplicationLoader.applicationContext
                        .getSharedPreferences("Notifications", Activity.MODE_PRIVATE).edit()
                        .putBoolean("silent_" + dialog_id, silent).commit();
                NotificationsController.updateServerNotificationsSettings(dialog_id);
                try {
                    if (visibleToast != null) {
                        visibleToast.cancel();
                    }
                } catch (Exception e) {
                    FileLog.e(e);
                }
                if (silent) {
                    visibleToast = Toast.makeText(parentActivity, LocaleController
                            .getString("ChannelNotifyMembersInfoOff", R.string.ChannelNotifyMembersInfoOff),
                            Toast.LENGTH_SHORT);
                } else {
                    visibleToast = Toast.makeText(parentActivity, LocaleController
                            .getString("ChannelNotifyMembersInfoOn", R.string.ChannelNotifyMembersInfoOn),
                            Toast.LENGTH_SHORT);
                }
                visibleToast.show();
                updateFieldHint();
            }
        });

        attachButton = new ImageView(context);
        attachButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelIcons),
                PorterDuff.Mode.MULTIPLY));
        attachButton.setImageResource(R.drawable.ic_ab_attach);
        attachButton.setScaleType(ImageView.ScaleType.CENTER);
        //            if (Build.VERSION.SDK_INT >= 21) {
        //                attachButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.INPUT_FIELD_SELECTOR_COLOR));
        //            }
        attachLayout.addView(attachButton, LayoutHelper.createLinear(48, 48));
        attachButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                delegate.didPressedAttachButton();
            }
        });
    }

    recordedAudioPanel = new FrameLayout(context);
    recordedAudioPanel.setVisibility(audioToSend == null ? GONE : VISIBLE);
    recordedAudioPanel.setBackgroundColor(Theme.getColor(Theme.key_chat_messagePanelBackground));
    recordedAudioPanel.setFocusable(true);
    recordedAudioPanel.setFocusableInTouchMode(true);
    recordedAudioPanel.setClickable(true);
    frameLayout.addView(recordedAudioPanel,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.BOTTOM));

    recordDeleteImageView = new ImageView(context);
    recordDeleteImageView.setScaleType(ImageView.ScaleType.CENTER);
    recordDeleteImageView.setImageResource(R.drawable.ic_ab_delete);
    recordDeleteImageView.setColorFilter(new PorterDuffColorFilter(
            Theme.getColor(Theme.key_chat_messagePanelVoiceDelete), PorterDuff.Mode.MULTIPLY));
    recordedAudioPanel.addView(recordDeleteImageView, LayoutHelper.createFrame(48, 48));
    recordDeleteImageView.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            MessageObject playing = MediaController.getInstance().getPlayingMessageObject();
            if (playing != null && playing == audioToSendMessageObject) {
                MediaController.getInstance().cleanupPlayer(true, true);
            }
            if (audioToSendPath != null) {
                new File(audioToSendPath).delete();
            }
            hideRecordedAudioPanel();
            checkSendButton(true);
        }
    });

    recordedAudioBackground = new View(context);
    recordedAudioBackground.setBackgroundDrawable(Theme.createRoundRectDrawable(AndroidUtilities.dp(16),
            Theme.getColor(Theme.key_chat_recordedVoiceBackground)));
    recordedAudioPanel.addView(recordedAudioBackground, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 32,
            Gravity.CENTER_VERTICAL | Gravity.LEFT, 48, 0, 0, 0));

    recordedAudioSeekBar = new SeekBarWaveformView(context);
    recordedAudioPanel.addView(recordedAudioSeekBar, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 32,
            Gravity.CENTER_VERTICAL | Gravity.LEFT, 48 + 44, 0, 52, 0));

    playDrawable = Theme.createSimpleSelectorDrawable(context, R.drawable.s_play,
            Theme.getColor(Theme.key_chat_recordedVoicePlayPause),
            Theme.getColor(Theme.key_chat_recordedVoicePlayPausePressed));
    pauseDrawable = Theme.createSimpleSelectorDrawable(context, R.drawable.s_pause,
            Theme.getColor(Theme.key_chat_recordedVoicePlayPause),
            Theme.getColor(Theme.key_chat_recordedVoicePlayPausePressed));

    recordedAudioPlayButton = new ImageView(context);
    recordedAudioPlayButton.setImageDrawable(playDrawable);
    recordedAudioPlayButton.setScaleType(ImageView.ScaleType.CENTER);
    recordedAudioPanel.addView(recordedAudioPlayButton,
            LayoutHelper.createFrame(48, 48, Gravity.LEFT | Gravity.BOTTOM, 48, 0, 0, 0));
    recordedAudioPlayButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (audioToSend == null) {
                return;
            }
            if (MediaController.getInstance().isPlayingAudio(audioToSendMessageObject)
                    && !MediaController.getInstance().isAudioPaused()) {
                MediaController.getInstance().pauseAudio(audioToSendMessageObject);
                recordedAudioPlayButton.setImageDrawable(playDrawable);
            } else {
                recordedAudioPlayButton.setImageDrawable(pauseDrawable);
                MediaController.getInstance().playAudio(audioToSendMessageObject);
            }
        }
    });

    recordedAudioTimeTextView = new TextView(context);
    recordedAudioTimeTextView.setTextColor(Theme.getColor(Theme.key_chat_messagePanelVoiceDuration));
    recordedAudioTimeTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
    recordedAudioPanel.addView(recordedAudioTimeTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.RIGHT | Gravity.CENTER_VERTICAL, 0, 0, 13, 0));

    recordPanel = new FrameLayout(context);
    recordPanel.setVisibility(GONE);
    recordPanel.setBackgroundColor(Theme.getColor(Theme.key_chat_messagePanelBackground));
    frameLayout.addView(recordPanel, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.BOTTOM));

    slideText = new LinearLayout(context);
    slideText.setOrientation(LinearLayout.HORIZONTAL);
    recordPanel.addView(slideText, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 30, 0, 0, 0));

    recordCancelImage = new ImageView(context);
    recordCancelImage.setImageResource(R.drawable.slidearrow);
    recordCancelImage.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_recordVoiceCancel),
            PorterDuff.Mode.MULTIPLY));
    slideText.addView(recordCancelImage, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, 0, 1, 0, 0));

    recordCancelText = new TextView(context);
    recordCancelText.setText(LocaleController.getString("SlideToCancel", R.string.SlideToCancel));
    recordCancelText.setTextColor(Theme.getColor(Theme.key_chat_recordVoiceCancel));
    recordCancelText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
    slideText.addView(recordCancelText, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, 6, 0, 0, 0));

    recordTimeContainer = new LinearLayout(context);
    recordTimeContainer.setOrientation(LinearLayout.HORIZONTAL);
    recordTimeContainer.setPadding(AndroidUtilities.dp(13), 0, 0, 0);
    recordTimeContainer.setBackgroundColor(Theme.getColor(Theme.key_chat_messagePanelBackground));
    recordPanel.addView(recordTimeContainer, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL));

    recordDot = new RecordDot(context);
    recordTimeContainer.addView(recordDot,
            LayoutHelper.createLinear(11, 11, Gravity.CENTER_VERTICAL, 0, 1, 0, 0));

    recordTimeText = new TextView(context);
    recordTimeText.setText("00:00");
    recordTimeText.setTextColor(Theme.getColor(Theme.key_chat_recordTime));
    recordTimeText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
    recordTimeContainer.addView(recordTimeText, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, 6, 0, 0, 0));

    sendButtonContainer = new FrameLayout(context);
    textFieldContainer.addView(sendButtonContainer, LayoutHelper.createLinear(48, 48, Gravity.BOTTOM));

    audioVideoButtonContainer = new FrameLayout(context);
    audioVideoButtonContainer.setBackgroundColor(Theme.getColor(Theme.key_chat_messagePanelBackground));
    audioVideoButtonContainer.setSoundEffectsEnabled(false);
    sendButtonContainer.addView(audioVideoButtonContainer, LayoutHelper.createFrame(48, 48));
    audioVideoButtonContainer.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                if (hasRecordVideo) {
                    recordAudioVideoRunnableStarted = true;
                    AndroidUtilities.runOnUIThread(recordAudioVideoRunnable, 150);
                } else {
                    recordAudioVideoRunnable.run();
                }
            } else if (motionEvent.getAction() == MotionEvent.ACTION_UP
                    || motionEvent.getAction() == MotionEvent.ACTION_CANCEL) {
                if (recordAudioVideoRunnableStarted) {
                    AndroidUtilities.cancelRunOnUIThread(recordAudioVideoRunnable);
                    setRecordVideoButtonVisible(videoSendButton.getTag() == null, true);
                } else {
                    startedDraggingX = -1;
                    if (hasRecordVideo && videoSendButton.getTag() != null) {
                        delegate.needStartRecordVideo(1);
                    } else {
                        MediaController.getInstance().stopRecording(1);
                    }
                    recordingAudioVideo = false;
                    updateRecordIntefrace();
                }
            } else if (motionEvent.getAction() == MotionEvent.ACTION_MOVE && recordingAudioVideo) {
                float x = motionEvent.getX();
                if (x < -distCanMove) {
                    if (hasRecordVideo && videoSendButton.getTag() != null) {
                        delegate.needStartRecordVideo(2);
                    } else {
                        MediaController.getInstance().stopRecording(0);
                    }
                    recordingAudioVideo = false;
                    updateRecordIntefrace();
                }

                x = x + audioVideoButtonContainer.getX();
                FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) slideText.getLayoutParams();
                if (startedDraggingX != -1) {
                    float dist = (x - startedDraggingX);
                    recordCircle.setTranslationX(dist);
                    params.leftMargin = AndroidUtilities.dp(30) + (int) dist;
                    slideText.setLayoutParams(params);
                    float alpha = 1.0f + dist / distCanMove;
                    if (alpha > 1) {
                        alpha = 1;
                    } else if (alpha < 0) {
                        alpha = 0;
                    }
                    slideText.setAlpha(alpha);
                }
                if (x <= slideText.getX() + slideText.getWidth() + AndroidUtilities.dp(30)) {
                    if (startedDraggingX == -1) {
                        startedDraggingX = x;
                        distCanMove = (recordPanel.getMeasuredWidth() - slideText.getMeasuredWidth()
                                - AndroidUtilities.dp(48)) / 2.0f;
                        if (distCanMove <= 0) {
                            distCanMove = AndroidUtilities.dp(80);
                        } else if (distCanMove > AndroidUtilities.dp(80)) {
                            distCanMove = AndroidUtilities.dp(80);
                        }
                    }
                }
                if (params.leftMargin > AndroidUtilities.dp(30)) {
                    params.leftMargin = AndroidUtilities.dp(30);
                    recordCircle.setTranslationX(0);
                    slideText.setLayoutParams(params);
                    slideText.setAlpha(1);
                    startedDraggingX = -1;
                }
            }
            view.onTouchEvent(motionEvent);
            return true;
        }
    });

    audioSendButton = new ImageView(context);
    audioSendButton.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
    audioSendButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelIcons),
            PorterDuff.Mode.MULTIPLY));
    audioSendButton.setImageResource(R.drawable.mic);
    audioSendButton.setPadding(0, 0, AndroidUtilities.dp(4), 0);
    audioVideoButtonContainer.addView(audioSendButton, LayoutHelper.createFrame(48, 48));

    if (hasRecordVideo) {
        videoSendButton = new ImageView(context);
        videoSendButton.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        videoSendButton.setColorFilter(new PorterDuffColorFilter(
                Theme.getColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY));
        videoSendButton.setImageResource(R.drawable.ic_msg_panel_video);
        videoSendButton.setPadding(0, 0, AndroidUtilities.dp(4), 0);
        audioVideoButtonContainer.addView(videoSendButton, LayoutHelper.createFrame(48, 48));
    }

    recordCircle = new RecordCircle(context);
    recordCircle.setVisibility(GONE);
    sizeNotifierLayout.addView(recordCircle,
            LayoutHelper.createFrame(124, 124, Gravity.BOTTOM | Gravity.RIGHT, 0, 0, -36, -38));

    cancelBotButton = new ImageView(context);
    cancelBotButton.setVisibility(INVISIBLE);
    cancelBotButton.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
    cancelBotButton.setImageDrawable(progressDrawable = new CloseProgressDrawable2());
    progressDrawable.setColorFilter(new PorterDuffColorFilter(
            Theme.getColor(Theme.key_chat_messagePanelCancelInlineBot), PorterDuff.Mode.MULTIPLY));
    cancelBotButton.setSoundEffectsEnabled(false);
    cancelBotButton.setScaleX(0.1f);
    cancelBotButton.setScaleY(0.1f);
    cancelBotButton.setAlpha(0.0f);
    sendButtonContainer.addView(cancelBotButton, LayoutHelper.createFrame(48, 48));
    cancelBotButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            String text = messageEditText.getText().toString();
            int idx = text.indexOf(' ');
            if (idx == -1 || idx == text.length() - 1) {
                setFieldText("");
            } else {
                setFieldText(text.substring(0, idx + 1));
            }
        }
    });

    sendButton = new ImageView(context);
    sendButton.setVisibility(INVISIBLE);
    sendButton.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
    sendButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelSend),
            PorterDuff.Mode.MULTIPLY));
    sendButton.setImageResource(R.drawable.ic_send);
    sendButton.setSoundEffectsEnabled(false);
    sendButton.setScaleX(0.1f);
    sendButton.setScaleY(0.1f);
    sendButton.setAlpha(0.0f);
    sendButtonContainer.addView(sendButton, LayoutHelper.createFrame(48, 48));
    sendButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            sendMessage();
        }
    });

    doneButtonContainer = new FrameLayout(context);
    doneButtonContainer.setVisibility(GONE);
    textFieldContainer.addView(doneButtonContainer, LayoutHelper.createLinear(48, 48, Gravity.BOTTOM));
    //        if (Build.VERSION.SDK_INT >= 21) {
    //            doneButtonContainer.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.INPUT_FIELD_SELECTOR_COLOR));
    //        }
    doneButtonContainer.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            doneEditingMessage();
        }
    });

    doneButtonImage = new ImageView(context);
    doneButtonImage.setScaleType(ImageView.ScaleType.CENTER);
    doneButtonImage.setImageResource(R.drawable.edit_done);
    doneButtonImage.setColorFilter(
            new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_editDoneIcon), PorterDuff.Mode.MULTIPLY));
    doneButtonContainer.addView(doneButtonImage, LayoutHelper.createFrame(48, 48));

    doneButtonProgress = new ContextProgressView(context, 0);
    doneButtonProgress.setVisibility(View.INVISIBLE);
    doneButtonContainer.addView(doneButtonProgress,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));

    SharedPreferences sharedPreferences = ApplicationLoader.applicationContext.getSharedPreferences("emoji",
            Context.MODE_PRIVATE);
    keyboardHeight = sharedPreferences.getInt("kbd_height", AndroidUtilities.dp(200));
    keyboardHeightLand = sharedPreferences.getInt("kbd_height_land3", AndroidUtilities.dp(200));

    setRecordVideoButtonVisible(false, false);
    checkSendButton(false);
}