Example usage for android.view View getTop

List of usage examples for android.view View getTop

Introduction

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

Prototype

@ViewDebug.CapturedViewProperty
public final int getTop() 

Source Link

Document

Top position of this view relative to its parent.

Usage

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

/**
 * Should be called with mPopulating set to true
 *
 * @param fromPosition Position to start filling from
 * @param overhang     the number of extra pixels to fill beyond the current top edge
 * @return the max overhang beyond the beginning of the view of any added items at the top
 *///  w  w  w.j ava 2 s . c  o m
final int fillUp(int fromPosition, int overhang) {

    final int paddingLeft = getPaddingLeft();
    final int paddingRight = getPaddingRight();
    final int itemMargin = mItemMargin;
    final int colWidth = (getWidth() - paddingLeft - paddingRight - itemMargin * (mColCount - 1)) / mColCount;
    mColWidth = colWidth;
    final int gridTop = getPaddingTop();
    final int fillTo = gridTop - overhang;
    int nextCol = getNextColumnUp();
    int position = fromPosition;

    while (nextCol >= 0 && mItemTops[nextCol] > fillTo && position >= 0) {
        // make sure the nextCol is correct. check to see if has been mapped
        // otherwise stick to getNextColumnUp()
        if (!mColMappings.get(nextCol).contains((Integer) position)) {
            for (int i = 0; i < mColMappings.size(); i++) {
                if (mColMappings.get(i).contains((Integer) position)) {
                    nextCol = i;
                    break;
                }
            }
        }

        //                displayMapping();

        final View child = obtainView(position, null);

        if (child == null)
            continue;

        LayoutParams lp = (LayoutParams) child.getLayoutParams();

        if (lp == null) {
            lp = this.generateDefaultLayoutParams();
            child.setLayoutParams(lp);
        }

        if (child.getParent() != this) {
            if (mInLayout) {
                addViewInLayout(child, 0, lp);
            } else {
                addView(child, 0);
            }
        }

        final int span = Math.min(mColCount, lp.span);
        final int widthSize = colWidth * span + itemMargin * (span - 1);
        final int widthSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);

        LayoutRecord rec;
        if (span > 1) {
            rec = getNextRecordUp(position, span);
            //                nextCol = rec.column;
            nextCol = 0;
        } else {
            rec = mLayoutRecords.get(position);
        }

        boolean invalidateBefore = false;
        if (rec == null) {
            rec = new LayoutRecord();
            mLayoutRecords.put(position, rec);
            rec.column = nextCol;
            rec.span = span;
        } else if (span != rec.span) {
            rec.span = span;
            rec.column = nextCol;
            invalidateBefore = true;
        } else {
            //                nextCol = rec.column;
        }

        if (mHasStableIds) {
            final long id = mAdapter.getItemId(position);
            rec.id = id;
            lp.id = id;
        }

        lp.column = nextCol;

        final int heightSpec;
        if (lp.height == LayoutParams.WRAP_CONTENT) {
            heightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
        } else {
            heightSpec = MeasureSpec.makeMeasureSpec(lp.height, MeasureSpec.EXACTLY);
        }
        child.measure(widthSpec, heightSpec);

        final int childHeight = child.getMeasuredHeight();
        if (invalidateBefore || (childHeight != rec.height && rec.height > 0)) {
            invalidateLayoutRecordsBeforePosition(position);
        }
        rec.height = childHeight;

        int itemTop = mItemTops[nextCol];

        final int startFrom;
        if (span > 1) {
            int lowest = mItemTops[nextCol];
            final int colEnd = Math.min(mColCount, nextCol + lp.span);
            for (int i = nextCol; i < colEnd; i++) {
                final int top = mItemTops[i];
                if (top < lowest) {
                    lowest = top;
                }
            }
            startFrom = lowest;
        } else {
            startFrom = mItemTops[nextCol];
        }

        int childBottom = startFrom;
        int childTop = childBottom - childHeight;
        final int childLeft = paddingLeft + nextCol * (colWidth + itemMargin);
        final int childRight = childLeft + child.getMeasuredWidth();

        //            if(position == 0){
        //                    if(this.getChildCount()>1 && this.mColCount>1){
        //                            childTop = this.getChildAt(1).getTop();
        //                            childBottom = childTop + childHeight;
        //                    }
        //            }

        child.layout(childLeft, childTop, childRight, childBottom);

        final int colEnd = Math.min(mColCount, nextCol + lp.span);
        for (int i = nextCol; i < colEnd; i++) {
            mItemTops[i] = childTop - itemMargin;
        }

        nextCol = getNextColumnUp();
        mFirstPosition = position--;
    }

    int highestView = getHeight();

    for (int i = 0; i < getChildCount(); i++) {
        final View child = getChildAt(i);
        if (child == null) {
            //                highestView = 0;
            break;
        }
        final int top = child.getTop();

        if (top < highestView) {
            highestView = top;
        }
    }

    return gridTop - highestView;
}

From source file:com.artifex.mupdflib.TwoWayView.java

private int getChildStartEdge(View child) {
    return (mIsVertical ? child.getTop() : child.getLeft());
}

From source file:com.aliasapps.seq.scroller.TwoWayView.java

/**
 * Do an arrow scroll based on focus searching.  If a new view is
 * given focus, return the selection delta and amount to scroll via
 * an {@link ArrowScrollFocusResult}, otherwise, return null.
 *
 * @param direction either {@link View#FOCUS_UP} or {@link View#FOCUS_DOWN} or
 *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT} depending on the
 *        current view orientation./*from  w  w  w.j  a v a 2 s .  c o m*/
 *
 * @return The result if focus has changed, or <code>null</code>.
 */
private ArrowScrollFocusResult arrowScrollFocused(final int direction) {
    forceValidFocusDirection(direction);

    final View selectedView = getSelectedView();
    final View newFocus;
    final int searchPoint;

    if (selectedView != null && selectedView.hasFocus()) {
        View oldFocus = selectedView.findFocus();
        newFocus = FocusFinder.getInstance().findNextFocus(this, oldFocus, direction);
    } else {
        if (direction == View.FOCUS_DOWN || direction == View.FOCUS_RIGHT) {
            final int start = (mIsVertical ? getPaddingTop() : getPaddingLeft());

            final int selectedStart;
            if (selectedView != null) {
                selectedStart = (mIsVertical ? selectedView.getTop() : selectedView.getLeft());
            } else {
                selectedStart = start;
            }

            searchPoint = Math.max(selectedStart, start);
        } else {
            final int end = (mIsVertical ? getHeight() - getPaddingBottom() : getWidth() - getPaddingRight());

            final int selectedEnd;
            if (selectedView != null) {
                selectedEnd = (mIsVertical ? selectedView.getBottom() : selectedView.getRight());
            } else {
                selectedEnd = end;
            }

            searchPoint = Math.min(selectedEnd, end);
        }

        final int x = (mIsVertical ? 0 : searchPoint);
        final int y = (mIsVertical ? searchPoint : 0);
        mTempRect.set(x, y, x, y);

        newFocus = FocusFinder.getInstance().findNextFocusFromRect(this, mTempRect, direction);
    }

    if (newFocus != null) {
        final int positionOfNewFocus = positionOfNewFocus(newFocus);

        // If the focus change is in a different new position, make sure
        // we aren't jumping over another selectable position.
        if (mSelectedPosition != INVALID_POSITION && positionOfNewFocus != mSelectedPosition) {
            final int selectablePosition = lookForSelectablePositionOnScreen(direction);

            final boolean movingForward = (direction == View.FOCUS_DOWN || direction == View.FOCUS_RIGHT);
            final boolean movingBackward = (direction == View.FOCUS_UP || direction == View.FOCUS_LEFT);

            if (selectablePosition != INVALID_POSITION
                    && ((movingForward && selectablePosition < positionOfNewFocus)
                            || (movingBackward && selectablePosition > positionOfNewFocus))) {
                return null;
            }
        }

        int focusScroll = amountToScrollToNewFocus(direction, newFocus, positionOfNewFocus);

        final int maxScrollAmount = getMaxScrollAmount();
        if (focusScroll < maxScrollAmount) {
            // Not moving too far, safe to give next view focus
            newFocus.requestFocus(direction);
            mArrowScrollFocusResult.populate(positionOfNewFocus, focusScroll);
            return mArrowScrollFocusResult;
        } else if (distanceToView(newFocus) < maxScrollAmount) {
            // Case to consider:
            // Too far to get entire next focusable on screen, but by going
            // max scroll amount, we are getting it at least partially in view,
            // so give it focus and scroll the max amount.
            newFocus.requestFocus(direction);
            mArrowScrollFocusResult.populate(positionOfNewFocus, maxScrollAmount);
            return mArrowScrollFocusResult;
        }
    }

    return null;
}

From source file:com.dishes.views.stageredggridview.StaggeredGridView.java

/**
 * Should be called with mPopulating set to true
 * /*ww  w .  j a  va 2 s  .c o m*/
 * @param fromPosition
 *            Position to start filling from
 * @param overhang
 *            the number of extra pixels to fill beyond the current top edge
 * @return the max overhang beyond the beginning of the view of any added
 *         items at the top
 */
final int fillUp(int fromPosition, int overhang) {

    final int paddingLeft = getPaddingLeft();
    final int paddingRight = getPaddingRight();
    // final int itemMargin = mItemMargin;
    final int leftMargin = mItemLeftMargin;
    final int rightMargin = mItemRightMargin;
    final int topMargin = mItemTopMargin;
    final int bottomMargin = mItemBottomMargin;

    final int colWidth = (getWidth() - paddingLeft - paddingRight
            - (leftMargin + rightMargin) * (mColCount - 1)) / mColCount;
    mColWidth = colWidth;
    final int gridTop = getPaddingTop();
    final int fillTo = gridTop - overhang;
    int nextCol = getNextColumnUp();
    int position = fromPosition;

    while (nextCol >= 0 && mItemTops[nextCol] > fillTo && position >= 0) {
        // make sure the nextCol is correct. check to see if has been mapped
        // otherwise stick to getNextColumnUp()
        if (!mColMappings.get(nextCol).contains((Integer) position)) {
            for (int i = 0; i < mColMappings.size(); i++) {
                if (mColMappings.get(i).contains((Integer) position)) {
                    nextCol = i;
                    break;
                }
            }
        }

        // displayMapping();

        final View child = obtainView(position, null);

        if (child == null)
            continue;

        LayoutParams lp = (LayoutParams) child.getLayoutParams();

        if (lp == null) {
            lp = this.generateDefaultLayoutParams();
            child.setLayoutParams(lp);
        }

        if (child.getParent() != this) {
            if (mInLayout) {
                addViewInLayout(child, 0, lp);
            } else {
                addView(child, 0);
            }
        }

        final int span = Math.min(mColCount, lp.span);
        final int widthSize = colWidth * span + (leftMargin + rightMargin) * (span - 1);
        final int widthSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);

        LayoutRecord rec;
        if (span > 1) {
            rec = getNextRecordUp(position, span);
            // nextCol = rec.column;
        } else {
            rec = mLayoutRecords.get(position);
        }

        boolean invalidateBefore = false;
        if (rec == null) {
            rec = new LayoutRecord();
            mLayoutRecords.put(position, rec);
            rec.column = nextCol;
            rec.span = span;
        } else if (span != rec.span) {
            rec.span = span;
            rec.column = nextCol;
            invalidateBefore = true;
        } else {
            // nextCol = rec.column;
        }

        if (mHasStableIds) {
            final long id = mAdapter.getItemId(position);
            rec.id = id;
            lp.id = id;
        }

        lp.column = nextCol;

        final int heightSpec;
        if (lp.height == LayoutParams.WRAP_CONTENT) {
            heightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
        } else {
            heightSpec = MeasureSpec.makeMeasureSpec(lp.height, MeasureSpec.EXACTLY);
        }
        child.measure(widthSpec, heightSpec);

        final int childHeight = child.getMeasuredHeight();
        if (invalidateBefore || (childHeight != rec.height && rec.height > 0)) {
            invalidateLayoutRecordsBeforePosition(position);
        }
        rec.height = childHeight;

        // int itemTop = mItemTops[nextCol];

        final int startFrom;
        if (span > 1) {
            int highest = mItemTops[nextCol];
            for (int i = nextCol + 1; i < nextCol + span; i++) {
                final int top = mItemTops[i];
                if (top < highest) {
                    highest = top;
                }
            }
            startFrom = highest;
        } else {
            startFrom = mItemTops[nextCol];
        }

        int childBottom = startFrom;
        int childTop = childBottom - childHeight;
        final int childLeft = paddingLeft + nextCol * (colWidth + (leftMargin + rightMargin));
        final int childRight = childLeft + child.getMeasuredWidth();

        // if(position == 0){
        // if(this.getChildCount()>1 && this.mColCount>1){
        // childTop = this.getChildAt(1).getTop();
        // childBottom = childTop + childHeight;
        // }
        // }

        child.layout(childLeft, childTop, childRight, childBottom);

        for (int i = nextCol; i < nextCol + span; i++) {
            mItemTops[i] = childTop - rec.getMarginAbove(i - nextCol) - (topMargin + bottomMargin);
        }

        nextCol = getNextColumnUp();
        mFirstPosition = position--;
    }

    int highestView = getHeight();

    for (int i = 0; i < mColCount; i++) {
        final View child = getFirstChildAtColumn(i);
        if (child == null) {
            highestView = 0;
            break;
        }
        final int top = child.getTop();

        if (top < highestView) {
            highestView = top;
        }
    }

    return gridTop - highestView;
}

From source file:com.appunite.list.AbsListView.java

/**
 * Track a motion scroll//w  w w  .ja va2  s. co m
 *
 * @param deltaY Amount to offset mMotionView. This is the accumulated delta since the motion
 *        began. Positive numbers mean the user's finger is moving down the screen.
 * @param incrementalDeltaY Change in deltaY from the previous event.
 * @return true if we're already at the beginning/end of the list and have nothing to do.
 */
boolean trackMotionScroll(int deltaY, int incrementalDeltaY) {
    final int childCount = getChildCount();
    if (childCount == 0) {
        return true;
    }

    final int firstTop = getChildAt(0).getTop();
    final int lastBottom = getChildAt(childCount - 1).getBottom();

    final Rect listPadding = mListPadding;

    // "effective padding" In this case is the amount of padding that affects
    // how much space should not be filled by items. If we don't clip to padding
    // there is no effective padding.
    int effectivePaddingTop = 0;
    int effectivePaddingBottom = 0;
    if (mClipToPadding) {
        effectivePaddingTop = listPadding.top;
        effectivePaddingBottom = listPadding.bottom;
    }

    // FIXME account for grid vertical spacing too?
    final int spaceAbove = effectivePaddingTop - firstTop;
    final int end = getHeight() - effectivePaddingBottom;
    final int spaceBelow = lastBottom - end;

    final int height = getHeight() - getPaddingBottom() - getPaddingTop();
    if (deltaY < 0) {
        deltaY = Math.max(-(height - 1), deltaY);
    } else {
        deltaY = Math.min(height - 1, deltaY);
    }

    if (incrementalDeltaY < 0) {
        incrementalDeltaY = Math.max(-(height - 1), incrementalDeltaY);
    } else {
        incrementalDeltaY = Math.min(height - 1, incrementalDeltaY);
    }

    final int firstPosition = mFirstPosition;

    // Update our guesses for where the first and last views are
    if (firstPosition == 0) {
        mFirstPositionDistanceGuess = firstTop - listPadding.top;
    } else {
        mFirstPositionDistanceGuess += incrementalDeltaY;
    }
    if (firstPosition + childCount == mItemCount) {
        mLastPositionDistanceGuess = lastBottom + listPadding.bottom;
    } else {
        mLastPositionDistanceGuess += incrementalDeltaY;
    }

    final boolean cannotScrollDown = (firstPosition == 0 && firstTop >= listPadding.top
            && incrementalDeltaY >= 0);
    final boolean cannotScrollUp = (firstPosition + childCount == mItemCount
            && lastBottom <= getHeight() - listPadding.bottom && incrementalDeltaY <= 0);

    if (cannotScrollDown || cannotScrollUp) {
        return incrementalDeltaY != 0;
    }

    final boolean down = incrementalDeltaY < 0;

    final boolean inTouchMode = isInTouchMode();
    if (inTouchMode) {
        hideSelector();
    }

    final int headerViewsCount = getHeaderViewsCount();
    final int footerViewsStart = mItemCount - getFooterViewsCount();

    int start = 0;
    int count = 0;

    if (down) {
        int top = -incrementalDeltaY;
        if (mClipToPadding) {
            top += listPadding.top;
        }
        for (int i = 0; i < childCount; i++) {
            final View child = getChildAt(i);
            if (child.getBottom() >= top) {
                break;
            } else {
                count++;
                int position = firstPosition + i;
                if (position >= headerViewsCount && position < footerViewsStart) {
                    mRecycler.addScrapView(child, position);
                }
            }
        }
    } else {
        int bottom = getHeight() - incrementalDeltaY;
        if (mClipToPadding) {
            bottom -= listPadding.bottom;
        }
        for (int i = childCount - 1; i >= 0; i--) {
            final View child = getChildAt(i);
            if (child.getTop() <= bottom) {
                break;
            } else {
                start = i;
                count++;
                int position = firstPosition + i;
                if (position >= headerViewsCount && position < footerViewsStart) {
                    mRecycler.addScrapView(child, position);
                }
            }
        }
    }

    mMotionViewNewTop = mMotionViewOriginalTop + deltaY;

    mBlockLayoutRequests = true;

    if (count > 0) {
        detachViewsFromParent(start, count);
        mRecycler.removeSkippedScrap();
    }

    // invalidate before moving the children to avoid unnecessary invalidate
    // calls to bubble up from the children all the way to the top
    if (!awakenScrollBars()) {
        invalidate();
    }

    offsetChildrenTopAndBottomUnhide(incrementalDeltaY);

    if (down) {
        mFirstPosition += count;
    }

    final int absIncrementalDeltaY = Math.abs(incrementalDeltaY);
    if (spaceAbove < absIncrementalDeltaY || spaceBelow < absIncrementalDeltaY) {
        fillGap(down);
    }

    if (!inTouchMode && mSelectedPosition != INVALID_POSITION) {
        final int childIndex = mSelectedPosition - mFirstPosition;
        if (childIndex >= 0 && childIndex < getChildCount()) {
            positionSelector(mSelectedPosition, getChildAt(childIndex));
        }
    } else if (mSelectorPosition != INVALID_POSITION) {
        final int childIndex = mSelectorPosition - mFirstPosition;
        if (childIndex >= 0 && childIndex < getChildCount()) {
            positionSelector(INVALID_POSITION, getChildAt(childIndex));
        }
    } else {
        mSelectorRect.setEmpty();
    }

    mBlockLayoutRequests = false;

    invokeOnItemScrollListener();

    return false;
}

From source file:com.artifex.mupdf.view.ThumbnailViews.java

/**
 * Do an arrow scroll based on focus searching. If a new view is given
 * focus, return the selection delta and amount to scroll via an
 * {@link ArrowScrollFocusResult}, otherwise, return null.
 * //  w  w w .  ja va2 s  .co  m
 * @param direction
 *            either {@link View#FOCUS_UP} or {@link View#FOCUS_DOWN} or
 *            {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT} depending
 *            on the current view orientation.
 * 
 * @return The result if focus has changed, or <code>null</code>.
 */
private ArrowScrollFocusResult arrowScrollFocused(final int direction) {
    forceValidFocusDirection(direction);

    final View selectedView = getSelectedView();
    final View newFocus;
    final int searchPoint;

    if (selectedView != null && selectedView.hasFocus()) {
        View oldFocus = selectedView.findFocus();
        newFocus = FocusFinder.getInstance().findNextFocus(this, oldFocus, direction);
    } else {
        if (direction == View.FOCUS_DOWN || direction == View.FOCUS_RIGHT) {
            final int start = (mIsVertical ? getPaddingTop() : getPaddingLeft());

            final int selectedStart;
            if (selectedView != null) {
                selectedStart = (mIsVertical ? selectedView.getTop() : selectedView.getLeft());
            } else {
                selectedStart = start;
            }

            searchPoint = Math.max(selectedStart, start);
        } else {
            final int end = (mIsVertical ? getHeight() - getPaddingBottom() : getWidth() - getPaddingRight());

            final int selectedEnd;
            if (selectedView != null) {
                selectedEnd = (mIsVertical ? selectedView.getBottom() : selectedView.getRight());
            } else {
                selectedEnd = end;
            }

            searchPoint = Math.min(selectedEnd, end);
        }

        final int x = (mIsVertical ? 0 : searchPoint);
        final int y = (mIsVertical ? searchPoint : 0);
        mTempRect.set(x, y, x, y);

        newFocus = FocusFinder.getInstance().findNextFocusFromRect(this, mTempRect, direction);
    }

    if (newFocus != null) {
        final int positionOfNewFocus = positionOfNewFocus(newFocus);

        // If the focus change is in a different new position, make sure
        // we aren't jumping over another selectable position.
        if (mSelectedPosition != INVALID_POSITION && positionOfNewFocus != mSelectedPosition) {
            final int selectablePosition = lookForSelectablePositionOnScreen(direction);

            final boolean movingForward = (direction == View.FOCUS_DOWN || direction == View.FOCUS_RIGHT);
            final boolean movingBackward = (direction == View.FOCUS_UP || direction == View.FOCUS_LEFT);

            if (selectablePosition != INVALID_POSITION
                    && ((movingForward && selectablePosition < positionOfNewFocus)
                            || (movingBackward && selectablePosition > positionOfNewFocus))) {
                return null;
            }
        }

        int focusScroll = amountToScrollToNewFocus(direction, newFocus, positionOfNewFocus);

        final int maxScrollAmount = getMaxScrollAmount();
        if (focusScroll < maxScrollAmount) {
            // Not moving too far, safe to give next view focus
            newFocus.requestFocus(direction);
            mArrowScrollFocusResult.populate(positionOfNewFocus, focusScroll);
            return mArrowScrollFocusResult;
        } else if (distanceToView(newFocus) < maxScrollAmount) {
            // Case to consider:
            // Too far to get entire next focusable on screen, but by going
            // max scroll amount, we are getting it at least partially in
            // view,
            // so give it focus and scroll the max amount.
            newFocus.requestFocus(direction);
            mArrowScrollFocusResult.populate(positionOfNewFocus, maxScrollAmount);
            return mArrowScrollFocusResult;
        }
    }

    return null;
}

From source file:me.ububble.speakall.fragment.ConversationGroupFragment.java

@Override
public boolean onTouch(View v, MotionEvent event) {

    int action = event.getActionMasked();
    switch (v.getId()) {
    case R.id.record_audio:
        switch (action) {
        case MotionEvent.ACTION_DOWN:
            textRecordingPress.setVisibility(View.INVISIBLE);
            rect = new Rect(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
            fechaAudioMillis = Calendar.getInstance().getTimeInMillis();
            File directory = new File(
                    Environment.getExternalStorageDirectory().getAbsolutePath() + "/SpeakOn/Audio/Sent");
            directory.mkdirs();//from  w w  w .  jav  a  2s  .c  om
            ficheroAudio = Environment.getExternalStorageDirectory().getAbsolutePath() + "/SpeakOn/Audio/Sent/"
                    + fechaAudioMillis + ".mp4";
            mediaRecorder = new MediaRecorder();
            mediaRecorder.setOutputFile(ficheroAudio);
            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
            try {
                mediaRecorder.prepare();
            } catch (IOException e) {
            }
            mediaRecorder.start();
            handler.post(new Runnable() {
                @Override
                public void run() {
                    finalTime += 1000;
                    int seconds = (int) (finalTime / 1000) % 60;
                    int minutes = (int) ((finalTime / (1000 * 60)) % 60);
                    int hours = (int) ((finalTime / (1000 * 60 * 60)) % 24);
                    timeFinal = String.format("%02d", minutes) + ":" + String.format("%02d", seconds);
                    timerAudio.setText(timeFinal);
                    if (!saveAudio) {
                        textRecording.setText(timeFinal);
                    }
                    handler.postDelayed(this, 1000);
                }
            });
            scaleAnimX = ObjectAnimator.ofFloat(recordAudioButton, "scaleX", 1, 1.2f);
            scaleAnimX.setDuration(800);
            scaleAnimX.setRepeatCount(ValueAnimator.INFINITE);
            scaleAnimX.setRepeatMode(ValueAnimator.REVERSE);
            scaleAnimY = ObjectAnimator.ofFloat(recordAudioButton, "scaleY", 1, 1.2f);
            scaleAnimY.setDuration(800);
            scaleAnimY.setRepeatCount(ValueAnimator.INFINITE);
            scaleAnimY.setRepeatMode(ValueAnimator.REVERSE);
            scaleAnimY.start();
            scaleAnimX.start();

            scaleRedBackgroundX = ObjectAnimator.ofFloat(audioRecordBackground, "scaleX", 1, 100f);
            scaleRedBackgroundX.setDuration(200);
            scaleRedBackgroundY = ObjectAnimator.ofFloat(audioRecordBackground, "scaleY", 1, 100f);
            scaleRedBackgroundY.setDuration(200);
            saveAudio = true;
            break;

        case MotionEvent.ACTION_MOVE:
            if (!rect.contains(v.getLeft() + (int) event.getX(), v.getTop() + (int) event.getY())) {
                recordAudioButton.setBackgroundResource(R.drawable.rounded_record_audio_white);
                timerAudio.setVisibility(View.GONE);
                textRecording.setTextColor(getResources().getColor(R.color.speak_all_red));
                if (!animatorBackground) {
                    textRecording.setText(timeFinal);
                    if (scaleRedBackgroundX.isRunning())
                        scaleRedBackgroundX.end();
                    if (scaleRedBackgroundY.isRunning())
                        scaleRedBackgroundY.end();
                    scaleRedBackgroundY.start();
                    scaleRedBackgroundX.start();
                    animatorBackground = true;
                }
                saveAudio = false;
            } else {
                recordAudioButton.setBackgroundResource(R.drawable.rounded_record_audio_red);
                textRecording.setTextColor(getResources().getColor(R.color.speak_all_white));
                textRecording.setText(getString(R.string.audio_record));
                timerAudio.setVisibility(View.VISIBLE);
                if (animatorBackground) {
                    if (scaleRedBackgroundX.isRunning())
                        scaleRedBackgroundX.end();
                    if (scaleRedBackgroundY.isRunning())
                        scaleRedBackgroundY.end();
                    ViewHelper.setScaleX(audioRecordBackground, 1);
                    ViewHelper.setScaleY(audioRecordBackground, 1);
                    animatorBackground = false;
                }
                saveAudio = true;
            }
            break;
        case MotionEvent.ACTION_UP:
            textRecordingPress.setVisibility(View.VISIBLE);
            animatorBackground = false;
            if (scaleAnimY.isRunning())
                scaleAnimY.end();
            if (scaleAnimX.isRunning())
                scaleAnimX.end();
            if (scaleRedBackgroundX.isRunning())
                scaleRedBackgroundX.end();
            if (scaleRedBackgroundY.isRunning())
                scaleRedBackgroundY.end();
            ViewHelper.setScaleX(audioRecordBackground, 1);
            ViewHelper.setScaleY(audioRecordBackground, 1);
            ViewHelper.setScaleX(recordAudioButton, 1);
            ViewHelper.setScaleY(recordAudioButton, 1);
            handler.removeCallbacksAndMessages(null);
            timerAudio.setText("00:00");
            timerAudio.setVisibility(View.VISIBLE);
            textRecording.setTextColor(getResources().getColor(R.color.speak_all_white));
            textRecording.setText(getString(R.string.audio_record));
            recordAudioButton.setBackgroundResource(R.drawable.rounded_record_audio_red);
            if (finalTime > 1000) {
                mediaRecorder.stop();
                mediaRecorder.release();
            } else {
                saveAudio = false;
                mediaRecorder.release();
            }
            finalTime = 0;
            timeFinal = "";
            if (saveAudio) {
                try {
                    hideKeyBoard();
                    final MsgGroups msjAudio = new MsgGroups();
                    JSONArray targets = new JSONArray();
                    JSONArray contactos = new JSONArray(grupo.targets);
                    String contactosId = null;
                    if (SpeakSocket.mSocket != null) {
                        if (SpeakSocket.mSocket.connected()) {
                            for (int i = 0; i < contactos.length(); i++) {
                                JSONObject contacto = contactos.getJSONObject(i);
                                JSONObject newContact = new JSONObject();
                                Contact contact = new Select().from(Contact.class)
                                        .where("id_contact = ?", contacto.getString("name")).executeSingle();
                                if (contact != null) {
                                    if (!contact.idContacto.equals(u.id)) {
                                        if (translate)
                                            newContact.put("lang", contact.lang);
                                        else
                                            newContact.put("lang", u.lang);
                                        newContact.put("name", contact.idContacto);
                                        newContact.put("screen_name", contact.screenName);
                                        newContact.put("status", 1);
                                        contactosId += contact.idContacto;
                                        targets.put(targets.length(), newContact);
                                    }
                                }
                            }
                        } else {
                            for (int i = 0; i < contactos.length(); i++) {
                                JSONObject contacto = contactos.getJSONObject(i);
                                JSONObject newContact = new JSONObject();
                                Contact contact = new Select().from(Contact.class)
                                        .where("id_contact = ?", contacto.getString("name")).executeSingle();
                                if (contact != null) {
                                    if (!contact.idContacto.equals(u.id)) {
                                        if (translate)
                                            newContact.put("lang", contact.lang);
                                        else
                                            newContact.put("lang", u.lang);
                                        newContact.put("name", contact.idContacto);
                                        newContact.put("screen_name", contact.screenName);
                                        newContact.put("status", -1);
                                        contactosId += contact.idContacto;
                                        targets.put(targets.length(), newContact);
                                    }
                                }
                            }
                        }
                    }
                    msjAudio.grupoId = grupo.grupoId;
                    msjAudio.mensajeId = u.id + grupo.grupoId + fechaAudioMillis + Settings.Secure
                            .getString(activity.getContentResolver(), Settings.Secure.ANDROID_ID);
                    msjAudio.emisor = u.id;
                    msjAudio.receptores = targets.toString();
                    msjAudio.mensaje = "new Audio";
                    msjAudio.emisorEmail = u.email;
                    msjAudio.emisorLang = u.lang;
                    msjAudio.translation = false;
                    msjAudio.emitedAt = fechaAudioMillis;
                    msjAudio.tipo = Integer.parseInt(getString(R.string.MSG_TYPE_GROUP_AUDIO));
                    msjAudio.delay = 0;
                    msjAudio.fileUploaded = false;
                    msjAudio.audioName = ficheroAudio;
                    msjAudio.save();
                    showNewMessage(msjAudio);

                } catch (Exception e) {
                    // TODO: handle exception
                }
            } else {
                new File(ficheroAudio).delete();
            }
            break;
        }
        break;
    }

    return true;
}

From source file:me.ububble.speakall.fragment.ConversationChatFragment.java

@Override
public boolean onTouch(View v, MotionEvent event) {
    int action = event.getActionMasked();
    switch (v.getId()) {
    case R.id.record_audio:
        switch (action) {
        case MotionEvent.ACTION_DOWN:
            textRecordingPress.setVisibility(View.INVISIBLE);
            rect = new Rect(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
            fechaAudioMillis = Calendar.getInstance().getTimeInMillis();
            File directory = new File(
                    Environment.getExternalStorageDirectory().getAbsolutePath() + "/SpeakOn/Audio/Sent");
            directory.mkdirs();//from w w  w  .  ja v a2 s . c  o m
            ficheroAudio = Environment.getExternalStorageDirectory().getAbsolutePath() + "/SpeakOn/Audio/Sent/"
                    + fechaAudioMillis + ".mp4";
            mediaRecorder = new MediaRecorder();
            mediaRecorder.setOutputFile(ficheroAudio);
            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
            try {
                mediaRecorder.prepare();
            } catch (IOException e) {
            }
            mediaRecorder.start();
            handler.post(new Runnable() {
                @Override
                public void run() {
                    finalTime += 1000;
                    int seconds = (int) (finalTime / 1000) % 60;
                    int minutes = (int) ((finalTime / (1000 * 60)) % 60);
                    int hours = (int) ((finalTime / (1000 * 60 * 60)) % 24);
                    timeFinal = String.format("%02d", minutes) + ":" + String.format("%02d", seconds);
                    timerAudio.setText(timeFinal);
                    if (!saveAudio) {
                        textRecording.setText(timeFinal);
                    }
                    handler.postDelayed(this, 1000);
                }
            });
            scaleAnimX = ObjectAnimator.ofFloat(recordAudioButton, "scaleX", 1, 1.2f);
            scaleAnimX.setDuration(800);
            scaleAnimX.setRepeatCount(ValueAnimator.INFINITE);
            scaleAnimX.setRepeatMode(ValueAnimator.REVERSE);
            scaleAnimY = ObjectAnimator.ofFloat(recordAudioButton, "scaleY", 1, 1.2f);
            scaleAnimY.setDuration(800);
            scaleAnimY.setRepeatCount(ValueAnimator.INFINITE);
            scaleAnimY.setRepeatMode(ValueAnimator.REVERSE);
            scaleAnimY.start();
            scaleAnimX.start();

            scaleRedBackgroundX = ObjectAnimator.ofFloat(audioRecordBackground, "scaleX", 1, 100f);
            scaleRedBackgroundX.setDuration(200);
            scaleRedBackgroundY = ObjectAnimator.ofFloat(audioRecordBackground, "scaleY", 1, 100f);
            scaleRedBackgroundY.setDuration(200);
            saveAudio = true;
            break;

        case MotionEvent.ACTION_MOVE:
            if (!rect.contains(v.getLeft() + (int) event.getX(), v.getTop() + (int) event.getY())) {
                recordAudioButton.setBackgroundResource(R.drawable.rounded_record_audio_white);
                timerAudio.setVisibility(View.GONE);
                textRecording.setTextColor(getResources().getColor(R.color.speak_all_red));
                if (!animatorBackground) {
                    textRecording.setText(timeFinal);
                    if (scaleRedBackgroundX.isRunning())
                        scaleRedBackgroundX.end();
                    if (scaleRedBackgroundY.isRunning())
                        scaleRedBackgroundY.end();
                    scaleRedBackgroundY.start();
                    scaleRedBackgroundX.start();
                    animatorBackground = true;
                }
                saveAudio = false;
            } else {
                recordAudioButton.setBackgroundResource(R.drawable.rounded_record_audio_red);
                textRecording.setTextColor(getResources().getColor(R.color.speak_all_white));
                textRecording.setText(getString(R.string.audio_record));
                timerAudio.setVisibility(View.VISIBLE);
                if (animatorBackground) {
                    if (scaleRedBackgroundX.isRunning())
                        scaleRedBackgroundX.end();
                    if (scaleRedBackgroundY.isRunning())
                        scaleRedBackgroundY.end();
                    ViewHelper.setScaleX(audioRecordBackground, 1);
                    ViewHelper.setScaleY(audioRecordBackground, 1);
                    animatorBackground = false;
                }
                saveAudio = true;
            }
            break;
        case MotionEvent.ACTION_UP:
            textRecordingPress.setVisibility(View.VISIBLE);
            animatorBackground = false;
            if (scaleAnimY.isRunning())
                scaleAnimY.end();
            if (scaleAnimX.isRunning())
                scaleAnimX.end();
            if (scaleRedBackgroundX.isRunning())
                scaleRedBackgroundX.end();
            if (scaleRedBackgroundY.isRunning())
                scaleRedBackgroundY.end();
            ViewHelper.setScaleX(audioRecordBackground, 1);
            ViewHelper.setScaleY(audioRecordBackground, 1);
            ViewHelper.setScaleX(recordAudioButton, 1);
            ViewHelper.setScaleY(recordAudioButton, 1);
            handler.removeCallbacksAndMessages(null);
            timerAudio.setText("00:00");
            timerAudio.setVisibility(View.VISIBLE);
            textRecording.setTextColor(getResources().getColor(R.color.speak_all_white));
            textRecording.setText(getString(R.string.audio_record));
            recordAudioButton.setBackgroundResource(R.drawable.rounded_record_audio_red);
            if (finalTime > 1000) {
                mediaRecorder.stop();
                mediaRecorder.release();
            } else {
                saveAudio = false;
                mediaRecorder.release();
            }
            finalTime = 0;
            timeFinal = "";
            if (saveAudio) {
                try {
                    hideKeyBoard();
                    final Message msjAudio = new Message();
                    String id = u.id + contact.idContacto + fechaAudioMillis + Settings.Secure
                            .getString(activity.getContentResolver(), Settings.Secure.ANDROID_ID);
                    msjAudio.mensajeId = id;
                    msjAudio.emisor = u.id;
                    msjAudio.receptor = contact.idContacto;
                    msjAudio.emisorEmail = u.email;
                    msjAudio.receptorEmail = contact.email;
                    msjAudio.emisorLang = u.lang;
                    msjAudio.receptorLang = contact.lang;
                    msjAudio.emitedAt = fechaAudioMillis;
                    msjAudio.tipo = Integer.parseInt(getString(R.string.MSG_TYPE_AUDIO));
                    if (SpeakSocket.mSocket != null)
                        if (SpeakSocket.mSocket.connected()) {
                            msjAudio.status = 1;
                        } else {
                            msjAudio.status = -1;
                        }
                    msjAudio.fileUploaded = false;
                    msjAudio.audioName = ficheroAudio;
                    msjAudio.save();
                    Chats chat = new Select().from(Chats.class).where("idContacto = ?", msjAudio.receptor)
                            .executeSingle();
                    if (chat == null) {
                        Contact contact = new Select().from(Contact.class)
                                .where("id_contact = ?", msjAudio.receptor).executeSingle();
                        Chats newChat = new Chats();
                        newChat.mensajeId = msjAudio.mensajeId;
                        newChat.idContacto = msjAudio.receptor;
                        newChat.isLockedConversation = false;
                        newChat.lastStatus = msjAudio.status;
                        newChat.email = msjAudio.receptorEmail;
                        if (contact != null) {
                            newChat.photo = contact.photo;
                            newChat.fullName = contact.fullName;
                            newChat.lang = contact.lang;
                            newChat.screenName = contact.screenName;
                            newChat.photoload = true;
                            newChat.phone = contact.phone;
                        } else {
                            newChat.photo = null;
                            newChat.photoload = false;
                            newChat.fullName = msjAudio.receptorEmail;
                            newChat.lang = msjAudio.receptorLang;
                            newChat.screenName = msjAudio.receptorEmail;
                            newChat.phone = null;
                        }
                        newChat.emitedAt = msjAudio.emitedAt;
                        newChat.notRead = 0;
                        newChat.lastMessage = "send Audio";
                        newChat.show = true;
                        newChat.save();
                    } else {
                        if (!chat.photoload) {
                            Contact contact = new Select().from(Contact.class)
                                    .where("id_contact = ?", msjAudio.emisor).executeSingle();
                            if (contact != null) {
                                chat.photo = contact.photo;
                                chat.photoload = true;
                            } else {
                                chat.photo = null;
                                chat.photoload = false;
                            }
                        }
                        chat.mensajeId = msjAudio.mensajeId;
                        chat.lastStatus = msjAudio.status;
                        chat.emitedAt = msjAudio.emitedAt;
                        chat.notRead = 0;
                        chat.lastMessage = "send Audio";
                        chat.save();
                    }
                    showNewMessage(msjAudio);

                } catch (Exception e) {
                    // TODO: handle exception
                }
            } else {
                new File(ficheroAudio).delete();
            }
            break;
        }
        break;
    }

    return true;
}

From source file:com.appunite.list.AbsListView.java

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    int action = ev.getAction();
    View v;

    if (mPositionScroller != null) {
        mPositionScroller.stop();//from   www.  j a  v a2 s  . com
    }

    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;
    }

    if (mFastScroller != null) {
        boolean intercepted = mFastScroller.onInterceptTouchEvent(ev);
        if (intercepted) {
            return true;
        }
    }

    switch (action & MotionEvent.ACTION_MASK) {
    case MotionEvent.ACTION_DOWN: {
        int touchMode = mTouchMode;
        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_FLING && motionPosition >= 0) {
            // User clicked on an actual view (and was not stopping a fling).
            // Remember where the motion event started
            v = getChildAt(motionPosition - mFirstPosition);
            mMotionViewOriginalTop = v.getTop();
            mMotionX = x;
            mMotionY = y;
            mMotionPosition = motionPosition;
            mTouchMode = TOUCH_MODE_DOWN;
            clearScrollingCache();
        }
        mLastY = Integer.MIN_VALUE;
        initOrResetVelocityTracker();
        mVelocityTracker.addMovement(ev);
        if (touchMode == TOUCH_MODE_FLING) {
            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_REST;
        mActivePointerId = INVALID_POINTER;
        recycleVelocityTracker();
        reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE);
        break;
    }

    case MotionEvent.ACTION_POINTER_UP: {
        onSecondaryPointerUp(ev);
        break;
    }
    }

    return false;
}