Example usage for android.view MotionEvent ACTION_DOWN

List of usage examples for android.view MotionEvent ACTION_DOWN

Introduction

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

Prototype

int ACTION_DOWN

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

Click Source Link

Document

Constant for #getActionMasked : A pressed gesture has started, the motion contains the initial starting location.

Usage

From source file:com.antew.redditinpictures.library.widget.SwipeListView.java

@Override
public boolean onTouchEvent(MotionEvent event) {
    // Store width of this list for usage of swipe distance detection
    if (mViewWidth < 2) {
        mViewWidth = getWidth();//from ww w  .j  a v a  2s .c o  m
    }

    switch (MotionEventCompat.getActionMasked(event)) {
    case MotionEvent.ACTION_DOWN:
        int[] viewCoords = new int[2];
        // Figure out where the touch occurred.
        getLocationOnScreen(viewCoords);

        int touchX = (int) event.getRawX() - viewCoords[0];
        int touchY = (int) event.getRawY() - viewCoords[1];

        Rect rect = new Rect();
        View child;

        int childCount = getChildCount();
        for (int i = getHeaderViewsCount(); i <= childCount; i++) {
            // Go through each child view (excluding headers) and see if our touch pressed it.
            child = getChildAt(i);

            if (child != null) {
                //Get the child hit rectangle.
                child.getHitRect(rect);
                //If the child would be hit by this press.
                if (rect.contains(touchX, touchY)) {
                    // DIRECT HIT! You sunk my battleship. Now that we know which view was touched, store it off for use if a move occurs.
                    View frontView = child.findViewById(mFrontViewId);
                    View backView = child.findViewById(mBackViewId);
                    // Create our view pair.
                    mViewPair = new SwipeableViewPair(frontView, backView);
                    break;
                }
            }
        }

        if (mViewPair != null) {
            // If we have a view pair, record details about the inital touch for use later.
            mDownX = event.getRawX();
            mVelocityTracker = VelocityTracker.obtain();
            mVelocityTracker.addMovement(event);
        }
        break;
    case MotionEvent.ACTION_UP:
        if (mVelocityTracker != null) {
            // Add the movement so we can calculate velocity.
            mVelocityTracker.addMovement(event);
            mVelocityTracker.computeCurrentVelocity(1000);

            float deltaX = event.getRawX() - mDownX;
            float velocityX = Math.abs(mVelocityTracker.getXVelocity());
            float velocityY = Math.abs(mVelocityTracker.getYVelocity());

            if (mViewPair != null) {
                boolean shouldSwipe = false;

                // If the view has been moved a significant enough distance or if the view was flung, check to see if we should swipe it.
                if ((Math.abs(deltaX) > mViewWidth / 2 && mState == State.SWIPING)
                        || (mMinFlingVelocity <= velocityX && velocityX <= mMaxFlingVelocity
                                && velocityX > velocityY)) {
                    if (mSwipeDirection == SWIPE_DIRECTION_BOTH) {
                        // If the list is setup to swipe in either direction, just let it go.
                        shouldSwipe = true;
                    } else if (mSwipeDirection == SWIPE_DIRECTION_LEFT && deltaX < 0) {
                        // If the list is only setup to swipe left, then only allow swiping to the left.
                        shouldSwipe = true;
                    } else if (mSwipeDirection == SWIPE_DIRECTION_RIGHT && deltaX > 0) {
                        // If the list is only setup to swipe right, then only allow swiping to the right.
                        shouldSwipe = true;
                    }
                }

                if (shouldSwipe) {
                    // If a swipe should occur meaning someone has let go of a view they were moving and it was far/fast enough for us to consider it a swipe start the animations.
                    mViewPair.mFrontView.animate().translationX(deltaX >= 0 ? mViewWidth : -mViewWidth).alpha(0)
                            .setDuration(mAnimationTime);
                    mViewPair.mBackView.animate().alpha(1).setDuration(mAnimationTime);
                    // Now that the item is open, store it off so we can close it when we scroll if needed.
                    mSwipedViews.put(mViewPair.hashCode(), mViewPair);
                    // Clear out current variables as they are no longer needed and recycle the velocity tracker.
                    resetState();
                } else {
                    // If the user let go of the view and we don't think the swipe was intended to occur (it was cancelled basically) reset the views.
                    // Make sure the back disappears, since if it has buttons these can intercept touches from the front view.
                    mViewPair.mBackView.setVisibility(View.GONE);
                    mViewPair.mFrontView.animate().translationX(0).alpha(1).setDuration(mAnimationTime);
                    // Clear out current variables as they are no longer needed and recycle the velocity tracker.
                    resetState();
                }
            }
        }
        break;
    case MotionEvent.ACTION_MOVE:
        if (mVelocityTracker != null && mState != State.SCROLLING) {
            // If this is an initial movement and we aren't already swiping.
            // Add the movement so we can calculate velocity.
            mVelocityTracker.addMovement(event);
            mVelocityTracker.computeCurrentVelocity(1000);

            float deltaX = event.getRawX() - mDownX;
            float velocityX = Math.abs(mVelocityTracker.getXVelocity());
            float velocityY = Math.abs(mVelocityTracker.getYVelocity());

            // If the movement has been more than what is considered slop, and they are clearing moving horizontal not vertical.
            if (Math.abs(deltaX) > mTouchSlop && velocityX > velocityY) {
                boolean initiateSwiping = false;

                if (mSwipeDirection == SWIPE_DIRECTION_BOTH) {
                    // If the list is setup to swipe in either direction, just let it go.
                    initiateSwiping = true;
                } else if (mSwipeDirection == SWIPE_DIRECTION_LEFT && deltaX < 0) {
                    // If the list is only setup to swipe left, then only allow swiping to the left.
                    initiateSwiping = true;
                } else if (mSwipeDirection == SWIPE_DIRECTION_RIGHT && deltaX > 0) {
                    // If the list is only setup to swipe right, then only allow swiping to the right.
                    initiateSwiping = true;
                }

                if (initiateSwiping) {
                    ViewParent parent = getParent();
                    if (parent != null) {
                        // Don't allow parent to intercept touch (prevents NavigationDrawers from intercepting when near the bezel).
                        parent.requestDisallowInterceptTouchEvent(true);
                    }
                    // Change our state to swiping to start tranforming the item.
                    changeState(State.SWIPING);
                    // Make sure that touches aren't intercepted.
                    requestDisallowInterceptTouchEvent(true);

                    // Cancel ListView's touch to prevent it from being focused.
                    MotionEvent cancelEvent = MotionEvent.obtain(event);
                    cancelEvent.setAction(MotionEvent.ACTION_CANCEL
                            | (event.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT));
                    super.onTouchEvent(cancelEvent);
                } else {
                    // Otherwise we need to cancel the touch event to prevent accidentally selecting the item and also preventing the swipe in the wrong direction or an incomplete touch from moving the view.
                    MotionEvent cancelEvent = MotionEvent.obtain(event);
                    cancelEvent.setAction(MotionEvent.ACTION_CANCEL
                            | (event.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT));
                    super.onTouchEvent(cancelEvent);
                }
            }

            if (mState == State.SWIPING && mViewPair != null) {
                // Make sure the back is visible.
                mViewPair.mBackView.setVisibility(View.VISIBLE);
                //Fade the back in and front out as they move.
                mViewPair.mBackView.setAlpha(Math.min(1f, 2f * Math.abs(deltaX) / mViewWidth));
                mViewPair.mFrontView.setTranslationX(deltaX);
                mViewPair.mFrontView
                        .setAlpha(Math.max(0f, Math.min(1f, 1f - 2f * Math.abs(deltaX) / mViewWidth)));
                return true;
            }
        }
        break;
    }
    return super.onTouchEvent(event);
}

From source file:chan.android.app.bitwise.util.StaggeredGridView.java

@Override
public boolean onTouchEvent(MotionEvent ev) {
    mVelocityTracker.addMovement(ev);//from  w w  w. jav a 2s .  com
    final int action = ev.getAction() & MotionEventCompat.ACTION_MASK;

    int motionPosition = pointToPosition((int) ev.getX(), (int) ev.getY());

    switch (action) {
    case MotionEvent.ACTION_DOWN:

        mVelocityTracker.clear();
        mScroller.abortAnimation();
        mLastTouchY = ev.getY();
        mLastTouchX = ev.getX();
        motionPosition = pointToPosition((int) mLastTouchX, (int) mLastTouchY);
        mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
        mTouchRemainderY = 0;

        if (mTouchMode != TOUCH_MODE_FLINGING && !mDataChanged && motionPosition >= 0
                && getAdapter().isEnabled(motionPosition)) {
            mTouchMode = TOUCH_MODE_DOWN;

            mBeginClick = true;

            if (mPendingCheckForTap == null) {
                mPendingCheckForTap = new CheckForTap();
            }

            postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
        }

        mMotionPosition = motionPosition;
        invalidate();
        break;

    case MotionEvent.ACTION_MOVE:

        final int index = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
        if (index < 0) {
            Log.e(TAG, "onInterceptTouchEvent could not find pointer with id " + mActivePointerId
                    + " - did StaggeredGridView receive an inconsistent " + "event stream?");
            return false;
        }
        final float y = MotionEventCompat.getY(ev, index);
        final float dy = y - mLastTouchY + mTouchRemainderY;
        final int deltaY = (int) dy;
        mTouchRemainderY = dy - deltaY;

        if (Math.abs(dy) > mTouchSlop) {
            mTouchMode = TOUCH_MODE_DRAGGING;
        }

        if (mTouchMode == TOUCH_MODE_DRAGGING) {
            mLastTouchY = y;

            if (!trackMotionScroll(deltaY, true)) {
                // Break fling velocity if we impacted an edge.
                mVelocityTracker.clear();
            }
        }

        updateSelectorState();
        break;

    case MotionEvent.ACTION_CANCEL:
        mTouchMode = TOUCH_MODE_IDLE;
        updateSelectorState();
        setPressed(false);
        View motionView = this.getChildAt(mMotionPosition - mFirstPosition);
        if (motionView != null) {
            motionView.setPressed(false);
        }
        final Handler handler = getHandler();
        if (handler != null) {
            handler.removeCallbacks(mPendingCheckForLongPress);
        }

        if (mTopEdge != null) {
            mTopEdge.onRelease();
            mBottomEdge.onRelease();
        }

        mTouchMode = TOUCH_MODE_IDLE;

        break;

    case MotionEvent.ACTION_UP: {
        mVelocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
        final float velocity = VelocityTrackerCompat.getYVelocity(mVelocityTracker, mActivePointerId);
        final int prevTouchMode = mTouchMode;

        if (Math.abs(velocity) > mFlingVelocity) { // TODO
            mTouchMode = TOUCH_MODE_FLINGING;
            mScroller.fling(0, 0, 0, (int) velocity, 0, 0, Integer.MIN_VALUE, Integer.MAX_VALUE);
            mLastTouchY = 0;
            invalidate();
        } else {
            mTouchMode = TOUCH_MODE_IDLE;
        }

        if (!mDataChanged && mAdapter.isEnabled(motionPosition)) {
            // TODO : handle
            mTouchMode = TOUCH_MODE_TAP;
        } else {
            mTouchMode = TOUCH_MODE_REST;
        }

        switch (prevTouchMode) {
        case TOUCH_MODE_DOWN:
        case TOUCH_MODE_TAP:
        case TOUCH_MODE_DONE_WAITING:
            final View child = getChildAt(motionPosition - mFirstPosition);
            final float x = ev.getX();
            final boolean inList = x > getPaddingLeft() && x < getWidth() - getPaddingRight();
            if (child != null && !child.hasFocusable() && inList) {
                if (mTouchMode != TOUCH_MODE_DOWN) {
                    child.setPressed(false);
                }

                if (mPerformClick == null) {
                    invalidate();
                    mPerformClick = new PerformClick();
                }

                final PerformClick performClick = mPerformClick;
                performClick.mClickMotionPosition = motionPosition;
                performClick.rememberWindowAttachCount();

                if (mTouchMode == TOUCH_MODE_DOWN || mTouchMode == TOUCH_MODE_TAP) {
                    final Handler handlerTouch = getHandler();
                    if (handlerTouch != null) {
                        handlerTouch.removeCallbacks(mTouchMode == TOUCH_MODE_DOWN ? mPendingCheckForTap
                                : mPendingCheckForLongPress);
                    }

                    if (!mDataChanged && mAdapter.isEnabled(motionPosition)) {
                        mTouchMode = TOUCH_MODE_TAP;

                        layoutChildren(mDataChanged);
                        child.setPressed(true);
                        positionSelector(mMotionPosition, child);
                        setPressed(true);
                        if (mSelector != null) {
                            Drawable d = mSelector.getCurrent();
                            if (d != null && d instanceof TransitionDrawable) {
                                ((TransitionDrawable) d).resetTransition();
                            }
                        }
                        if (mTouchModeReset != null) {
                            removeCallbacks(mTouchModeReset);
                        }
                        mTouchModeReset = new Runnable() {
                            @Override
                            public void run() {
                                mTouchMode = TOUCH_MODE_REST;
                                child.setPressed(false);
                                setPressed(false);
                                if (!mDataChanged) {
                                    performClick.run();
                                }
                            }
                        };
                        postDelayed(mTouchModeReset, ViewConfiguration.getPressedStateDuration());

                    } else {
                        mTouchMode = TOUCH_MODE_REST;
                    }
                    return true;
                } else if (!mDataChanged && mAdapter.isEnabled(motionPosition)) {
                    performClick.run();
                }
            }

            mTouchMode = TOUCH_MODE_REST;
        }

        mBeginClick = false;

        updateSelectorState();
    }
        break;
    }
    return true;
}

From source file:com.example.SmartBoard.DrawingView.java

@Override
public boolean onTouchEvent(MotionEvent event) {
    //detect user touch
    float touchX = event.getX();
    float touchY = event.getY();
    //System.out.println("X"+touchX);
    // System.out.println("Y"+touchY);

    if (rectMode) {
        onTouchRectangleMode(event);//from  www .j  a  va 2s.  c  o  m
        return true;
    } else if (circleMode) {
        onTouchCircleMode(event);
        return true;
    } else if (lineMode) {
        onTouchLineMode(event);
        return true;
    } else if (textMode) {
        onTouchTextMode(event);
        return true;
    } else if (dragMode) {
        onTouchDragEvent(event);
        return true;
    } else if (removeObjectMode) {
        onRemoveObjectEvent(event);
        return true;
    } else if (colorDropperMode) {
        onTouchColorDropperMode(event);
        return true;
    } else if (textSizeMode) {
        onTouchTextResizeEvent(event);
        return true;
    }

    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
        drawPath.moveTo(touchX, touchY);
        break;
    case MotionEvent.ACTION_MOVE:
        drawPath.lineTo(touchX, touchY);
        break;
    case MotionEvent.ACTION_UP:
        drawCanvas.drawPath(drawPath, drawPaint);
        drawPath.reset();
        break;
    default:
        return false;
    }
    //System.out.println(mqtt);

    invalidate();
    mqtt.publish(touchX, touchY, event.getAction(), paintColor, mode, strokeWidth);

    return true;
}

From source file:com.z.stproperty.PropertyDetailFragment.java

/**
 * PHOTOS/*from  w  w w  .ja  v a2s . co  m*/
 * 
 * photos are shown in pager and when the user touches the pager 
 * then scroll stops to scroll vertically
 * 
 * DETAILS
 * 
 * Will show all the details related to the property or directory
 * like type,
 * title,
 * subtype,
 * district etc..
 * 
 * FACILITIES
 * 
 * This method will add the facility details by calling both
 * loadLandDisplay() and loadPortraitDisplay(). It will check weather there
 * is any facility or not and if there is no facility, then noFacilites
 * TextView is made visible. Else, the TextView is made gone and
 * directory_facilities_row layout is inflated and is added to
 * facilityParent.
 * 
 */
private View addProjectDetail() {
    View view = inflater.inflate(R.layout.property_details, null);
    try {
        projectDetailScrollView = (ScrollView) view.findViewById(R.id.DetailsScroll);
        if (detailsJson == null) {
            SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
            detailsJson = new JSONObject(mPrefs.getString("PropertyDetailJson", null));
        } else {
            SharedPreferences mPrefs = PreferenceManager
                    .getDefaultSharedPreferences(getActivity().getApplicationContext());
            mPrefs.edit().putString("PropertyDetailJson", detailsJson.toString()).commit();
        }
        try {
            ((HelveticaBold) view.findViewById(R.id.propertyTitle))
                    .setText(detailsJson.getString("property_title"));
            ((HelveticaBold) view.findViewById(R.id.projectName))
                    .setText(detailsJson.getString("project_name"));
            ((HelveticaBold) view.findViewById(R.id.Classification))
                    .setText(detailsJson.getString("property_classification"));
            ((HelveticaBold) view.findViewById(R.id.Tenure))
                    .setText(detailsJson.getString("tenure").replace("null", "-"));
            ((HelveticaBold) view.findViewById(R.id.propertyType))
                    .setText(detailsJson.getString("property_type"));
        } catch (Exception e) {
            Toast.makeText(getActivity(), e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
        }
        String floorArea = "-";
        if (!detailsJson.getString("builtin_area").equals("null")) {
            floorArea = detailsJson.getString("builtin_area") + " sqft";
        }
        ((HelveticaBold) view.findViewById(R.id.FloorArea)).setText(floorArea);

        ((HelveticaBold) view.findViewById(R.id.Address)).setText(detailsJson.getString("address"));
        ((HelveticaBold) view.findViewById(R.id.PostalCode))
                .setText(detailsJson.getString("postal_code").replace("null", "-"));
        String bedRoom = detailsJson.getString("bedrooms");
        String bathRoom = detailsJson.getString("bathroom");
        ((HelveticaBold) view.findViewById(R.id.Bedrooms))
                .setText(bedRoom.equals("null") || bedRoom.equals("0") ? "-" : bedRoom);
        ((HelveticaBold) view.findViewById(R.id.Bathrooms))
                .setText(bathRoom.equals("null") || bathRoom.equals("0") ? "-" : bathRoom);
        String psf = detailsJson.getString("psf");
        psf = psf.equals("null") || psf.equals("0") ? "-" : "SGD " + psf;
        ((HelveticaBold) view.findViewById(R.id.Psf)).setText(psf);
        String district = detailsJson.get("property_district").toString();
        String estate = detailsJson.get("property_estate").toString();
        if (!estate.equals("")) {
            district = estate;
        }
        ((HelveticaBold) view.findViewById(R.id.district)).setText(district);
        price = detailsJson.getString("price").replace("null", "");
        price = price.equals("") || price.equalsIgnoreCase("price on ask") ? price
                : "SGD " + SharedFunction.getPriceWithComma(detailsJson.getString("price"));
        view.findViewById(R.id.PSFDetailLayout).setVisibility(psf.equals("-") ? View.GONE : View.VISIBLE);
        if (price.equals("")) {
            ((LinearLayout) view.findViewById(R.id.PriceLayout)).setVisibility(View.GONE);
            ((LinearLayout) view.findViewById(R.id.PSFDetailLayout)).setVisibility(View.GONE);
        } else {
            ((HelveticaBold) view.findViewById(R.id.Price)).setText(price);
        }
        ((HelveticaBold) view.findViewById(R.id.Psf)).setText(psf);
        title = detailsJson.getString("property_title");
        prurl = detailsJson.getString("url");
        JSONObject sellerJson = detailsJson.getJSONObject("seller_info");
        String registerNoStr = sellerJson.getString("agent_cea_reg_no").replace("null", "-");
        String licenceNoStr = sellerJson.getString("agent_cea_license_no").replace("null", "-");
        String agentImageUrl = sellerJson.getString("agent_image");
        agentEmail = sellerJson.getString("agent_email");
        mobileNoStr = sellerJson.getString("agent_mobile");
        ((HelveticaBold) view.findViewById(R.id.AgentName))
                .setText("Agent Name : " + sellerJson.getString("agent_name"));
        ((HelveticaBold) view.findViewById(R.id.AgentMobile)).setText(sellerJson.getString("agent_mobile"));
        ((HelveticaBold) view.findViewById(R.id.RegisterNo)).setText(registerNoStr);
        ((HelveticaBold) view.findViewById(R.id.LicenceNo)).setText(licenceNoStr);
        ((HelveticaBold) view.findViewById(R.id.agentEmail)).setText(sellerJson.getString("agent_email"));
        ((HelveticaBold) view.findViewById(R.id.Agency)).setText(sellerJson.getString("agency_name"));
        imageLoader.displayImage(agentImageUrl, (ImageView) view.findViewById(R.id.AgentImage));

        if (detailsJson.getString("property_for").equalsIgnoreCase("for sale")
                && !price.equalsIgnoreCase("price on ask") && !price.equalsIgnoreCase("")) {
            ((Button) view.findViewById(R.id.LoanCalculator)).setOnClickListener(onClick);
        } else {
            ((Button) view.findViewById(R.id.LoanCalculator))
                    .setBackgroundResource(R.drawable.green_btn_disables);
            ((Button) view.findViewById(R.id.LoanCalculator)).getBackground().setAlpha(128);
        }
        final TextView imageCount = (TextView) view.findViewById(R.id.imageCount);
        view.findViewById(R.id.AgentMobile).setOnClickListener(onClick);
        view.findViewById(R.id.SendEmailBtn).setOnClickListener(onClick);
        view.findViewById(R.id.SendEnquiryBtn).setOnClickListener(onClick);
        ViewPager pager = (ViewPager) view.findViewById(R.id.pager);

        PhotoGallery gallery = new PhotoGallery();
        pager.setAdapter(gallery);
        JSONArray galery = detailsJson.getJSONArray("photos");
        final String[] photosArray = new String[galery.length()];
        imageCount.setText("1/" + photosArray.length);
        for (int index = 0; index < galery.length(); index++) {
            View imageLoading = inflater.inflate(R.layout.image_with_loading, null);
            ImageView image = (ImageView) imageLoading.findViewById(R.id.galleryPhoto);
            photosArray[index] = galery.getString(index).replace("_S.", "_L.");
            imageLoader.displayImage(galery.getString(index).replace("_S.", "_L."), image);
            final int curIndex = index;
            imageLoading.setOnTouchListener(new OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (event.getAction() == MotionEvent.ACTION_DOWN) {
                        projectDetailScrollView.requestDisallowInterceptTouchEvent(true);
                    } else if (event.getAction() == MotionEvent.ACTION_UP) {
                        projectDetailScrollView.requestDisallowInterceptTouchEvent(false);
                    }
                    return false;
                }
            });
            imageLoading.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Intent galleryIntent = new Intent(getActivity(), Photos.class);
                    galleryIntent.putExtra("photos1", photosArray);
                    galleryIntent.putExtra("selected", curIndex);
                    startActivity(galleryIntent);
                }
            });
            gallery.addView(imageLoading);
        }
        pager.setOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageSelected(int arg0) {
                imageCount.setText((arg0 + 1) + "/" + photosArray.length);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // Auto-generated method stub
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                // Auto-generated method stub
            }
        });
        gallery.notifyDataSetChanged();
        view.findViewById(R.id.BedBathLayout).setVisibility(
                Arrays.asList(Constants.RESIDENTIAL_TYPE).contains(detailsJson.getString("property_type"))
                        ? View.VISIBLE
                        : View.GONE);
    } catch (Exception e) {
        Log.e(this.getClass().getSimpleName(), e.getLocalizedMessage(), e);
    }
    return view;
}

From source file:co.vn.e_alarm.customwiget.SlidingLayer.java

@Override
public boolean onTouchEvent(MotionEvent ev) {
    if (!mEnabled || !mIsDragging && !mLastTouchAllowed && !allowSlidingFromHereX(ev, mInitialX)
            && !allowSlidingFromHereY(ev, mInitialY)) {
        return false;
    }//  w  w w  .  j a v  a  2s  .  c o m

    final int action = ev.getAction();

    if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL
            || action == MotionEvent.ACTION_OUTSIDE) {
        mLastTouchAllowed = false;
    } else {
        mLastTouchAllowed = true;
    }

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

    switch (action & MotionEventCompat.ACTION_MASK) {
    case MotionEvent.ACTION_DOWN:
        completeScroll();
        // Remember where the motion event started
        mLastX = mInitialX = ev.getX();
        mLastY = mInitialY = ev.getY();
        mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
        break;
    case MotionEvent.ACTION_MOVE:
        if (!mIsDragging) {
            final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
            if (pointerIndex == -1) {
                mActivePointerId = INVALID_POINTER;
                break;
            }
            final float x = MotionEventCompat.getX(ev, pointerIndex);
            final float xDiff = Math.abs(x - mLastX);
            final float y = MotionEventCompat.getY(ev, pointerIndex);
            final float yDiff = Math.abs(y - mLastY);
            if (xDiff > mTouchSlop && xDiff > yDiff) {
                mIsDragging = true;
                mLastX = x;
                setDrawingCacheEnabled(true);
            } else if (yDiff > mTouchSlop && yDiff > xDiff) {
                mIsDragging = true;
                mLastY = y;
                setDrawingCacheEnabled(true);
            }
        }
        if (mIsDragging) {
            // Scroll to follow the motion event
            final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
            if (activePointerIndex == -1) {
                mActivePointerId = INVALID_POINTER;
                break;
            }
            final float x = MotionEventCompat.getX(ev, activePointerIndex);
            final float y = MotionEventCompat.getY(ev, activePointerIndex);
            final float deltaX = mLastX - x;
            final float deltaY = mLastY - y;
            mLastX = x;
            mLastY = y;
            final float oldScrollX = getScrollX();
            final float oldScrollY = getScrollY();
            float scrollX = oldScrollX + deltaX;
            float scrollY = oldScrollY + deltaY;

            /*
             * Not need change : Done
             */
            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_MIDDLE:
                topBound = getHeight();
                bottomBound = -getHeight();
                leftBound = getWidth();
                rightBound = -getWidth();
                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:
                topBound = rightBound = leftBound = 0;
                bottomBound = -getHeight();
                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;
            }

            // TODO top/bottom bounds
            // Keep the precision
            mLastX += scrollX - (int) scrollX;
            mLastY += scrollY - (int) scrollY;
            scrollTo((int) scrollX, (int) scrollY);
        }
        break;
    //--- Doan nay dang kiem tra
    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 activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
            final float x = MotionEventCompat.getX(ev, activePointerIndex);
            final float y = MotionEventCompat.getY(ev, activePointerIndex);
            final int totalDeltaX = (int) (x - mInitialX);
            final int totalDeltaY = (int) (y - mInitialY);

            /*
            * Here is condition to check when to change state of layer. open / close.
            */
            boolean nextStateOpened = determineNextStateOpened(mIsOpen, scrollX, scrollY, initialVelocityX,
                    initialVelocityY, totalDeltaX, totalDeltaY);
            switchLayer(nextStateOpened, true, true, initialVelocityX, initialVelocityY);

            mActivePointerId = INVALID_POINTER;
            endDrag();
        } else if (mIsOpen && closeOnTapEnabled) {
            closeLayer(true);
        } else if (!mIsOpen && openOnTapEnabled) {
            openLayer(true);
        }
        break;
    case MotionEvent.ACTION_CANCEL:
        if (mIsDragging) {
            switchLayer(mIsOpen, true, true);
            mActivePointerId = INVALID_POINTER;
            endDrag();
        }
        break;
    case MotionEventCompat.ACTION_POINTER_DOWN: {
        final int index = MotionEventCompat.getActionIndex(ev);
        mLastX = MotionEventCompat.getX(ev, index);
        mLastY = MotionEventCompat.getY(ev, index);
        mActivePointerId = MotionEventCompat.getPointerId(ev, index);
        break;
    }
    case MotionEventCompat.ACTION_POINTER_UP:
        onSecondaryPointerUp(ev);
        mLastX = MotionEventCompat.getX(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId));
        mLastY = MotionEventCompat.getY(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId));
        break;
    }
    if (mActivePointerId == INVALID_POINTER) {
        mLastTouchAllowed = false;
    }
    return true;
}

From source file:com.android.widget.SlidingPaneLayout.java

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    final int action = MotionEventCompat.getActionMasked(ev);

    if (!mCanSlide || (mIsUnableToDrag && action != MotionEvent.ACTION_DOWN)) {
        mDragHelper.cancel();/*from   w w w.  j  av  a  2 s  .co  m*/
        return super.onInterceptTouchEvent(ev);
    }

    if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
        mDragHelper.cancel();
        return false;
    }

    float x, y;
    switch (action) {
    case MotionEvent.ACTION_DOWN:
        mIsUnableToDrag = false;
        x = ev.getX();
        y = ev.getY();
        mInitialMotionX = x;
        mInitialMotionY = y;
        break;
    case MotionEvent.ACTION_MOVE:
        x = ev.getX();
        y = ev.getY();
        final float adx = Math.abs(x - mInitialMotionX);
        final float ady = Math.abs(y - mInitialMotionY);
        final int slop = mDragHelper.getTouchSlop();
        if (ady > slop && adx > ady) {
            mDragHelper.cancel();
            mIsUnableToDrag = true;
            return false;
        }
    }

    final boolean interceptForDrag = mDragHelper.shouldInterceptTouchEvent(ev)
            // Intercept touch events only in the overhang area.
            && (ev.getY() <= mSlideOffset * mSlideRange + mOverhangSize && mState != STATE_OPENED_ENTIRELY);

    return interceptForDrag;
}

From source file:com.VVTeam.ManHood.Fragment.HistogramFragment.java

private void initViews(View view) {
    parentLayout = (RelativeLayout) view.findViewById(R.id.fragment_histogram_parent_relative_layout);
    /*BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 2;//  ww w.j  a  v  a  2 s  . co m
    parentLayout.setBackgroundDrawable(new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.histogram_bg, options)));*/
    settingsRelative = (RelativeLayout) view.findViewById(R.id.fragment_histogram_settings_relative_layout);
    markRelative = (RelativeLayout) view.findViewById(R.id.fragment_histogram_mark_relative_layout);
    worldRelative = (RelativeLayout) view.findViewById(R.id.fragment_histogram_world_relative);
    //        worldRelative.setSelected(true);
    worldRelative.setBackgroundResource(R.drawable.cell_p);
    areaRelative = (RelativeLayout) view.findViewById(R.id.fragment_histogram_area_relative);
    hoodRelative = (RelativeLayout) view.findViewById(R.id.fragment_histogram_hood_relative);
    yourResultButton = (Button) view.findViewById(R.id.fragment_histogram_your_result_button);

    contentRelative = (RelativeLayout) view.findViewById(R.id.fragment_histogram_content_relative);

    RelativeLayout shareRelative = (RelativeLayout) view
            .findViewById(R.id.fragment_histogram_share_button_relative);
    shareRelative.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            GoogleTracker.StarSendEvent(getActivity(), "ui_action", "user_action", "histogram_share");

            Bitmap image = makeSnapshot();

            File pictureFile = getOutputMediaFile();
            try {
                FileOutputStream fos = new FileOutputStream(pictureFile);
                image.compress(Bitmap.CompressFormat.PNG, 90, fos);
                fos.close();

            } catch (Exception e) {

            }

            //            String pathofBmp = Images.Media.insertImage(getActivity().getContentResolver(), makeSnapshot(), "Man Hood App", null);
            //             Uri bmpUri = Uri.parse(pathofBmp);
            Uri bmpUri = Uri.fromFile(pictureFile);
            final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
            emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            emailIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
            emailIntent.setType("image/png");
            emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Man Hood App");
            getActivity().startActivity(emailIntent);

        }
    });

    polarPlot = (PolarPlot) view.findViewById(R.id.polarPlot);

    thicknessHisto = (Histogram) view.findViewById(R.id.thicknessHisto);
    thicknessHisto.setOrientation(ORIENT.LEFT);
    thicknessHisto.setBackgroundColor(Color.TRANSPARENT);
    lengthHisto = (Histogram) view.findViewById(R.id.lengthHistogram);
    lengthHisto.setOrientation(ORIENT.RIGHT);
    lengthHisto.setBackgroundColor(Color.TRANSPARENT);
    girthHisto = (Histogram) view.findViewById(R.id.girthHistogram);
    girthHisto.setOrientation(ORIENT.BOTTOM);
    girthHisto.setBackgroundColor(Color.TRANSPARENT);

    lengthHisto.setCallBackListener(new HistogramCallBack() {

        @Override
        public void setValueSelectionChangedBlock(Histogram histo, HistogramSelectionState selectionState,
                float value, HistogramBin bin) {
            // TODO Auto-generated method stub
            if (selectionState == HistogramSelectionState.HistogramSelectionStateSelected) {
                histogramSelected = true;

                setNearestUserID(usersData.userIDWithNearestLength(value));

                setSelection(true, girthHisto, usersData.girthOfUserWithID(nearestUserID));
                setSelection(true, thicknessHisto, usersData.thicknessOfUserWithID(nearestUserID));
                //               setSelection(false, lengthHisto, 0.0f);
                setSelection(true, lengthHisto, value);

                setupPolarPlotWithCurrentUserID(nearestUserID, usersData, selfUserData);
            } else if (selectionState == HistogramSelectionState.HistogramSelectionStateNotSelected) {
                histogramSelected = false;

                setNearestUserID(null);
                setSelectionForAverage();
                setupPolarPlotWithCurrentUserID(nearestUserID, usersData, selfUserData);
            } else if (selectionState == HistogramSelectionState.HistogramSelectionStateDelayedFinish) {

            }

        }
    });

    girthHisto.setCallBackListener(new HistogramCallBack() {

        @Override
        public void setValueSelectionChangedBlock(Histogram histo, HistogramSelectionState selectionState,
                float value, HistogramBin bin) {
            // TODO Auto-generated method stub
            if (selectionState == HistogramSelectionState.HistogramSelectionStateSelected) {
                histogramSelected = true;

                setNearestUserID(usersData.userIDWithNearestGirth(value));

                setSelection(true, lengthHisto, usersData.lengthOfUserWithID(nearestUserID));
                setSelection(true, thicknessHisto, usersData.thicknessOfUserWithID(nearestUserID));
                //               setSelection(false, girthHisto, 0.0f);
                setSelection(true, girthHisto, value);

                setupPolarPlotWithCurrentUserID(nearestUserID, usersData, selfUserData);
            } else if (selectionState == HistogramSelectionState.HistogramSelectionStateNotSelected) {
                histogramSelected = false;

                setNearestUserID(null);

                setSelectionForAverage();
                setupPolarPlotWithCurrentUserID(nearestUserID, usersData, selfUserData);
            } else if (selectionState == HistogramSelectionState.HistogramSelectionStateDelayedFinish) {

            }

        }
    });

    thicknessHisto.setCallBackListener(new HistogramCallBack() {

        @Override
        public void setValueSelectionChangedBlock(Histogram histo, HistogramSelectionState selectionState,
                float value, HistogramBin bin) {
            // TODO Auto-generated method stub
            if (selectionState == HistogramSelectionState.HistogramSelectionStateSelected) {
                histogramSelected = true;

                setNearestUserID(usersData.userIDWithNearestThickness(value));

                setSelection(true, girthHisto, usersData.girthOfUserWithID(nearestUserID));
                setSelection(true, lengthHisto, usersData.lengthOfUserWithID(nearestUserID));
                //                 setSelection(false, thicknessHisto, 0.0f);
                setSelection(true, thicknessHisto, value);

                setupPolarPlotWithCurrentUserID(nearestUserID, usersData, selfUserData);
            } else if (selectionState == HistogramSelectionState.HistogramSelectionStateNotSelected) {
                histogramSelected = false;

                setNearestUserID(null);
                setSelectionForAverage();
                setupPolarPlotWithCurrentUserID(nearestUserID, usersData, selfUserData);
            } else if (selectionState == HistogramSelectionState.HistogramSelectionStateDelayedFinish) {

            }

        }
    });

    textBoxTitleLabel = (TextView) view.findViewById(R.id.txtBoxTitle);
    textBoxTitleLabel.setText("AVERAGE");

    layoutSubTitle = (LinearLayout) view.findViewById(R.id.layoutSubTitle);
    layoutSubTitle.setVisibility(View.INVISIBLE);
    textBoxSubtitleLabel = (TextView) view.findViewById(R.id.txtBoxSubTitleLabel);
    textBoxSubtitleValueLabel = (TextView) view.findViewById(R.id.txtBoxSubTitleValue);

    lengthSelectedLabel = (TextView) view.findViewById(R.id.txtlengthselected);
    lengthSelectedLabel.setText("50%");
    lengthTOPLabel = (TextView) view.findViewById(R.id.lengthTOPLabel);

    girthSelectedLabel = (TextView) view.findViewById(R.id.txtgirthselected);
    girthSelectedLabel.setText("50%");
    girthTOPLabel = (TextView) view.findViewById(R.id.girthTOPLabel);

    thicknessSelectedLabel = (TextView) view.findViewById(R.id.txtthicknessselected);
    thicknessSelectedLabel.setText("50%");
    thinkestAtTOPLabel = (TextView) view.findViewById(R.id.thinkestAtTOPLabel);

    curvedSelectedLabel = (TextView) view.findViewById(R.id.txtcurvedselected);
    curvedSelectedLabel.setText("0");

    girthTopLB = (TextView) view.findViewById(R.id.girthTop);
    girthMiddleLB = (TextView) view.findViewById(R.id.girthMiddle);
    girthBottomLB = (TextView) view.findViewById(R.id.girthBottom);

    thicknessTopLB = (TextView) view.findViewById(R.id.thicknessTop);
    thicknessMiddleLB = (TextView) view.findViewById(R.id.thicknessMiddle);
    thicknessBottomLB = (TextView) view.findViewById(R.id.thicknessBottom);

    lengthTopLB = (TextView) view.findViewById(R.id.lengthTop);
    lengthMiddleLB = (TextView) view.findViewById(R.id.lengthMiddle);
    lengthBottomLB = (TextView) view.findViewById(R.id.lengthBottom);

    settingsRelative.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ((MainActivity) getActivity()).openSettingsActivity();
        }
    });
    markRelative.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ((MainActivity) getActivity()).openCertificateActivity();
        }
    });

    worldRelative.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setSelectedRange(SliceRange.SliceRangeAll);
            updateRangeSwitch();
        }
    });
    areaRelative.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setSelectedRange(SliceRange.SliceRange200);
            updateRangeSwitch();
        }
    });
    hoodRelative.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setSelectedRange(SliceRange.SliceRange20);
            updateRangeSwitch();
        }
    });

    yourResultButton.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub

            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                youTouchDown();
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                youTouchUp();
                //               final Handler handler = new Handler();
                //                handler.postDelayed(new Runnable() {
                //                    @Override
                //                    public void run() {
                //                       youTouchUp();             
                //                    }
                //                }, 2000);
            }

            return true;
        }
    });

    RequestManager.getInstance().checkUser();

    /* in-app billing */
    String base64EncodedPublicKey = LICENSE_KEY;

    // Create the helper, passing it our context and the public key to verify signatures with
    Log.d(TAG, "Creating IAB helper.");
    mHelper = new IabHelper(getActivity(), base64EncodedPublicKey);

    // enable debug logging (for a production application, you should set this to false).
    mHelper.enableDebugLogging(true);

    // Start setup. This is asynchronous and the specified listener
    // will be called once setup completes.
    Log.d(TAG, "Starting setup.");
    mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
        public void onIabSetupFinished(IabResult result) {
            Log.d(TAG, "Setup finished.");

            if (!result.isSuccess()) {
                // Oh noes, there was a problem.
                Log.d(TAG, "Problem setting up in-app billing: " + result);
                return;
            }

            // Have we been disposed of in the meantime? If so, quit.
            if (mHelper == null)
                return;

            // IAB is fully set up. Now, let's get an inventory of stuff we own.
            Log.d(TAG, "Setup successful. Querying inventory.");
            mHelper.queryInventoryAsync(mGotInventoryListener);
        }
    });

}

From source file:sjizl.com.ChatActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (CommonUtilities.isInternetAvailable(getApplicationContext())) //returns true if internet available
    {//from   ww w  .j  a  v a 2s  .  c om

        SharedPreferences sp = getApplicationContext().getSharedPreferences("loginSaved", Context.MODE_PRIVATE);
        pid = sp.getString("pid", null);
        naam = sp.getString("naam", null);
        username = sp.getString("username", null);
        password = sp.getString("password", null);
        foto = sp.getString("foto", null);
        foto_num = sp.getString("foto_num", null);
        Bundle bundle = getIntent().getExtras();
        pid_user = bundle.getString("pid_user");
        user = bundle.getString("user");
        user_foto_num = bundle.getString("user_foto_num");
        user_foto = bundle.getString("user_foto");

        // Toast.makeText(getApplicationContext(), "pid_user"+pid_user, Toast.LENGTH_SHORT).show();

        if (user.equalsIgnoreCase(naam.toString())) {
            Toast.makeText(getApplicationContext(), "You can't message yourself!", Toast.LENGTH_SHORT).show();
            finish();
        }

        AbsListViewBaseActivity.imageLoader.init(ImageLoaderConfiguration.createDefault(getBaseContext()));

        //registerReceiver(mHandleMessageReceiver2, new IntentFilter(DISPLAY_MESSAGE_ACTION));
        setContentView(R.layout.activity_chat);

        imageLoader.loadImage("https://www.sjizl.com/fotos/" + user_foto_num + "/thumbs/" + user_foto + "",
                new SimpleImageLoadingListener() {
                    @Override
                    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {

                        d1 = new BitmapDrawable(getResources(), loadedImage);

                    }
                });

        imageLoader.loadImage("https://www.sjizl.com/fotos/" + foto_num + "/thumbs/" + foto + "",
                new SimpleImageLoadingListener() {
                    @Override
                    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {

                        d2 = new BitmapDrawable(getResources(), loadedImage);

                    }
                });

        smilbtn = (ImageView) findViewById(R.id.smilbtn);
        listView = (ListView) findViewById(android.R.id.list);
        underlayout = (LinearLayout) findViewById(R.id.underlayout);
        smiles_layout = (LinearLayout) findViewById(R.id.smiles);
        textView1_bgtext = (TextView) findViewById(R.id.textView1_bgtext);
        textView1_bgtext.setText(user);
        imageView2_dashboard = (ImageView) findViewById(R.id.imageView2_dashboard);
        imageView1_logo = (ImageView) findViewById(R.id.imageView1_logo);
        imageView_bericht = (ImageView) findViewById(R.id.imageView_bericht);
        textView2_under_title = (TextView) findViewById(R.id.textView2_under_title);
        right_lin = (LinearLayout) findViewById(R.id.right_lin);
        left_lin1 = (LinearLayout) findViewById(R.id.left_lin1);
        left_lin3 = (LinearLayout) findViewById(R.id.left_lin3);
        left_lin4 = (LinearLayout) findViewById(R.id.left_lin4);
        middle_lin = (LinearLayout) findViewById(R.id.middle_lin);
        smile_lin = (LinearLayout) findViewById(R.id.smile_lin);
        ber_lin = (LinearLayout) findViewById(R.id.ber_lin);
        progressBar_hole = (ProgressBar) findViewById(R.id.progressBar_hole);
        progressBar_hole.setVisibility(View.INVISIBLE);
        imageLoader.displayImage("http://sjizl.com/fotos/" + user_foto_num + "/thumbs/" + user_foto,
                imageView2_dashboard, options);
        new UpdateChat().execute();
        mNewMessage = (EditText) findViewById(R.id.newmsg);

        ber_lin = (LinearLayout) findViewById(R.id.ber_lin);
        photosend = (ImageView) findViewById(R.id.photosend);

        /*
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    
                    
                    
            imageLoader.loadImage("http://sjizl.com/fotos/"+user_foto_num+"/thumbs/"+user_foto, new SimpleImageLoadingListener() {
               @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
        super.onLoadingComplete(imageUri, view, loadedImage);
                
        Bitmap LoadedImage2 = loadedImage;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
           if(loadedImage!=null){
        LoadedImage2 = CommonUtilities.fastblur16(loadedImage, 4,getApplicationContext());
           }
        }
                
        if (Build.VERSION.SDK_INT >= 16) {
                
           listView.setBackground(new BitmapDrawable(getApplicationContext().getResources(), LoadedImage2));
                
          } else {
                
             listView.setBackgroundDrawable(new BitmapDrawable(LoadedImage2));
          }
                
        }
        }
            );
        }
        */
        final ImageView left_button;
        left_button = (ImageView) findViewById(R.id.imageView1_back);
        CommonUtilities u = new CommonUtilities();
        u.setHeaderConrols(getApplicationContext(), this, right_lin, left_lin3, left_lin4, left_lin1,
                left_button);

        listView.setOnScrollListener(new OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                mScrollState = scrollState;
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                    int totalItemCount) {
            }

        });
        listView.setLongClickable(true);
        registerForContextMenu(listView);

        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        viewPager_smiles = new ViewPager(this);
        viewPager_smiles.setId(0x1000);
        LayoutParams layoutParams555 = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        layoutParams555.width = LayoutParams.MATCH_PARENT;
        layoutParams555.height = (metrics.heightPixels / 2);
        viewPager_smiles.setLayoutParams(layoutParams555);
        TabsPagerAdapter mAdapter = new TabsPagerAdapter(getSupportFragmentManager(), mNewMessage);
        viewPager_smiles.setAdapter(mAdapter);
        LayoutInflater inflater = null;
        viewPager_smiles.setVisibility(View.VISIBLE);
        smiles_layout.addView(viewPager_smiles);
        smiles_layout.setVisibility(View.GONE);

        left_lin4.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    Intent profile = new Intent(getApplicationContext(), ProfileActivityMain.class);
                    profile.putExtra("user", user);
                    profile.putExtra("user_foto", user_foto);
                    profile.putExtra("user_foto_num", user_foto_num);
                    profile.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(profile);
                }
                return false;
            }
        });
        middle_lin.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    Intent profile = new Intent(getApplicationContext(), ProfileActivityMain.class);
                    profile.putExtra("user", user);
                    profile.putExtra("user_foto", user_foto);
                    profile.putExtra("user_foto_num", user_foto_num);
                    profile.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(profile);
                }
                return false;
            }
        });

        smile_lin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                opensmiles();
            }
        });

        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent dashboard = new Intent(getApplicationContext(), ProfileActivityMain.class);
                dashboard.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                dashboard.putExtra("user", ArrChatLines.get(position).getNaam());
                dashboard.putExtra("user_foto", foto);
                dashboard.putExtra("user_foto_num", foto_num);
                startActivity(dashboard);
            }
        });

        mNewMessage.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {

                    v.setFocusable(true);
                    v.setFocusableInTouchMode(true);

                    smiles_layout.setVisibility(View.GONE);
                    smilbtn.setImageResource(R.drawable.emoji_btn_normal);
                    return false;
                }
                return false;
            }
        });

        TextWatcher textWatcher = new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //after text changed
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                if (ArrChatLines.get(0).getblocked_profile().equals("1")) {

                } else if (ArrChatLines.get(0).getblocked_profile2().equals("1")) {

                } else {
                    CommonUtilities.startandsendwebsock(
                            "" + pid_user + " " + naam + " " + pid + " is typing to you ...");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                /*
                 AsyncHttpClient.getDefaultInstance().websocket("ws://sjizl.com:9300", "my-protocol", new WebSocketConnectCallback() {
                  @Override
                     public void onCompleted(Exception ex, WebSocket webSocket) {
                         if (ex != null) {
                   ex.printStackTrace();
                   return;
                         }
                         webSocket.send(""+pid_user+" "+naam+" "+pid+" is typing to you ...");
                                 
                         webSocket.close();
                     }
                 });
                 */
            }
        };

        photosend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (ArrChatLines.get(0).getblocked_profile().equals("1")) {

                } else if (ArrChatLines.get(0).getblocked_profile2().equals("1")) {

                } else {
                    openGallery(SELECT_FILE1);
                }
            }
        });

        mNewMessage.addTextChangedListener(textWatcher);

        ber_lin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SpannableStringBuilder spanStr = (SpannableStringBuilder) mNewMessage.getText();
                Spanned cs = (Spanned) mNewMessage.getText();
                String a = Html.toHtml(spanStr);
                String text = mNewMessage.getText().toString();
                mNewMessage.setText("");
                mNewMessage.requestFocus();
                mybmp2 = "http://sjizl.com/fotos/" + foto_num + "/thumbs/" + foto;
                if (text.length() < 1) {
                } else {
                    addItem(foto, foto_num, "0", naam, text.toString(),
                            "http://sjizl.com/fotos/" + foto_num + "/thumbs/" + foto, "", a);
                }
            }
        });

        hideSoftKeyboard();

    } else {

        Intent dashboard = new Intent(getApplicationContext(), NoInternetActivity.class);
        dashboard.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(dashboard);

        finish();
    }
    mNewMessage.clearFocus();
    listView.requestFocus();

    final String wsuri = "ws://sjizl.com:9300";

    WebSocketConnection mConnection8 = new WebSocketConnection();

    if (mConnection8.isConnected()) {
        mConnection8.reconnect();

    } else {
        try {
            mConnection8.connect(wsuri, new WebSocketConnectionHandler() {

                @Override
                public void onOpen() {
                    Log.d("TAG", "Status: Connected to " + wsuri);

                }

                @Override
                public void onTextMessage(String payload) {

                    if (payload.contains("message send")) {
                        String[] parts = payload.split(" ");
                        String zender = parts[0];
                        String send_from = parts[1];
                        String send_name = parts[2];
                        String send_foto = parts[3];
                        String send_foto_num = parts[4];
                        String send_xxx = parts[5];

                        //      Toast.makeText(getApplication(), "" +   "\n zender: "+zender+"" +   "\n pid_user: "+pid_user+"" +"\n pid: "+pid+"" +
                        //         "\n send_from: "+send_from, 
                        //                  Toast.LENGTH_LONG).show();
                        if (zender.equalsIgnoreCase(pid) || zender.equalsIgnoreCase(pid_user)) {

                            if (send_from.equalsIgnoreCase(pid_user) || send_from.equalsIgnoreCase(pid)) {

                                //Toast.makeText(getApplication(), "uu",    Toast.LENGTH_LONG).show();

                                new UpdateChat().execute();

                            }
                        }

                    } else if (payload.contains("is typing to you")) {

                        String[] parts = payload.split(" ");
                        String part1 = parts[0]; // 004
                        is_typing_name = parts[1]; // 034556
                        if (is_typing_name.equalsIgnoreCase(user)) {

                            if (ArrChatLines.size() > 0) {
                                oldvalue = ArrChatLines.get(0).getLaatstOnline();

                            } else {
                                oldvalue = textView2_under_title.getText().toString();
                            }

                            Timer t = new Timer(false);
                            t.schedule(new TimerTask() {
                                @Override
                                public void run() {
                                    runOnUiThread(new Runnable() {
                                        public void run() {
                                            textView2_under_title.setText("typing ...");
                                        }
                                    });
                                }
                            }, 2);

                            Timer t2 = new Timer(false);
                            t2.schedule(new TimerTask() {
                                @Override
                                public void run() {
                                    runOnUiThread(new Runnable() {
                                        public void run() {
                                            textView2_under_title.setText(oldvalue);
                                        }
                                    });
                                }
                            }, 2000);
                        }

                    }
                    Log.d("TAG", "Got echo: " + payload);
                }

                @Override
                public void onClose(int code, String reason) {
                    Log.d("TAG", "Connection lost.");
                }
            });
        } catch (WebSocketException e) {
            Log.d("TAG", e.toString());
        }
    }

}

From source file:com.appsummary.luoxf.myappsummary.navigationtabstrip.NavigationTabStrip.java

@Override
public boolean onTouchEvent(final MotionEvent event) {
    // Return if animation is running
    if (mAnimator.isRunning())
        return true;
    // If is not idle state, return
    if (mScrollState != ViewPager.SCROLL_STATE_IDLE)
        return true;

    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
        // Action down touch
        mIsActionDown = true;/*from   www  . j  av a2 s.  co  m*/
        if (!mIsViewPagerMode)
            break;
        // Detect if we touch down on tab, later to move
        mIsTabActionDown = (int) (event.getX() / mTabSize) == mIndex;
        break;
    case MotionEvent.ACTION_MOVE:
        // If tab touched, so move
        if (mIsTabActionDown) {
            mViewPager.setCurrentItem((int) (event.getX() / mTabSize), true);
            break;
        }
        if (mIsActionDown)
            break;
    case MotionEvent.ACTION_UP:
        // Press up and set tab index relative to current coordinate
        if (mIsActionDown)
            setTabIndex((int) (event.getX() / mTabSize));
    case MotionEvent.ACTION_CANCEL:
    case MotionEvent.ACTION_OUTSIDE:
    default:
        // Reset action touch variables
        mIsTabActionDown = false;
        mIsActionDown = false;
        break;
    }

    return true;
}

From source file:bk.vinhdo.taxiads.utils.view.SlidingLayer.java

@Override
public boolean onTouchEvent(MotionEvent ev) {

    final int action = ev.getAction();

    if (!mEnabled || !mIsDragging && !mLastTouchAllowed && !allowSlidingFromHereX(ev, mInitialX)
            && !allowSlidingFromHereY(ev, mInitialY)) {
        return false;
    }//from  w  w w .  ja  v  a 2 s  .co  m

    if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL
            || action == MotionEvent.ACTION_OUTSIDE) {
        mLastTouchAllowed = false;
    } else {
        mLastTouchAllowed = true;
    }

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

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

        // Remember where the motion event started
        mLastX = mInitialX = ev.getX();
        mLastY = mInitialY = ev.getY();
        mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
        break;
    case MotionEvent.ACTION_MOVE:
        if (!mIsDragging) {
            final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
            if (pointerIndex == -1) {
                mActivePointerId = INVALID_POINTER;
                break;
            }
            final float x = MotionEventCompat.getX(ev, pointerIndex);
            final float xDiff = Math.abs(x - mLastX);
            final float y = MotionEventCompat.getY(ev, pointerIndex);
            final float yDiff = Math.abs(y - mLastY);
            if (xDiff > mTouchSlop && xDiff > yDiff) {
                mIsDragging = true;
                mLastX = x;
                setDrawingCacheEnabled(true);
            } else if (yDiff > mTouchSlop && yDiff > xDiff) {
                mIsDragging = true;
                mLastY = y;
                setDrawingCacheEnabled(true);
            }
        }
        if (mIsDragging) {
            // Scroll to follow the motion event
            final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
            if (activePointerIndex == -1) {
                mActivePointerId = INVALID_POINTER;
                break;
            }
            final float x = MotionEventCompat.getX(ev, activePointerIndex);
            final float y = MotionEventCompat.getY(ev, activePointerIndex);
            if (mOnInteractListener != null) {
                mOnInteractListener.onActionMove(x, y);
            }
            final float deltaX = mLastX - x;
            final float deltaY = mLastY - y;
            mLastX = x;
            mLastY = y;
            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_MIDDLE:
                topBound = getHeight();
                bottomBound = -getHeight();
                leftBound = getWidth();
                rightBound = -getWidth();
                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:
                topBound = rightBound = leftBound = 0;
                bottomBound = -getHeight();
                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;
            }

            // TODO top/bottom bounds
            // Keep the precision
            mLastX += scrollX - (int) scrollX;
            mLastY += scrollY - (int) scrollY;
            scrollTo((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 activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
            final float x = MotionEventCompat.getX(ev, activePointerIndex);
            final float y = MotionEventCompat.getY(ev, activePointerIndex);
            final int totalDeltaX = (int) (x - mInitialX);
            final int totalDeltaY = (int) (y - mInitialY);

            boolean nextStateOpened = determineNextStateOpened(mIsOpen, scrollX, scrollY, initialVelocityX,
                    initialVelocityY, totalDeltaX, totalDeltaY);

            boolean isControlled = false;
            if (isControlled) {
                break;
            }

            switchLayer(nextStateOpened, true, true, initialVelocityX, initialVelocityY);

            mActivePointerId = INVALID_POINTER;
            Log.d("", "end drag from action up");
            endDrag();
        } else if (mIsOpen && closeOnTapEnabled) {
            closeLayer(true);
        } else if (!mIsOpen && openOnTapEnabled) {
            openLayer(true);
        }
        break;
    case MotionEvent.ACTION_CANCEL:
        if (mIsDragging) {
            switchLayer(mIsOpen, true, true);
            mActivePointerId = INVALID_POINTER;
            Log.d(TAG, "end drag from action cancel");
            endDrag();
        }
        break;
    case MotionEventCompat.ACTION_POINTER_DOWN: {
        final int index = MotionEventCompat.getActionIndex(ev);
        mLastX = MotionEventCompat.getX(ev, index);
        mLastY = MotionEventCompat.getY(ev, index);
        mActivePointerId = MotionEventCompat.getPointerId(ev, index);
        break;
    }
    case MotionEventCompat.ACTION_POINTER_UP:
        onSecondaryPointerUp(ev);
        mLastX = MotionEventCompat.getX(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId));
        mLastY = MotionEventCompat.getY(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId));
        break;
    }
    if (mActivePointerId == INVALID_POINTER) {
        mLastTouchAllowed = false;
    }
    return true;
}