Example usage for android.view MotionEvent ACTION_POINTER_UP

List of usage examples for android.view MotionEvent ACTION_POINTER_UP

Introduction

In this page you can find the example usage for android.view MotionEvent ACTION_POINTER_UP.

Prototype

int ACTION_POINTER_UP

To view the source code for android.view MotionEvent ACTION_POINTER_UP.

Click Source Link

Document

Constant for #getActionMasked : A non-primary pointer has gone up.

Usage

From source file:com.cbs.corona.lib.ExtendableListView.java

/**
 * {@inheritDoc}//from  ww w  .  j  ava2 s.c  o m
 */
@Override
public boolean onTouchEvent(MotionEvent event) {
    // we're not passing this down as
    // all the touch handling is right here
    // super.onTouchEvent(event);

    if (!isEnabled()) {
        // A disabled view that is clickable still consumes the touch
        // events, it just doesn't respond to them.
        return isClickable() || isLongClickable();
    }

    initVelocityTrackerIfNotExists();
    mVelocityTracker.addMovement(event);

    if (!hasChildren())
        return false;

    boolean handled;
    final int action = event.getAction() & MotionEventCompat.ACTION_MASK;
    switch (action) {
    case MotionEvent.ACTION_DOWN:
        handled = onTouchDown(event);
        break;

    case MotionEvent.ACTION_MOVE:
        handled = onTouchMove(event);
        break;

    case MotionEvent.ACTION_CANCEL:
        handled = onTouchCancel(event);
        break;

    case MotionEvent.ACTION_POINTER_UP:
        handled = onTouchPointerUp(event);
        break;

    case MotionEvent.ACTION_UP:
    default:
        handled = onTouchUp(event);
        break;
    }

    notifyTouchMode();

    return handled;
}

From source file:com.lovebridge.library.view.staggeredGridView.ExtendableListView.java

/**
 * {@inheritDoc}//w ww.  java  2s.c o  m
 */
@Override
public boolean onTouchEvent(MotionEvent event) {
    // we're not passing this down as
    // all the touch handling is right here
    // super.onTouchEvent(event);
    if (!isEnabled()) {
        // A disabled view that is clickable still consumes the touch
        // events, it just doesn't respond to them.
        return isClickable() || isLongClickable();
    }
    initVelocityTrackerIfNotExists();
    mVelocityTracker.addMovement(event);
    if (!hasChildren())
        return false;
    boolean handled;
    final int action = event.getAction() & MotionEventCompat.ACTION_MASK;
    switch (action) {
    case MotionEvent.ACTION_DOWN:
        handled = onTouchDown(event);
        break;
    case MotionEvent.ACTION_MOVE:
        handled = onTouchMove(event);
        break;
    case MotionEvent.ACTION_CANCEL:
        handled = onTouchCancel(event);
        break;
    case MotionEvent.ACTION_POINTER_UP:
        handled = onTouchPointerUp(event);
        break;
    case MotionEvent.ACTION_UP:
    default:
        handled = onTouchUp(event);
        break;
    }
    notifyTouchMode();
    return handled;
}

From source file:com.dirkgassen.wator.ui.view.RangeSlider.java

/**
 * Handle touch events: drag the thumb to new values. This method also detects clicks.
 *
 * @param event the touch event/*w w w .  ja  va2  s  .c  om*/
 * @return {@code true} if the event was handled; {@code false} otherwise
 */
@Override
public boolean onTouchEvent(@NonNull MotionEvent event) {
    if (Log.isLoggable("Wa-Tor", Log.DEBUG)) {
        Log.d("Wa-Tor", "Got touch event: " + event);
    }
    int paddingLeft = getPaddingLeft();
    int paddingRight = getPaddingRight();
    switch (event.getAction() & MotionEvent.ACTION_MASK) {
    case MotionEvent.ACTION_DOWN:
        touchEventStartTime = System.currentTimeMillis();
        valueBeforeDragging = value;
        activePointerId = event.getPointerId(0);
        float valuePos = positionFromValue(paddingLeft, paddingRight);
        float x = event.getX();
        if (x < valuePos - thumbSize / 2 || x > valuePos + thumbSize / 2) {
            int newValue = valueFromPosition(x, paddingLeft, paddingRight);
            if (Log.isLoggable("Wa-Tor", Log.DEBUG)) {
                Log.d("Wa-Tor", "Starting to drag thumb OUTSIDE of thumb");
            }
            if (newValue != value) {
                touchEventStartTime = 0L; // Not a click
                updateValue(newValue, true /* from user */);
            }
            touchOffset = 0f;
        } else {
            touchOffset = x - valuePos;
            if (Log.isLoggable("Wa-Tor", Log.DEBUG)) {
                Log.d("Wa-Tor", "Starting to drag thumb INSIDE of thumb; offset = " + touchOffset);
            }
        }
        isDragging = true;
        return true;
    case MotionEvent.ACTION_MOVE:
        if (activePointerId != -1) {
            final int pointerIndex = event.findPointerIndex(activePointerId);
            float currentPos = event.getX(pointerIndex) - touchOffset;
            int newValue = valueFromPosition(currentPos, paddingLeft, paddingRight);
            if (newValue != value) {
                if (Log.isLoggable("Wa-Tor", Log.DEBUG)) {
                    Log.d("Wa-Tor", "Got new value " + newValue + " (old = " + value + ")");
                }
                touchEventStartTime = 0L; // Not a click
                updateValue(newValue, true /* from user */);
            }
        }
        return true;
    case MotionEvent.ACTION_UP:
        if (touchEventStartTime > 0L && System.currentTimeMillis() - touchEventStartTime < MAX_CLICK_DURATION) {
            performClick();
        }
        isDragging = false;
        break;
    case MotionEvent.ACTION_CANCEL:
        isDragging = false;
        updateValue(valueBeforeDragging, true /* from user */);
        break;
    case MotionEvent.ACTION_POINTER_UP:
        isDragging = false;
        break;
    }

    return super.onTouchEvent(event);
}

From source file:caesar.feng.framework.widget.StaggeredGrid.ExtendableListView.java

/**
 * {@inheritDoc}/*from   w  w  w .  j a v  a 2s.  c om*/
 */
@Override
public boolean onTouchEvent(MotionEvent event) {
    // we're not passing this down as
    // all the touch handling is right here
    // super.onTouchEvent(event);

    if (!isEnabled()) {
        // A disabled view that is clickable still consumes the touch
        // events, it just doesn't respond to them.
        return isClickable() || isLongClickable();
    }

    initVelocityTrackerIfNotExists();
    mVelocityTracker.addMovement(event);

    if (!hasChildren())
        return false;

    boolean handled;
    final int action = event.getAction() & MotionEventCompat.ACTION_MASK;
    switch (action) {
    case MotionEvent.ACTION_DOWN:
        handled = onTouchDown(event);
        break;

    case MotionEvent.ACTION_MOVE:
        handled = onTouchMove(event);
        break;

    case MotionEvent.ACTION_CANCEL:
        handled = onTouchCancel(event);
        break;

    case MotionEvent.ACTION_POINTER_UP:
        handled = onTouchPointerUp(event);
        break;

    case MotionEvent.ACTION_UP:
        handled = onTouchUp(event);
        break;

    default:
        handled = false;
        break;
    }

    notifyTouchMode();

    return handled;
}

From source file:com.goftagram.telegram.ui.Components.EmojiView.java

public EmojiView(boolean needStickers, Context context) {
    super(context);

    showStickers = needStickers;/*from  www. j  av a2 s . c  om*/

    for (int i = 0; i < EmojiData.dataColored.length + 1; i++) {
        GridView gridView = new GridView(context);
        if (AndroidUtilities.isTablet()) {
            gridView.setColumnWidth(AndroidUtilities.dp(60));
        } else {
            gridView.setColumnWidth(AndroidUtilities.dp(45));
        }
        gridView.setNumColumns(-1);
        views.add(gridView);

        EmojiGridAdapter emojiGridAdapter = new EmojiGridAdapter(i - 1);
        gridView.setAdapter(emojiGridAdapter);
        AndroidUtilities.setListViewEdgeEffectColor(gridView, 0xfff5f6f7);
        adapters.add(emojiGridAdapter);
    }

    if (showStickers) {
        StickersQuery.checkStickers();
        stickersGridView = new GridView(context) {
            @Override
            public boolean onInterceptTouchEvent(MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    int x = (int) event.getX();
                    int y = (int) event.getY();
                    int count = stickersGridView.getChildCount();
                    for (int a = 0; a < count; a++) {
                        View view = stickersGridView.getChildAt(a);
                        int top = view.getTop();
                        int bottom = view.getBottom();
                        int left = view.getLeft();
                        int right = view.getRight();
                        if (top > y || bottom < y || left > x || right < x) {
                            continue;
                        }
                        if (!(view instanceof StickerEmojiCell) || !((StickerEmojiCell) view).showingBitmap()) {
                            return super.onInterceptTouchEvent(event);
                        }
                        startX = x;
                        startY = y;
                        currentStickerPreviewCell = (StickerEmojiCell) view;
                        openStickerPreviewRunnable = new Runnable() {
                            @Override
                            public void run() {
                                if (openStickerPreviewRunnable == null) {
                                    return;
                                }
                                stickersGridView.setOnItemClickListener(null);
                                stickersGridView.requestDisallowInterceptTouchEvent(true);
                                openStickerPreviewRunnable = null;
                                StickerPreviewViewer.getInstance().setParentActivity((Activity) getContext());
                                StickerPreviewViewer.getInstance()
                                        .setKeyboardHeight(EmojiView.this.getMeasuredHeight());
                                StickerPreviewViewer.getInstance().open(currentStickerPreviewCell.getSticker());
                                currentStickerPreviewCell.setScaled(true);
                            }
                        };
                        AndroidUtilities.runOnUIThread(openStickerPreviewRunnable, 200);
                        return true;
                    }
                }
                return false;
            }
        };
        stickersGridView.setSelector(R.drawable.transparent);
        stickersGridView.setColumnWidth(AndroidUtilities.dp(72));
        stickersGridView.setNumColumns(-1);
        stickersGridView.setPadding(0, AndroidUtilities.dp(4), 0, 0);
        stickersGridView.setClipToPadding(false);
        views.add(stickersGridView);
        stickersGridAdapter = new StickersGridAdapter(context);
        stickersGridView.setAdapter(stickersGridAdapter);
        stickersGridView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (openStickerPreviewRunnable != null || StickerPreviewViewer.getInstance().isVisible()) {
                    if (event.getAction() == MotionEvent.ACTION_UP
                            || event.getAction() == MotionEvent.ACTION_CANCEL
                            || event.getAction() == MotionEvent.ACTION_POINTER_UP) {
                        AndroidUtilities.runOnUIThread(new Runnable() {
                            @Override
                            public void run() {
                                stickersGridView.setOnItemClickListener(stickersOnItemClickListener);
                            }
                        }, 150);
                        if (openStickerPreviewRunnable != null) {
                            AndroidUtilities.cancelRunOnUIThread(openStickerPreviewRunnable);
                            openStickerPreviewRunnable = null;
                        } else if (StickerPreviewViewer.getInstance().isVisible()) {
                            StickerPreviewViewer.getInstance().close();
                            if (currentStickerPreviewCell != null) {
                                currentStickerPreviewCell.setScaled(false);
                                currentStickerPreviewCell = null;
                            }
                        }
                    } else if (event.getAction() != MotionEvent.ACTION_DOWN) {
                        if (StickerPreviewViewer.getInstance().isVisible()) {
                            if (event.getAction() == MotionEvent.ACTION_MOVE) {
                                int x = (int) event.getX();
                                int y = (int) event.getY();
                                int count = stickersGridView.getChildCount();
                                for (int a = 0; a < count; a++) {
                                    View view = stickersGridView.getChildAt(a);
                                    int top = view.getTop();
                                    int bottom = view.getBottom();
                                    int left = view.getLeft();
                                    int right = view.getRight();
                                    if (top > y || bottom < y || left > x || right < x) {
                                        continue;
                                    }
                                    if (!(view instanceof StickerEmojiCell)
                                            || view == currentStickerPreviewCell) {
                                        break;
                                    }
                                    if (currentStickerPreviewCell != null) {
                                        currentStickerPreviewCell.setScaled(false);
                                    }
                                    currentStickerPreviewCell = (StickerEmojiCell) view;
                                    StickerPreviewViewer.getInstance()
                                            .setKeyboardHeight(EmojiView.this.getMeasuredHeight());
                                    StickerPreviewViewer.getInstance()
                                            .open(currentStickerPreviewCell.getSticker());
                                    currentStickerPreviewCell.setScaled(true);
                                    return true;
                                }
                            }
                            return true;
                        } else if (openStickerPreviewRunnable != null) {
                            if (event.getAction() == MotionEvent.ACTION_MOVE) {
                                if (Math.hypot(startX - event.getX(), startY - event.getY()) > AndroidUtilities
                                        .dp(10)) {
                                    AndroidUtilities.cancelRunOnUIThread(openStickerPreviewRunnable);
                                    openStickerPreviewRunnable = null;
                                }
                            } else {
                                AndroidUtilities.cancelRunOnUIThread(openStickerPreviewRunnable);
                                openStickerPreviewRunnable = null;
                            }
                        }
                    }
                }
                return false;
            }
        });
        stickersOnItemClickListener = new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long i) {
                if (!(view instanceof StickerEmojiCell)) {
                    return;
                }
                if (openStickerPreviewRunnable != null) {
                    AndroidUtilities.cancelRunOnUIThread(openStickerPreviewRunnable);
                    openStickerPreviewRunnable = null;
                }
                if (currentStickerPreviewCell != null) {
                    currentStickerPreviewCell.setScaled(false);
                    currentStickerPreviewCell = null;
                }
                StickerEmojiCell cell = (StickerEmojiCell) view;
                if (cell.isDisabled()) {
                    return;
                }
                cell.disable();
                TLRPC.Document document = cell.getSticker();
                Integer count = stickersUseHistory.get(document.id);
                if (count == null) {
                    count = 0;
                }
                if (count == 0 && stickersUseHistory.size() > 19) {
                    for (int a = recentStickers.size() - 1; a >= 0; a--) {
                        TLRPC.Document sticker = recentStickers.get(a);
                        stickersUseHistory.remove(sticker.id);
                        recentStickers.remove(a);
                        if (stickersUseHistory.size() <= 19) {
                            break;
                        }
                    }
                }
                stickersUseHistory.put(document.id, ++count);

                saveRecentStickers();
                if (listener != null) {
                    listener.onStickerSelected(document);
                }
            }
        };
        stickersGridView.setOnItemClickListener(stickersOnItemClickListener);
        AndroidUtilities.setListViewEdgeEffectColor(stickersGridView, 0xfff5f6f7);

        stickersWrap = new FrameLayout(context);
        stickersWrap.addView(stickersGridView);

        TextView textView = new TextView(context);
        textView.setText(LocaleController.getString("NoStickers", R.string.NoStickers));
        textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
        textView.setTextColor(0xff888888);
        stickersWrap.addView(textView,
                LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
        stickersGridView.setEmptyView(textView);

        scrollSlidingTabStrip = new ScrollSlidingTabStrip(context) {

            boolean startedScroll;
            float lastX;
            float lastTranslateX;
            boolean first = true;

            @Override
            public boolean onInterceptTouchEvent(MotionEvent ev) {
                if (getParent() != null) {
                    getParent().requestDisallowInterceptTouchEvent(true);
                }
                return super.onInterceptTouchEvent(ev);
            }

            @Override
            public boolean onTouchEvent(MotionEvent ev) {
                if (Build.VERSION.SDK_INT >= 11) {
                    if (first) {
                        first = false;
                        lastX = ev.getX();
                    }
                    float newTranslationX = ViewProxy.getTranslationX(scrollSlidingTabStrip);
                    if (scrollSlidingTabStrip.getScrollX() == 0 && newTranslationX == 0) {
                        if (!startedScroll && lastX - ev.getX() < 0) {
                            if (pager.beginFakeDrag()) {
                                startedScroll = true;
                                lastTranslateX = ViewProxy.getTranslationX(scrollSlidingTabStrip);
                            }
                        } else if (startedScroll && lastX - ev.getX() > 0) {
                            if (pager.isFakeDragging()) {
                                pager.endFakeDrag();
                                startedScroll = false;
                            }
                        }
                    }
                    if (startedScroll) {
                        int dx = (int) (ev.getX() - lastX + newTranslationX - lastTranslateX);
                        try {
                            pager.fakeDragBy(dx);
                            lastTranslateX = newTranslationX;
                        } catch (Exception e) {
                            try {
                                pager.endFakeDrag();
                            } catch (Exception e2) {
                                //don't promt
                            }
                            startedScroll = false;
                            FileLog.e("tmessages", e);
                        }
                    }
                    lastX = ev.getX();
                    if (ev.getAction() == MotionEvent.ACTION_CANCEL
                            || ev.getAction() == MotionEvent.ACTION_UP) {
                        first = true;
                        if (startedScroll) {
                            pager.endFakeDrag();
                            startedScroll = false;
                        }
                    }
                    return startedScroll || super.onTouchEvent(ev);
                }
                return super.onTouchEvent(ev);
            }
        };
        scrollSlidingTabStrip.setUnderlineHeight(AndroidUtilities.dp(1));
        scrollSlidingTabStrip.setIndicatorColor(0xffe2e5e7);
        scrollSlidingTabStrip.setUnderlineColor(0xffe2e5e7);
        scrollSlidingTabStrip.setVisibility(INVISIBLE);
        addView(scrollSlidingTabStrip,
                LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.LEFT | Gravity.TOP));
        ViewProxy.setTranslationX(scrollSlidingTabStrip, AndroidUtilities.displaySize.x);
        updateStickerTabs();
        scrollSlidingTabStrip.setDelegate(new ScrollSlidingTabStrip.ScrollSlidingTabStripDelegate() {
            @Override
            public void onPageSelected(int page) {
                if (page == 0) {
                    pager.setCurrentItem(0);
                    return;
                } else if (page == 1 && !recentStickers.isEmpty()) {
                    views.get(6).setSelection(0);
                    return;
                }
                int index = page - (recentStickers.isEmpty() ? 1 : 2);
                if (index == stickerSets.size()) {
                    if (listener != null) {
                        listener.onStickersSettingsClick();
                    }
                    return;
                }
                if (index >= stickerSets.size()) {
                    index = stickerSets.size() - 1;
                }
                views.get(6).setSelection(stickersGridAdapter.getPositionForPack(stickerSets.get(index)));
            }
        });

        stickersGridView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                    int totalItemCount) {
                int count = view.getChildCount();
                for (int a = 0; a < count; a++) {
                    View child = view.getChildAt(a);
                    if (child.getHeight() + child.getTop() < AndroidUtilities.dp(5)) {
                        firstVisibleItem++;
                    } else {
                        break;
                    }
                }
                scrollSlidingTabStrip
                        .onPageScrolled(stickersGridAdapter.getTabForPosition(firstVisibleItem) + 1, 0);
            }
        });
    }

    setBackgroundColor(0xfff5f6f7);

    pager = new ViewPager(context) {
        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            if (getParent() != null) {
                getParent().requestDisallowInterceptTouchEvent(true);
            }
            return super.onInterceptTouchEvent(ev);
        }
    };
    pager.setAdapter(new EmojiPagesAdapter());

    pagerSlidingTabStripContainer = new LinearLayout(context) {
        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            if (getParent() != null) {
                getParent().requestDisallowInterceptTouchEvent(true);
            }
            return super.onInterceptTouchEvent(ev);
        }
    };
    pagerSlidingTabStripContainer.setOrientation(LinearLayout.HORIZONTAL);
    pagerSlidingTabStripContainer.setBackgroundColor(0xfff5f6f7);
    addView(pagerSlidingTabStripContainer, LayoutHelper.createFrame(LayoutParams.MATCH_PARENT, 48));

    PagerSlidingTabStrip pagerSlidingTabStrip = new PagerSlidingTabStrip(context);
    pagerSlidingTabStrip.setViewPager(pager);
    pagerSlidingTabStrip.setShouldExpand(true);
    pagerSlidingTabStrip.setIndicatorHeight(AndroidUtilities.dp(2));
    pagerSlidingTabStrip.setUnderlineHeight(AndroidUtilities.dp(1));
    pagerSlidingTabStrip.setIndicatorColor(0xff2b96e2);
    pagerSlidingTabStrip.setUnderlineColor(0xffe2e5e7);
    pagerSlidingTabStripContainer.addView(pagerSlidingTabStrip, LayoutHelper.createLinear(0, 48, 1.0f));
    pagerSlidingTabStrip.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            EmojiView.this.onPageScrolled(position, getMeasuredWidth(), positionOffsetPixels);
        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

    FrameLayout frameLayout = new FrameLayout(context);
    pagerSlidingTabStripContainer.addView(frameLayout, LayoutHelper.createLinear(52, 48));

    backspaceButton = new ImageView(context) {
        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                backspacePressed = true;
                backspaceOnce = false;
                postBackspaceRunnable(350);
            } else if (event.getAction() == MotionEvent.ACTION_CANCEL
                    || event.getAction() == MotionEvent.ACTION_UP) {
                backspacePressed = false;
                if (!backspaceOnce) {
                    if (listener != null && listener.onBackspace()) {
                        backspaceButton.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP);
                    }
                }
            }
            super.onTouchEvent(event);
            return true;
        }
    };
    backspaceButton.setImageResource(R.drawable.ic_smiles_backspace);
    backspaceButton.setBackgroundResource(R.drawable.ic_emoji_backspace);
    backspaceButton.setScaleType(ImageView.ScaleType.CENTER);
    frameLayout.addView(backspaceButton, LayoutHelper.createFrame(52, 48));

    View view = new View(context);
    view.setBackgroundColor(0xffe2e5e7);
    frameLayout.addView(view, LayoutHelper.createFrame(52, 1, Gravity.LEFT | Gravity.BOTTOM));

    recentsWrap = new FrameLayout(context);
    recentsWrap.addView(views.get(0));

    TextView textView = new TextView(context);
    textView.setText(LocaleController.getString("NoRecent", R.string.NoRecent));
    textView.setTextSize(18);
    textView.setTextColor(0xff888888);
    textView.setGravity(Gravity.CENTER);
    recentsWrap.addView(textView);
    views.get(0).setEmptyView(textView);

    addView(pager, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT,
            Gravity.LEFT | Gravity.TOP, 0, 48, 0, 0));

    emojiSize = AndroidUtilities.dp(AndroidUtilities.isTablet() ? 40 : 32);
    pickerView = new EmojiColorPickerView(context);
    pickerViewPopup = new EmojiPopupWindow(pickerView,
            popupWidth = AndroidUtilities.dp((AndroidUtilities.isTablet() ? 40 : 32) * 6 + 10 + 4 * 5),
            popupHeight = AndroidUtilities.dp(AndroidUtilities.isTablet() ? 64 : 56));
    pickerViewPopup.setOutsideTouchable(true);
    pickerViewPopup.setClippingEnabled(true);
    pickerViewPopup.setInputMethodMode(EmojiPopupWindow.INPUT_METHOD_NOT_NEEDED);
    pickerViewPopup.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED);
    pickerViewPopup.getContentView().setFocusableInTouchMode(true);
    pickerViewPopup.getContentView().setOnKeyListener(new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_MENU && event.getRepeatCount() == 0
                    && event.getAction() == KeyEvent.ACTION_UP && pickerViewPopup != null
                    && pickerViewPopup.isShowing()) {
                pickerViewPopup.dismiss();
                return true;
            }
            return false;
        }
    });

    loadRecents();
}

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

public EmojiView(boolean needStickers, Context context) {
    super(context);

    showStickers = needStickers;//from www . jav a2s . c o  m

    //Creates 5 grid views for each emoji set +
    //for (int i = 0; i < EmojiData.dataColored.length; i++) {
    GridView gridView = new GridView(context);
    if (AndroidUtilities.isTablet()) {
        gridView.setColumnWidth(AndroidUtilities.dp(60));
    } else {
        gridView.setColumnWidth(AndroidUtilities.dp(45));
    }
    gridView.setNumColumns(-1);
    views.add(gridView);

    //EmojiGridAdapter emojiGridAdapter = new EmojiGridAdapter(i-1);
    EmojiGridAdapter emojiGridAdapter = new EmojiGridAdapter(-1);
    gridView.setAdapter(emojiGridAdapter);
    AndroidUtilities.setListViewEdgeEffectColor(gridView, 0xfff5f6f7);
    adapters.add(emojiGridAdapter);
    //}

    if (showStickers) {
        StickersQuery.checkStickers();
        stickersGridView = new GridView(context) {
            @Override
            public boolean onInterceptTouchEvent(MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    int x = (int) event.getX();
                    int y = (int) event.getY();
                    int count = stickersGridView.getChildCount();
                    for (int a = 0; a < count; a++) {
                        View view = stickersGridView.getChildAt(a);
                        int top = view.getTop();
                        int bottom = view.getBottom();
                        int left = view.getLeft();
                        int right = view.getRight();
                        if (top > y || bottom < y || left > x || right < x) {
                            continue;
                        }
                        if (!(view instanceof StickerEmojiCell) || !((StickerEmojiCell) view).showingBitmap()) {
                            return super.onInterceptTouchEvent(event);
                        }
                        startX = x;
                        startY = y;
                        currentStickerPreviewCell = (StickerEmojiCell) view;
                        openStickerPreviewRunnable = new Runnable() {
                            @Override
                            public void run() {
                                if (openStickerPreviewRunnable == null) {
                                    return;
                                }
                                stickersGridView.setOnItemClickListener(null);
                                stickersGridView.requestDisallowInterceptTouchEvent(true);
                                openStickerPreviewRunnable = null;
                                StickerPreviewViewer.getInstance().setParentActivity((Activity) getContext());
                                StickerPreviewViewer.getInstance()
                                        .setKeyboardHeight(EmojiView.this.getMeasuredHeight());
                                StickerPreviewViewer.getInstance().open(currentStickerPreviewCell.getSticker());
                                currentStickerPreviewCell.setScaled(true);
                            }
                        };
                        AndroidUtilities.runOnUIThread(openStickerPreviewRunnable, 200);
                        return true;
                    }
                }
                return false;
            }
        };
        stickersGridView.setSelector(R.drawable.transparent);
        stickersGridView.setColumnWidth(AndroidUtilities.dp(72));
        stickersGridView.setNumColumns(-1);
        stickersGridView.setPadding(0, AndroidUtilities.dp(4), 0, 0);
        stickersGridView.setClipToPadding(false);
        views.add(stickersGridView);
        stickersGridAdapter = new StickersGridAdapter(context);
        stickersGridView.setAdapter(stickersGridAdapter);
        stickersGridView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (openStickerPreviewRunnable != null || StickerPreviewViewer.getInstance().isVisible()) {
                    if (event.getAction() == MotionEvent.ACTION_UP
                            || event.getAction() == MotionEvent.ACTION_CANCEL
                            || event.getAction() == MotionEvent.ACTION_POINTER_UP) {
                        AndroidUtilities.runOnUIThread(new Runnable() {
                            @Override
                            public void run() {
                                stickersGridView.setOnItemClickListener(stickersOnItemClickListener);
                            }
                        }, 150);
                        if (openStickerPreviewRunnable != null) {
                            AndroidUtilities.cancelRunOnUIThread(openStickerPreviewRunnable);
                            openStickerPreviewRunnable = null;
                        } else if (StickerPreviewViewer.getInstance().isVisible()) {
                            StickerPreviewViewer.getInstance().close();
                            if (currentStickerPreviewCell != null) {
                                currentStickerPreviewCell.setScaled(false);
                                currentStickerPreviewCell = null;
                            }
                        }
                    } else if (event.getAction() != MotionEvent.ACTION_DOWN) {
                        if (StickerPreviewViewer.getInstance().isVisible()) {
                            if (event.getAction() == MotionEvent.ACTION_MOVE) {
                                int x = (int) event.getX();
                                int y = (int) event.getY();
                                int count = stickersGridView.getChildCount();
                                for (int a = 0; a < count; a++) {
                                    View view = stickersGridView.getChildAt(a);
                                    int top = view.getTop();
                                    int bottom = view.getBottom();
                                    int left = view.getLeft();
                                    int right = view.getRight();
                                    if (top > y || bottom < y || left > x || right < x) {
                                        continue;
                                    }
                                    if (!(view instanceof StickerEmojiCell)
                                            || view == currentStickerPreviewCell) {
                                        break;
                                    }
                                    if (currentStickerPreviewCell != null) {
                                        currentStickerPreviewCell.setScaled(false);
                                    }
                                    currentStickerPreviewCell = (StickerEmojiCell) view;
                                    StickerPreviewViewer.getInstance()
                                            .setKeyboardHeight(EmojiView.this.getMeasuredHeight());
                                    StickerPreviewViewer.getInstance()
                                            .open(currentStickerPreviewCell.getSticker());
                                    currentStickerPreviewCell.setScaled(true);
                                    return true;
                                }
                            }
                            return true;
                        } else if (openStickerPreviewRunnable != null) {
                            if (event.getAction() == MotionEvent.ACTION_MOVE) {
                                if (Math.hypot(startX - event.getX(), startY - event.getY()) > AndroidUtilities
                                        .dp(10)) {
                                    AndroidUtilities.cancelRunOnUIThread(openStickerPreviewRunnable);
                                    openStickerPreviewRunnable = null;
                                }
                            } else {
                                AndroidUtilities.cancelRunOnUIThread(openStickerPreviewRunnable);
                                openStickerPreviewRunnable = null;
                            }
                        }
                    }
                }
                return false;
            }
        });
        stickersOnItemClickListener = new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long i) {
                if (!(view instanceof StickerEmojiCell)) {
                    return;
                }
                if (openStickerPreviewRunnable != null) {
                    AndroidUtilities.cancelRunOnUIThread(openStickerPreviewRunnable);
                    openStickerPreviewRunnable = null;
                }
                if (currentStickerPreviewCell != null) {
                    currentStickerPreviewCell.setScaled(false);
                    currentStickerPreviewCell = null;
                }
                StickerEmojiCell cell = (StickerEmojiCell) view;
                if (cell.isDisabled()) {
                    return;
                }
                cell.disable();
                TLRPC.Document document = cell.getSticker();
                Integer count = stickersUseHistory.get(document.id);
                if (count == null) {
                    count = 0;
                }
                if (count == 0 && stickersUseHistory.size() > 19) {
                    for (int a = recentStickers.size() - 1; a >= 0; a--) {
                        TLRPC.Document sticker = recentStickers.get(a);
                        stickersUseHistory.remove(sticker.id);
                        recentStickers.remove(a);
                        if (stickersUseHistory.size() <= 19) {
                            break;
                        }
                    }
                }
                stickersUseHistory.put(document.id, ++count);

                long id = StickersQuery.getStickerSetId(document);
                if (id != -1) {
                    count = stickerSetsUseCount.get(id);
                    if (count == null) {
                        count = 0;
                    }
                    stickerSetsUseCount.put(id, ++count);
                }

                saveRecentStickers();
                if (listener != null) {
                    listener.onStickerSelected(document);
                }
            }
        };
        stickersGridView.setOnItemClickListener(stickersOnItemClickListener);
        AndroidUtilities.setListViewEdgeEffectColor(stickersGridView, 0xfff5f6f7);

        stickersWrap = new FrameLayout(context);
        stickersWrap.addView(stickersGridView);

        TextView textView = new TextView(context);
        textView.setText(LocaleController.getString("NoStickers", R.string.NoStickers));
        textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
        textView.setTextColor(0xff888888);
        stickersWrap.addView(textView,
                LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
        stickersGridView.setEmptyView(textView);

        scrollSlidingTabStrip = new ScrollSlidingTabStrip(context) {

            boolean startedScroll;
            float lastX;
            float lastTranslateX;
            boolean first = true;

            @Override
            public boolean onInterceptTouchEvent(MotionEvent ev) {
                if (getParent() != null) {
                    getParent().requestDisallowInterceptTouchEvent(true);
                }
                return super.onInterceptTouchEvent(ev);
            }

            @Override
            public boolean onTouchEvent(MotionEvent ev) {
                if (Build.VERSION.SDK_INT >= 11) {
                    if (first) {
                        first = false;
                        lastX = ev.getX();
                    }
                    float newTranslationX = ViewProxy.getTranslationX(scrollSlidingTabStrip);
                    if (scrollSlidingTabStrip.getScrollX() == 0 && newTranslationX == 0) {
                        if (!startedScroll && lastX - ev.getX() < 0) {
                            if (pager.beginFakeDrag()) {
                                startedScroll = true;
                                lastTranslateX = ViewProxy.getTranslationX(scrollSlidingTabStrip);
                            }
                        } else if (startedScroll && lastX - ev.getX() > 0) {
                            if (pager.isFakeDragging()) {
                                pager.endFakeDrag();
                                startedScroll = false;
                            }
                        }
                    }
                    if (startedScroll) {
                        int dx = (int) (ev.getX() - lastX + newTranslationX - lastTranslateX);
                        try {
                            pager.fakeDragBy(dx);
                            lastTranslateX = newTranslationX;
                        } catch (Exception e) {
                            try {
                                pager.endFakeDrag();
                            } catch (Exception e2) {
                                //don't promt
                            }
                            startedScroll = false;
                            FileLog.e("tmessages", e);
                        }
                    }
                    lastX = ev.getX();
                    if (ev.getAction() == MotionEvent.ACTION_CANCEL
                            || ev.getAction() == MotionEvent.ACTION_UP) {
                        first = true;
                        if (startedScroll) {
                            pager.endFakeDrag();
                            startedScroll = false;
                        }
                    }
                    return startedScroll || super.onTouchEvent(ev);
                }
                return super.onTouchEvent(ev);
            }
        };
        scrollSlidingTabStrip.setUnderlineHeight(AndroidUtilities.dp(1));
        scrollSlidingTabStrip.setIndicatorColor(0xffe2e5e7);
        scrollSlidingTabStrip.setUnderlineColor(0xffe2e5e7);
        scrollSlidingTabStrip.setVisibility(INVISIBLE);
        addView(scrollSlidingTabStrip,
                LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.LEFT | Gravity.TOP));
        ViewProxy.setTranslationX(scrollSlidingTabStrip, AndroidUtilities.displaySize.x);
        updateStickerTabs();
        scrollSlidingTabStrip.setDelegate(new ScrollSlidingTabStrip.ScrollSlidingTabStripDelegate() {
            @Override
            public void onPageSelected(int page) {
                if (page == 0) {
                    pager.setCurrentItem(0);
                    return;
                } else if (page == 1 && !recentStickers.isEmpty()) {
                    views.get(6).setSelection(0);
                    return;
                }
                int index = page - (recentStickers.isEmpty() ? 1 : 2);
                if (index >= stickerSets.size()) {
                    index = stickerSets.size() - 1;
                }
                views.get(6).setSelection(stickersGridAdapter.getPositionForPack(stickerSets.get(index)));
            }
        });

        stickersGridView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                    int totalItemCount) {
                int count = view.getChildCount();
                for (int a = 0; a < count; a++) {
                    View child = view.getChildAt(a);
                    if (child.getHeight() + child.getTop() < AndroidUtilities.dp(5)) {
                        firstVisibleItem++;
                    } else {
                        break;
                    }
                }
                scrollSlidingTabStrip
                        .onPageScrolled(stickersGridAdapter.getTabForPosition(firstVisibleItem) + 1, 0);
            }
        });
    }

    setBackgroundColor(0xfff5f6f7);

    pager = new ViewPager(context) {
        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            if (getParent() != null) {
                getParent().requestDisallowInterceptTouchEvent(true);
            }
            return super.onInterceptTouchEvent(ev);
        }
    };
    pager.setAdapter(new EmojiPagesAdapter());

    pagerSlidingTabStripContainer = new LinearLayout(context) {
        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            if (getParent() != null) {
                getParent().requestDisallowInterceptTouchEvent(true);
            }
            return super.onInterceptTouchEvent(ev);
        }
    };
    pagerSlidingTabStripContainer.setOrientation(LinearLayout.HORIZONTAL);
    pagerSlidingTabStripContainer.setBackgroundColor(0xfff5f6f7);
    addView(pagerSlidingTabStripContainer, LayoutHelper.createFrame(LayoutParams.MATCH_PARENT, 48));

    PagerSlidingTabStrip pagerSlidingTabStrip = new PagerSlidingTabStrip(context);
    pagerSlidingTabStrip.setViewPager(pager);
    pagerSlidingTabStrip.setShouldExpand(true);
    pagerSlidingTabStrip.setIndicatorHeight(AndroidUtilities.dp(2));
    pagerSlidingTabStrip.setUnderlineHeight(AndroidUtilities.dp(1));
    pagerSlidingTabStrip.setIndicatorColor(0xff2b96e2);
    pagerSlidingTabStrip.setUnderlineColor(0xffe2e5e7);
    pagerSlidingTabStripContainer.addView(pagerSlidingTabStrip, LayoutHelper.createLinear(0, 48, 1.0f));
    pagerSlidingTabStrip.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            EmojiView.this.onPageScrolled(position, getMeasuredWidth(), positionOffsetPixels);
        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

    FrameLayout frameLayout = new FrameLayout(context);
    pagerSlidingTabStripContainer.addView(frameLayout, LayoutHelper.createLinear(52, 48));

    backspaceButton = new ImageView(context) {
        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                backspacePressed = true;
                backspaceOnce = false;
                postBackspaceRunnable(350);
            } else if (event.getAction() == MotionEvent.ACTION_CANCEL
                    || event.getAction() == MotionEvent.ACTION_UP) {
                backspacePressed = false;
                if (!backspaceOnce) {
                    if (listener != null && listener.onBackspace()) {
                        backspaceButton.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP);
                    }
                }
            }
            super.onTouchEvent(event);
            return true;
        }
    };
    backspaceButton.setImageResource(R.drawable.ic_smiles_backspace);
    backspaceButton.setBackgroundResource(R.drawable.ic_emoji_backspace);
    backspaceButton.setScaleType(ImageView.ScaleType.CENTER);
    frameLayout.addView(backspaceButton, LayoutHelper.createFrame(52, 48));

    View view = new View(context);
    view.setBackgroundColor(0xffe2e5e7);
    frameLayout.addView(view, LayoutHelper.createFrame(52, 1, Gravity.LEFT | Gravity.BOTTOM));

    recentsWrap = new FrameLayout(context);
    recentsWrap.addView(views.get(0));

    TextView textView = new TextView(context);
    textView.setText(LocaleController.getString("NoRecent", R.string.NoRecent));
    textView.setTextSize(18);
    textView.setTextColor(0xff888888);
    textView.setGravity(Gravity.CENTER);
    recentsWrap.addView(textView);
    views.get(0).setEmptyView(textView);

    addView(pager, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT,
            Gravity.LEFT | Gravity.TOP, 0, 48, 0, 0));

    emojiSize = AndroidUtilities.dp(AndroidUtilities.isTablet() ? 40 : 32);
    pickerView = new EmojiColorPickerView(context);
    pickerViewPopup = new EmojiPopupWindow(pickerView,
            popupWidth = AndroidUtilities.dp((AndroidUtilities.isTablet() ? 40 : 32) * 6 + 10 + 4 * 5),
            popupHeight = AndroidUtilities.dp(AndroidUtilities.isTablet() ? 64 : 56));
    pickerViewPopup.setOutsideTouchable(true);
    pickerViewPopup.setClippingEnabled(true);
    pickerViewPopup.setInputMethodMode(EmojiPopupWindow.INPUT_METHOD_NOT_NEEDED);
    pickerViewPopup.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED);
    pickerViewPopup.getContentView().setFocusableInTouchMode(true);
    pickerViewPopup.getContentView().setOnKeyListener(new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_MENU && event.getRepeatCount() == 0
                    && event.getAction() == KeyEvent.ACTION_UP && pickerViewPopup != null
                    && pickerViewPopup.isShowing()) {
                pickerViewPopup.dismiss();
                return true;
            }
            return false;
        }
    });

    loadRecents();
}

From source file:org.florescu.android.rangeseekbar.RangeSeekBar.java

/**
 * Handles thumb selection and movement. Notifies listener callback on certain events.
 *//*from  w w w  .  ja  v  a  2 s  . com*/
@Override
public boolean onTouchEvent(@NonNull MotionEvent event) {

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

    int pointerIndex;

    final int action = event.getAction();
    switch (action & MotionEvent.ACTION_MASK) {

    case MotionEvent.ACTION_DOWN:
        // Remember where the motion event started
        mActivePointerId = event.getPointerId(event.getPointerCount() - 1);
        pointerIndex = event.findPointerIndex(mActivePointerId);
        mDownMotionX = event.getX(pointerIndex);

        pressedThumb = evalPressedThumb(mDownMotionX);

        // Only handle thumb presses.
        if (pressedThumb == null) {
            pressedThumb = getClosestThumb(mDownMotionX);
            if (pressedThumb == null) {
                return false;
            }
        }

        if (listener != null) {
            listener.onRangeSeekBarPressed(this,
                    Thumb.MAX.equals(pressedThumb) ? getSelectedMaxValue() : getSelectedMinValue(),
                    pressedThumb);
        }

        setPressed(true);
        invalidate();
        onStartTrackingTouch();
        trackTouchEvent(event);
        attemptClaimDrag();

        break;
    case MotionEvent.ACTION_MOVE:
        if (pressedThumb != null) {

            if (mIsDragging) {
                trackTouchEvent(event);
            } else {
                // Scroll to follow the motion event
                pointerIndex = event.findPointerIndex(mActivePointerId);
                final float x = event.getX(pointerIndex);

                if (Math.abs(x - mDownMotionX) > mScaledTouchSlop) {
                    setPressed(true);
                    invalidate();
                    onStartTrackingTouch();
                    trackTouchEvent(event);
                    attemptClaimDrag();
                }
            }

            if (notifyWhileDragging && listener != null) {
                listener.onRangeSeekBarValueChanged(this,
                        Thumb.MAX.equals(pressedThumb) ? getSelectedMaxValue() : getSelectedMinValue(),
                        pressedThumb);
            }
        }
        break;
    case MotionEvent.ACTION_UP:
        if (mIsDragging) {
            trackTouchEvent(event);
            onStopTrackingTouch();
            setPressed(false);
        } else {
            // Touch up when we never crossed the touch slop threshold
            // should be interpreted as a tap-seek to that location.
            onStartTrackingTouch();
            trackTouchEvent(event);
            onStopTrackingTouch();
        }

        if (listener != null) {
            listener.onRangeSeekBarValueChanged(this,
                    Thumb.MAX.equals(pressedThumb) ? getSelectedMaxValue() : getSelectedMinValue(),
                    pressedThumb);
        }

        pressedThumb = null;
        invalidate();

        break;
    case MotionEvent.ACTION_POINTER_DOWN: {
        final int index = event.getPointerCount() - 1;
        // final int index = ev.getActionIndex();
        mDownMotionX = event.getX(index);
        mActivePointerId = event.getPointerId(index);
        invalidate();
        break;
    }
    case MotionEvent.ACTION_POINTER_UP:
        onSecondaryPointerUp(event);
        invalidate();
        break;
    case MotionEvent.ACTION_CANCEL:
        if (mIsDragging) {
            onStopTrackingTouch();
            setPressed(false);
        }
        invalidate(); // see above explanation
        break;
    }
    return true;
}

From source file:pl.edu.agh.mindmapex.gui.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    progressDialog = ProgressDialog.show(this, "Drawing", "Please wait...", true, false);
    if (WelcomeScreen.workbook != null) {
        workbook = WelcomeScreen.workbook;
    }/*from  w ww  .j  a va2s. c om*/
    res = getResources();
    if (handler == null) {
        handler = WorkbookHandler.createNewWorkbook();
    }

    if (workbook == null) {
        workbook = handler.getWorkbook();
        styleSheet = workbook.getStyleSheet();
        style1 = styleSheet.createStyle(IStyle.TOPIC);
        styleSheet.addStyle(style1, IStyleSheet.NORMAL_STYLES);
    }
    styleSheet = workbook.getStyleSheet();
    sheet1 = workbook.getPrimarySheet();
    res = getResources();
    if (style == null) {
        Intent intent = getIntent();
        style = intent.getStringExtra(WelcomeScreen.STYLE);
    }
    if (root == null) {

        //            Display display = getWindowManager().getDefaultDisplay();
        setContentView(R.layout.main_content_view);
        lay = (DrawView) findViewById(R.id.main_draw_view);
        lay.post(new Runnable() {
            @Override
            public void run() {
                rootTopic = sheet1.getRootTopic();
                root = new Box();

                //            Point size = new Point(lay.getWidth(), lay.getHeight());
                //            width = size.x / 2;
                //            height = size.y / 2;
                root.setPoint(new pl.edu.agh.mindmapex.common.Point(
                        lay.getWidth() / 2 - getResources().getDimensionPixelSize(R.dimen.init_box_size),
                        lay.getHeight() / 2
                                - getResources().getDimensionPixelSize(R.dimen.init_box_size_height)));
                lay.setZOrderOnTop(true);

                if (style.equals("ReadyMap")) {

                    if (sheet1.getTheme() == null) {
                        root.setPoint(new pl.edu.agh.mindmapex.common.Point(width, height));
                        final HashMap<String, Box> boxes = new HashMap<>();
                        root.topic = rootTopic;
                        if (root.topic.getStyleId() != null) {
                            checkStyle(root);
                        } else {
                            root.setDrawableShape(res.getDrawable(R.drawable.round_rect));
                        }

                        root.topic.setFolded(false);

                        boxes.put(root.topic.getId(), root);
                        for (ITopic t : root.topic.getAllChildren()) {
                            Box b = new Box();
                            b.topic = t;
                            boxes.put(root.topic.getId(), root);
                            b.point = new pl.edu.agh.mindmapex.common.Point();
                            if (b.topic.getStyleId() != null) {
                                checkStyle(b);
                            } else {
                                b.setDrawableShape(res.getDrawable(R.drawable.round_rect));
                            }
                            b.parent = root;
                            root.addChild(b);
                            rootTopic.add(b.topic, 0, ITopic.ATTACHED);
                            Utils.fireAddSubtopic(b, boxes);
                            boxes.put(t.getId(), b);
                        }
                        Utils.findRelationships(boxes);
                    } else {
                        if (sheet1.getTheme().getName().equals("%classic")
                                || sheet1.getTheme().getName().equals("%comic")) {
                            root.setPoint(new pl.edu.agh.mindmapex.common.Point(width, height));
                            root.topic = rootTopic;
                            final HashMap<String, Box> boxes = new HashMap<>();
                            if (root.topic.getStyleId() != null) {
                                checkStyle(root);
                            } else {
                                root.setDrawableShape(res.getDrawable(R.drawable.elipse));
                            }
                            root.topic.setFolded(false);
                            boxes.put(root.topic.getId(), root);

                            for (ITopic t : root.topic.getAllChildren()) {
                                Box b = new Box();
                                b.topic = t;
                                b.point = new pl.edu.agh.mindmapex.common.Point();
                                boxes.put(root.topic.getId(), root);
                                if (b.topic.getStyleId() != null) {
                                    checkStyle(b);
                                } else {
                                    b.setDrawableShape(res.getDrawable(R.drawable.round_rect));
                                }
                                b.parent = root;
                                root.addChild(b);
                                Utils.fireAddSubtopic(b, boxes);
                                rootTopic.add(b.topic, 0, ITopic.ATTACHED);
                                boxes.put(t.getId(), b);
                            }
                            Utils.findRelationships(boxes);
                        } else if (sheet1.getTheme().getName().equals("%simple")) {
                            root.setPoint(new pl.edu.agh.mindmapex.common.Point(width, height));
                            final HashMap<String, Box> boxes = new HashMap<>();
                            root.topic = rootTopic;
                            if (root.topic.getStyleId() != null) {
                                checkStyle(root);
                            } else {
                                root.setDrawableShape(res.getDrawable(R.drawable.elipse));
                            }
                            root.topic.setFolded(false);
                            boxes.put(root.topic.getId(), root);

                            for (ITopic t : root.topic.getAllChildren()) {
                                Box b = new Box();
                                b.topic = t;
                                b.point = new pl.edu.agh.mindmapex.common.Point();
                                boxes.put(root.topic.getId(), root);

                                if (b.topic.getStyleId() != null) {
                                    checkStyle(b);
                                } else {
                                    b.setDrawableShape(res.getDrawable(R.drawable.no_border));
                                }
                                b.parent = root;
                                root.addChild(b);
                                rootTopic.add(b.topic, 0, ITopic.ATTACHED);
                                Utils.fireAddSubtopic(b, boxes);
                                boxes.put(t.getId(), b);
                            }
                            Utils.findRelationships(boxes);
                        } else if (sheet1.getTheme().getName().equals("%bussiness")) {
                            root.setPoint(new pl.edu.agh.mindmapex.common.Point(width, height));
                            final HashMap<String, Box> boxes = new HashMap<>();
                            root.topic = rootTopic;
                            if (root.topic.getStyleId() != null) {
                                checkStyle(root);
                            } else {
                                root.setDrawableShape(res.getDrawable(R.drawable.round_rect));
                            }
                            root.topic.setFolded(false);

                            boxes.put(root.topic.getId(), root);

                            for (ITopic t : root.topic.getAllChildren()) {
                                Box b = new Box();
                                b.topic = t;
                                b.point = new pl.edu.agh.mindmapex.common.Point();
                                boxes.put(root.topic.getId(), root);
                                if (b.topic.getStyleId() != null) {
                                    checkStyle(b);
                                } else {
                                    b.setDrawableShape(res.getDrawable(R.drawable.rect));
                                }

                                b.parent = root;
                                root.addChild(b);
                                rootTopic.add(b.topic, 0, ITopic.ATTACHED);
                                Utils.fireAddSubtopic(b, boxes);
                                boxes.put(t.getId(), b);
                            }
                            Utils.findRelationships(boxes);
                        } else if (sheet1.getTheme().getName().equals("%academese")) {
                            root.setPoint(new pl.edu.agh.mindmapex.common.Point(width, height));
                            final HashMap<String, Box> boxes = new HashMap<>();
                            root.topic = rootTopic;
                            if (root.topic.getStyleId() != null) {
                                checkStyle(root);
                            } else {
                                root.setDrawableShape(res.getDrawable(R.drawable.rect));
                            }
                            root.topic.setFolded(false);
                            Style s = (Style) workbook.getStyleSheet().createStyle(IStyle.MAP);
                            s.setProperty(Styles.FillColor,
                                    Integer.toString(res.getColor(R.color.dark_gray), 16));
                            styleSheet.addStyle(s, IStyleSheet.NORMAL_STYLES);
                            sheet1.setStyleId(s.getId());
                            lay.setBackgroundColor(res.getColor(R.color.dark_gray));

                            boxes.put(root.topic.getId(), root);

                            for (ITopic t : root.topic.getAllChildren()) {
                                Box b = new Box();
                                b.topic = t;
                                b.point = new pl.edu.agh.mindmapex.common.Point();
                                boxes.put(root.topic.getId(), root);

                                if (b.topic.getStyleId() != null) {
                                    checkStyle(b);
                                } else {
                                    b.setDrawableShape(res.getDrawable(R.drawable.elipse));
                                }
                                b.parent = root;
                                root.addChild(b);
                                Utils.fireAddSubtopic(b, boxes);
                                rootTopic.add(b.topic, 0, ITopic.ATTACHED);
                                boxes.put(t.getId(), b);
                            }
                            Utils.findRelationships(boxes);
                        }
                    }
                } else if (style.equals("Default")) {

                    rootTopic.setTitleText("Central Topic");
                    root.topic = rootTopic;
                    root.topic.setFolded(false);
                    root.setDrawableShape(res.getDrawable(R.drawable.round_rect));
                    IStyle style3 = styleSheet.createStyle(IStyle.TOPIC);
                    style3.setProperty(Styles.FillColor, "#CCE5FF");
                    style3.setProperty(Styles.ShapeClass, Styles.TOPIC_SHAPE_ROUNDEDRECT);
                    style3.setProperty(Styles.LineClass, Styles.BRANCH_CONN_STRAIGHT);
                    styleSheet.addStyle(style3, IStyleSheet.NORMAL_STYLES);
                    rootTopic.setStyleId(style3.getId());
                } else if (style.equals("Classic")) {
                    rootTopic.setTitleText("Central Topic");
                    root.topic = rootTopic;
                    root.topic.setFolded(false);
                    root.setDrawableShape(res.getDrawable(R.drawable.elipse));
                    IStyle style2 = styleSheet.createStyle(IStyle.THEME);
                    style2.setName("%classic");
                    style2.setProperty(Styles.FillColor, String.valueOf(res.getColor(R.color.light_yellow)));
                    styleSheet.addStyle(style2, IStyleSheet.NORMAL_STYLES);
                    sheet1.setThemeId(style2.getId());
                    IStyle style3 = styleSheet.createStyle(IStyle.TOPIC);
                    style3.setProperty(Styles.FillColor, "#9ACD32");
                    style3.setProperty(Styles.ShapeClass, Styles.TOPIC_SHAPE_ELLIPSE);
                    style3.setProperty(Styles.LineClass, Styles.BRANCH_CONN_CURVE);
                    styleSheet.addStyle(style3, IStyleSheet.NORMAL_STYLES);
                    style2.setProperty(Style.TOPIC, style3.getId());
                    rootTopic.setStyleId(style3.getId());
                } else if (style.equals("Simple")) {
                    rootTopic.setTitleText("Central Topic");
                    root.topic = rootTopic;
                    root.topic.setFolded(false);
                    root.setDrawableShape(res.getDrawable(R.drawable.elipse));
                    IStyle style2 = styleSheet.createStyle(IStyle.THEME);
                    style2.setName("%simple");
                    style2.setProperty(Styles.FillColor, String.valueOf(res.getColor(R.color.white)));
                    styleSheet.addStyle(style2, IStyleSheet.NORMAL_STYLES);
                    sheet1.setThemeId(style2.getId());
                    IStyle style3 = styleSheet.createStyle(IStyle.TOPIC);
                    style3.setProperty(Styles.FillColor, "#FFFFFF");
                    style3.setProperty(Styles.ShapeClass, Styles.TOPIC_SHAPE_ELLIPSE);
                    style3.setProperty(Styles.LineClass, Styles.BRANCH_CONN_CURVE);
                    styleSheet.addStyle(style3, IStyleSheet.NORMAL_STYLES);
                    style2.setProperty(Style.TOPIC, style3.getId());
                    rootTopic.setStyleId(style3.getId());
                } else if (style.equals("Business")) {
                    rootTopic.setTitleText("Central Topic");
                    root.topic = rootTopic;
                    root.topic.setFolded(false);
                    root.setDrawableShape(res.getDrawable(R.drawable.round_rect));
                    IStyle style2 = styleSheet.createStyle(IStyle.THEME);
                    style2.setName("%business");
                    style2.setProperty(Styles.FillColor, String.valueOf(res.getColor(R.color.white)));
                    styleSheet.addStyle(style2, IStyleSheet.NORMAL_STYLES);
                    sheet1.setThemeId(style2.getId());
                    IStyle style3 = styleSheet.createStyle(IStyle.TOPIC);
                    style3.setProperty(Styles.FillColor, "#B87333");
                    style3.setProperty(Styles.ShapeClass, Styles.TOPIC_SHAPE_ROUNDEDRECT);
                    style3.setProperty(Styles.LineClass, Styles.BRANCH_CONN_CURVE);
                    styleSheet.addStyle(style3, IStyleSheet.NORMAL_STYLES);
                    style2.setProperty(Style.TOPIC, style3.getId());
                    rootTopic.setStyleId(style3.getId());
                } else if (style.equals("Academese")) {
                    rootTopic.setTitleText("Central Topic");
                    root.topic = rootTopic;
                    root.topic.setFolded(false);
                    root.setDrawableShape(res.getDrawable(R.drawable.rect));
                    IStyle style2 = styleSheet.createStyle(IStyle.THEME);
                    style2.setProperty(Styles.FillColor, "#404040");
                    styleSheet.addStyle(style2, IStyleSheet.NORMAL_STYLES);
                    sheet1.setStyleId(style2.getId());
                    lay.setBackgroundColor(res.getColor(R.color.dark_gray));
                    IStyle style3 = styleSheet.createStyle(IStyle.TOPIC);
                    style3.setProperty(Styles.FillColor, "#404040");
                    style3.setProperty(Styles.ShapeClass, Styles.TOPIC_SHAPE_RECT);
                    style3.setProperty(Styles.LineClass, Styles.BRANCH_CONN_STRAIGHT);
                    style3.setProperty(Styles.LineColor, "#FFFFFF");
                    styleSheet.addStyle(style3, IStyleSheet.NORMAL_STYLES);
                    style2.setProperty(Style.TOPIC, style3.getId());
                    rootTopic.setStyleId(style3.getId());
                }

            }
        });

    } else {
        setContentView(R.layout.main_content_view);
        lay = (DrawView) findViewById(R.id.main_draw_view);
        lay.setZOrderOnTop(true);
    }
    gestureDetector = new GestureDetector(this, gestList);
    Utils.lay = lay;
    if (lay != null) {
        lay.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                detector.onTouchEvent(event);

                switch (event.getActionMasked()) {
                case (MotionEvent.ACTION_OUTSIDE):
                    return true;
                case (MotionEvent.ACTION_UP):
                    break;
                case MotionEvent.ACTION_POINTER_UP:

                    if (!detector.isInProgress()) {
                        int count = event.getPointerCount(); // Number of 'fingers' in this time

                        Utils.getCoordsInView(lay, event, 1);
                        boxEdited = Utils.whichBox(lay, event);
                        float[] tab1 = Utils.getCoordsInView(lay, event, 0);
                        float[] tab = Utils.getCoordsInView(lay, event, 1);
                        if (count == 2 && boxEdited != null) {

                            if (tab.length == 2) {
                                if (mTourGuide != null)
                                    mTourGuide.cleanUp();
                                Box box1 = new Box();
                                box1.setPoint(new pl.edu.agh.mindmapex.common.Point(
                                        (int) tab[0] - (box1.getWidth() / 2),
                                        (int) tab[1] - (box1.getHeight() / 2)));
                                AddBox addBox = new AddBox();
                                Properties properties = new Properties();
                                properties.put("box", MainActivity.boxEdited);
                                properties.put("new_box", box1);
                                properties.put("root", root);
                                properties.put("res", res);
                                properties.put("style", style);
                                addBox.execute(properties);
                                MainActivity.addCommendUndo(addBox);
                                editContent(box1, addBox);
                                lay.updateBoxWithText(box1);

                            }
                        }

                        break;
                    }
                default:
                    break;
                }

                boolean response = gestureDetector.onTouchEvent(event);
                lay.requestFocus();
                InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                in.hideSoftInputFromWindow(lay.getApplicationWindowToken(), 0);
                return response;
            }
        });
        lay.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }
    Utils.context = this;
    this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayOptions(
            ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE | ActionBar.DISPLAY_SHOW_CUSTOM);
    actionBar.show();

    detector = new ScaleGestureDetector(this, new SimpleOnScaleGestureListener() {
        @Override
        public boolean onScaleBegin(ScaleGestureDetector detector) {
            mScaling = true;
            return true;
        }

        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            //                float focusX = detector.getFocusX();
            //                float focusY = detector.getFocusY();
            ////                lay.setPivotX(mid.x);
            ////                lay.setPivotY(mid.y);
            ////                               lay.pivotx = (int) (lastFocusX  + detector.getFocusX())/2;
            ////               lay.pivoty = (int) (lastFocusY+ detector.getFocusY())/2;
            //          //     lay.pivotx = (int) mid.x;
            //          //     lay.pivoty = (int) mid.y;
            //            //    lay.canvas.translate(-focusX,-focusY);
            lay.pivotx = detector.getFocusX();
            lay.pivoty = detector.getFocusY();
            //                lay.transx = (lay.pivotx);
            //                lay.transy = (lay.pivoty);
            //                lay.pivotx = (int) mid.x;
            //                lay.pivoty = (int) mid.y;
            //                lay.setPivotX(lastFocusX);
            //                lay.setPivotY(lastFocusY);
            float SF = detector.getScaleFactor();
            lay.zoomx *= SF;
            lay.zoomy *= SF;
            //    lay.canvas.scale(SF, SF, mid.x, mid.y);
            //                float focusShiftX = focusX - lastFocusX;
            //                float focusShiftY = focusY - lastFocusY;
            //lay.canvas.translate(focusX + focusShiftX, focusY + focusShiftY);
            //  lastFocusX = focusX;
            // lastFocusY = focusY;
            //  lay.transy = detector.getFocusY();
            // lay.zoomx = Math.max(0.1f, Math.min(lay.zoomx, 5.0f));
            // lay.zoomy = Math.max(0.1f, Math.min(lay.zoomy, 5.0f));
            return true;

        }
    });
    progressDialog.dismiss();
    lay.setId(View.generateViewId());
    lay.setSaveEnabled(true);

    if (savedInstanceState != null) {
        lay.transx = savedInstanceState.getFloat(TRANSX_KEY);
        lay.transy = savedInstanceState.getFloat(TRANSY_KEY);
        lay.zoomx = savedInstanceState.getFloat(ZOOMX_KEY);
        lay.zoomy = savedInstanceState.getFloat(ZOOMY_KEY);
        lay.pivotx = savedInstanceState.getFloat(PIVOTX_KEY);
        lay.pivoty = savedInstanceState.getFloat(PIVOTY_KEY);

    }

}

From source file:com.wunderlist.slidinglayer.SlidingLayer.java

@Override
public boolean onTouchEvent(MotionEvent ev) {

    if (ev.getAction() == MotionEvent.ACTION_DOWN && ev.getEdgeFlags() != 0) {
        return false;
    }/*from w w  w .j  a v a2s .c o m*/

    if (!mEnabled || !mIsDragging && !touchPointIsWithinBounds(mInitialX, mInitialY)) {
        return false;
    }

    if (mVelocityTracker == null) {
        mVelocityTracker = VelocityTracker.obtain();
    }
    mVelocityTracker.addMovement(ev);

    final int action = ev.getAction();

    switch (action & MotionEvent.ACTION_MASK) {
    case MotionEvent.ACTION_DOWN: {
        completeScroll();

        // Remember where the motion event started
        mLastX = mInitialRawX = getViewX(ev);
        mLastY = mInitialRawY = getViewY(ev);
        mInitialX = ev.getX();
        mInitialY = ev.getY();
        mActivePointerId = ev.getPointerId(0);
        break;
    }

    case MotionEvent.ACTION_MOVE: {

        final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);

        if (!touchPointIsWithinBounds(ev.getX(), ev.getY(), false))
            return false;

        final float x = getViewX(ev);
        final float y = getViewY(ev);

        final float deltaX = mLastX - x;
        final float deltaY = mLastY - y;

        mLastX = x;
        mLastY = y;

        if (!mIsDragging) {

            final float xDiff = Math.abs(x - mInitialRawX);
            final float yDiff = Math.abs(y - mInitialRawY);

            final boolean validHorizontalDrag = xDiff > mTouchSlop && xDiff > yDiff;
            final boolean validVerticalDrag = yDiff > mTouchSlop && yDiff > xDiff;

            if (validHorizontalDrag || validVerticalDrag) {
                mIsDragging = true;
                setDrawingCacheEnabled(true);
            }
        }

        if (mIsDragging) {

            final float oldScrollX = getScrollX();
            final float oldScrollY = getScrollY();
            float scrollX = oldScrollX + deltaX;
            float scrollY = oldScrollY + deltaY;

            // Log.d("Layer", String.format("Layer scrollX[%f],scrollY[%f]", scrollX, scrollY));
            final float leftBound, rightBound;
            final float bottomBound, topBound;
            switch (mScreenSide) {
            case STICK_TO_LEFT:
                topBound = bottomBound = rightBound = 0;
                leftBound = getWidth(); // How far left we can scroll
                break;
            case STICK_TO_RIGHT:
                rightBound = -getWidth();
                topBound = bottomBound = leftBound = 0;
                break;
            case STICK_TO_TOP:
                topBound = getHeight();
                bottomBound = rightBound = leftBound = 0;
                break;
            case STICK_TO_BOTTOM:
                bottomBound = -getHeight();
                topBound = rightBound = leftBound = 0;
                break;
            default:
                topBound = bottomBound = rightBound = leftBound = 0;
                break;
            }

            if (scrollX > leftBound) {
                scrollX = leftBound;
            } else if (scrollX < rightBound) {
                scrollX = rightBound;
            }
            if (scrollY > topBound) {
                scrollY = topBound;
            } else if (scrollY < bottomBound) {
                scrollY = bottomBound;
            }

            // Keep the precision
            mLastX += scrollX - (int) scrollX;
            mLastY += scrollY - (int) scrollY;

            scrollToAndNotify((int) scrollX, (int) scrollY);
        }
        break;
    }

    case MotionEvent.ACTION_UP: {

        if (mIsDragging) {
            final VelocityTracker velocityTracker = mVelocityTracker;
            velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
            final int initialVelocityX = (int) VelocityTrackerCompat.getXVelocity(velocityTracker,
                    mActivePointerId);
            final int initialVelocityY = (int) VelocityTrackerCompat.getYVelocity(velocityTracker,
                    mActivePointerId);
            final int scrollX = getScrollX();
            final int scrollY = getScrollY();

            final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
            final float x = getViewX(ev);
            final float y = getViewY(ev);

            int nextState = determineNextStateForDrag(scrollX, scrollY, initialVelocityX, initialVelocityY,
                    (int) mInitialRawX, (int) mInitialRawY, (int) x, (int) y);
            setLayerState(nextState, true, true, initialVelocityX, initialVelocityY);

            mActivePointerId = INVALID_VALUE;
            endDrag();

        } else if (changeStateOnTap) {
            int nextState = determineNextStateAfterTap();
            setLayerState(nextState, true, true);
        }
        break;
    }

    case MotionEvent.ACTION_CANCEL:
        if (mIsDragging) {
            setLayerState(mCurrentState, true, true);
            mActivePointerId = INVALID_VALUE;
            endDrag();
        }
        break;

    case MotionEvent.ACTION_POINTER_DOWN: {
        final int pointerIndex = MotionEventCompat.getActionIndex(ev);
        mActivePointerId = ev.getPointerId(pointerIndex);
        mLastX = getViewX(ev);
        mLastY = getViewY(ev);
        break;

    }
    case MotionEvent.ACTION_POINTER_UP: {
        onSecondaryPointerUp(ev);
        final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
        mLastX = getViewX(ev);
        mLastY = getViewY(ev);
        break;
    }
    }

    return true;
}

From source file:com.lovebridge.library.view.staggeredGridView.ExtendableListView.java

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    int action = ev.getAction();
    if (!mIsAttached) {
        // Something isn't right.
        // Since we rely on being attached to get data set change
        // notifications,
        // don't risk doing anything where we might try to resync and find
        // things
        // in a bogus state.
        return false;
    }/*from w w  w.  j  a  va  2s  . c  o m*/
    switch (action & MotionEvent.ACTION_MASK) {
    case MotionEvent.ACTION_DOWN: {
        int touchMode = mTouchMode;
        // TODO : overscroll
        // if (touchMode == TOUCH_MODE_OVERFLING || touchMode ==
        // TOUCH_MODE_OVERSCROLL) {
        // mMotionCorrection = 0;
        // return true;
        // }
        final int x = (int) ev.getX();
        final int y = (int) ev.getY();
        mActivePointerId = ev.getPointerId(0);
        int motionPosition = findMotionRow(y);
        if (touchMode != TOUCH_MODE_FLINGING && motionPosition >= 0) {
            // User clicked on an actual view (and was not stopping a
            // fling).
            // Remember where the motion event started
            mMotionX = x;
            mMotionY = y;
            mMotionPosition = motionPosition;
            mTouchMode = TOUCH_MODE_DOWN;
        }
        mLastY = Integer.MIN_VALUE;
        initOrResetVelocityTracker();
        mVelocityTracker.addMovement(ev);
        if (touchMode == TOUCH_MODE_FLINGING) {
            return true;
        }
        break;
    }
    case MotionEvent.ACTION_MOVE: {
        switch (mTouchMode) {
        case TOUCH_MODE_DOWN:
            int pointerIndex = ev.findPointerIndex(mActivePointerId);
            if (pointerIndex == -1) {
                pointerIndex = 0;
                mActivePointerId = ev.getPointerId(pointerIndex);
            }
            final int y = (int) ev.getY(pointerIndex);
            initVelocityTrackerIfNotExists();
            mVelocityTracker.addMovement(ev);
            if (startScrollIfNeeded(y)) {
                return true;
            }
            break;
        }
        break;
    }
    case MotionEvent.ACTION_CANCEL:
    case MotionEvent.ACTION_UP: {
        mTouchMode = TOUCH_MODE_IDLE;
        mActivePointerId = INVALID_POINTER;
        recycleVelocityTracker();
        reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE);
        break;
    }
    case MotionEvent.ACTION_POINTER_UP: {
        onSecondaryPointerUp(ev);
        break;
    }
    }
    return false;
}