Example usage for android.view View getLeft

List of usage examples for android.view View getLeft

Introduction

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

Prototype

@ViewDebug.CapturedViewProperty
public final int getLeft() 

Source Link

Document

Left position of this view relative to its parent.

Usage

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  a  2  s  . 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 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.AbsHorizontalListView.java

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

    if (mPositionScroller != null) {
        mPositionScroller.stop();//w w  w. j  av  a2s .  c  om
    }

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

    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 = findMotionCol(x);
        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);
            mMotionViewOriginalLeft = v.getLeft();
            mMotionX = x;
            mMotionY = y;
            mMotionPosition = motionPosition;
            mTouchMode = TOUCH_MODE_DOWN;
            clearScrollingCache();
        }
        mLastX = 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 x = (int) ev.getX(pointerIndex);
            initVelocityTrackerIfNotExists();
            mVelocityTracker.addMovement(ev);
            if (startScrollIfNeeded(x)) {
                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;
}

From source file:android.support.v7.widget.RecyclerViewEx.java

/**
 * Find the topmost view under the given point.
 *
 * @param x Horizontal position in pixels to search
 * @param y Vertical position in pixels to search
 * @return The child view under (x, y) or null if no matching child is found
 *///w w w. ja v a2 s.  co  m
public View findChildViewUnder(float x, float y) {
    final int count = mChildHelper.getChildCount();
    for (int i = count - 1; i >= 0; i--) {
        final View child = mChildHelper.getChildAt(i);
        final float translationX = ViewCompat.getTranslationX(child);
        final float translationY = ViewCompat.getTranslationY(child);
        if (x >= child.getLeft() + translationX && x <= child.getRight() + translationX
                && y >= child.getTop() + translationY && y <= child.getBottom() + translationY) {
            return child;
        }
    }
    return null;
}

From source file:android.support.v7.widget.RecyclerViewEx.java

private void animateDisappearance(ItemHolderInfo disappearingItem) {
    View disappearingItemView = disappearingItem.holder.itemView;
    addAnimatingView(disappearingItem.holder);
    int oldLeft = disappearingItem.left;
    int oldTop = disappearingItem.top;
    int newLeft = disappearingItemView.getLeft();
    int newTop = disappearingItemView.getTop();
    if (oldLeft != newLeft || oldTop != newTop) {
        disappearingItem.holder.setIsRecyclable(false);
        disappearingItemView.layout(newLeft, newTop, newLeft + disappearingItemView.getWidth(),
                newTop + disappearingItemView.getHeight());
        if (DEBUG) {
            Log.d(TAG, "DISAPPEARING: " + disappearingItem.holder + " with view " + disappearingItemView);
        }//from  ww w . j av  a  2s .c  o  m
        if (mItemAnimator.animateMove(disappearingItem.holder, oldLeft, oldTop, newLeft, newTop)) {
            postAnimationRunner();
        }
    } else {
        if (DEBUG) {
            Log.d(TAG, "REMOVED: " + disappearingItem.holder + " with view " + disappearingItemView);
        }
        disappearingItem.holder.setIsRecyclable(false);
        if (mItemAnimator.animateRemove(disappearingItem.holder)) {
            postAnimationRunner();
        }
    }
}

From source file:android.support.v7.widget.RecyclerViewEx.java

/**
 * Wrapper around layoutChildren() that handles animating changes caused by layout.
 * Animations work on the assumption that there are five different kinds of items
 * in play:/*from   w ww.j  a v  a 2  s.  c om*/
 * PERSISTENT: items are visible before and after layout
 * REMOVED: items were visible before layout and were removed by the app
 * ADDED: items did not exist before layout and were added by the app
 * DISAPPEARING: items exist in the data set before/after, but changed from
 * visible to non-visible in the process of layout (they were moved off
 * screen as a side-effect of other changes)
 * APPEARING: items exist in the data set before/after, but changed from
 * non-visible to visible in the process of layout (they were moved on
 * screen as a side-effect of other changes)
 * The overall approach figures out what items exist before/after layout and
 * infers one of the five above states for each of the items. Then the animations
 * are set up accordingly:
 * PERSISTENT views are moved ({@link android.support.v7.widget.RecyclerViewEx.ItemAnimator#animateMove(android.support.v7.widget.RecyclerViewEx.ViewHolder, int, int, int, int)})
 * REMOVED views are removed ({@link android.support.v7.widget.RecyclerViewEx.ItemAnimator#animateRemove(android.support.v7.widget.RecyclerViewEx.ViewHolder)})
 * ADDED views are added ({@link android.support.v7.widget.RecyclerViewEx.ItemAnimator#animateAdd(android.support.v7.widget.RecyclerViewEx.ViewHolder)})
 * DISAPPEARING views are moved off screen
 * APPEARING views are moved on screen
 */
void dispatchLayout() {
    if (mAdapter == null) {
        Log.e(TAG, "No adapter attached; skipping layout");
        return;
    }
    mDisappearingViewsInLayoutPass.clear();
    eatRequestLayout();
    mRunningLayoutOrScroll = true;

    processAdapterUpdatesAndSetAnimationFlags();

    mState.mOldChangedHolders = mState.mRunSimpleAnimations && mItemsChanged && supportsChangeAnimations()
            ? new ArrayMap<Long, ViewHolder>()
            : null;
    mItemsAddedOrRemoved = mItemsChanged = false;
    ArrayMap<View, Rect> appearingViewInitialBounds = null;
    mState.mInPreLayout = mState.mRunPredictiveAnimations;
    mState.mItemCount = mAdapter.getItemCount();

    if (mState.mRunSimpleAnimations) {
        // Step 0: Find out where all non-removed items are, pre-layout
        mState.mPreLayoutHolderMap.clear();
        mState.mPostLayoutHolderMap.clear();
        int count = mChildHelper.getChildCount();
        for (int i = 0; i < count; ++i) {
            final ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i));
            if (holder.shouldIgnore() || (holder.isInvalid() && !mAdapter.hasStableIds())) {
                continue;
            }
            final View view = holder.itemView;
            mState.mPreLayoutHolderMap.put(holder, new ItemHolderInfo(holder, view.getLeft(), view.getTop(),
                    view.getRight(), view.getBottom()));
        }
    }
    if (mState.mRunPredictiveAnimations) {
        // Step 1: run prelayout: This will use the old positions of items. The layout manager
        // is expected to layout everything, even removed items (though not to add removed
        // items back to the container). This gives the pre-layout position of APPEARING views
        // which come into existence as part of the real layout.

        // Save old positions so that LayoutManager can run its mapping logic.
        saveOldPositions();
        // processAdapterUpdatesAndSetAnimationFlags already run pre-layout animations.
        if (mState.mOldChangedHolders != null) {
            int count = mChildHelper.getChildCount();
            for (int i = 0; i < count; ++i) {
                final ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i));
                if (holder.isChanged() && !holder.isRemoved() && !holder.shouldIgnore()) {
                    long key = getChangedHolderKey(holder);
                    mState.mOldChangedHolders.put(key, holder);
                    mState.mPreLayoutHolderMap.remove(holder);
                }
            }
        }

        final boolean didStructureChange = mState.mStructureChanged;
        mState.mStructureChanged = false;
        // temporarily disable flag because we are asking for previous layout
        mLayout.onLayoutChildren(mRecycler, mState);
        mState.mStructureChanged = didStructureChange;

        appearingViewInitialBounds = new ArrayMap<View, Rect>();
        for (int i = 0; i < mChildHelper.getChildCount(); ++i) {
            boolean found = false;
            View child = mChildHelper.getChildAt(i);
            if (getChildViewHolderInt(child).shouldIgnore()) {
                continue;
            }
            for (int j = 0; j < mState.mPreLayoutHolderMap.size(); ++j) {
                ViewHolder holder = mState.mPreLayoutHolderMap.keyAt(j);
                if (holder.itemView == child) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                appearingViewInitialBounds.put(child,
                        new Rect(child.getLeft(), child.getTop(), child.getRight(), child.getBottom()));
            }
        }
        // we don't process disappearing list because they may re-appear in post layout pass.
        clearOldPositions();
        mAdapterHelper.consumePostponedUpdates();
    } else {
        clearOldPositions();
        // in case pre layout did run but we decided not to run predictive animations.
        mAdapterHelper.consumeUpdatesInOnePass();
        if (mState.mOldChangedHolders != null) {
            int count = mChildHelper.getChildCount();
            for (int i = 0; i < count; ++i) {
                final ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i));
                if (holder.isChanged() && !holder.isRemoved() && !holder.shouldIgnore()) {
                    long key = getChangedHolderKey(holder);
                    mState.mOldChangedHolders.put(key, holder);
                    mState.mPreLayoutHolderMap.remove(holder);
                }
            }
        }
    }
    mState.mItemCount = mAdapter.getItemCount();
    mState.mDeletedInvisibleItemCountSincePreviousLayout = 0;

    // Step 2: Run layout
    mState.mInPreLayout = false;
    mLayout.onLayoutChildren(mRecycler, mState);

    mState.mStructureChanged = false;
    mPendingSavedState = null;

    // onLayoutChildren may have caused client code to disable item animations; re-check
    mState.mRunSimpleAnimations = mState.mRunSimpleAnimations && mItemAnimator != null;

    if (mState.mRunSimpleAnimations) {
        // Step 3: Find out where things are now, post-layout
        ArrayMap<Long, ViewHolder> newChangedHolders = mState.mOldChangedHolders != null
                ? new ArrayMap<Long, ViewHolder>()
                : null;
        int count = mChildHelper.getChildCount();
        for (int i = 0; i < count; ++i) {
            ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i));
            if (holder.shouldIgnore()) {
                continue;
            }
            final View view = holder.itemView;
            long key = getChangedHolderKey(holder);
            if (newChangedHolders != null && mState.mOldChangedHolders.get(key) != null) {
                newChangedHolders.put(key, holder);
            } else {
                mState.mPostLayoutHolderMap.put(holder, new ItemHolderInfo(holder, view.getLeft(),
                        view.getTop(), view.getRight(), view.getBottom()));
            }
        }
        processDisappearingList(appearingViewInitialBounds);
        // Step 4: Animate DISAPPEARING and REMOVED items
        int preLayoutCount = mState.mPreLayoutHolderMap.size();
        for (int i = preLayoutCount - 1; i >= 0; i--) {
            ViewHolder itemHolder = mState.mPreLayoutHolderMap.keyAt(i);
            if (!mState.mPostLayoutHolderMap.containsKey(itemHolder)) {
                ItemHolderInfo disappearingItem = mState.mPreLayoutHolderMap.valueAt(i);
                mState.mPreLayoutHolderMap.removeAt(i);

                View disappearingItemView = disappearingItem.holder.itemView;
                mRecycler.unscrapView(disappearingItem.holder);
                animateDisappearance(disappearingItem);
            }
        }
        // Step 5: Animate APPEARING and ADDED items
        int postLayoutCount = mState.mPostLayoutHolderMap.size();
        if (postLayoutCount > 0) {
            for (int i = postLayoutCount - 1; i >= 0; i--) {
                ViewHolder itemHolder = mState.mPostLayoutHolderMap.keyAt(i);
                ItemHolderInfo info = mState.mPostLayoutHolderMap.valueAt(i);
                if ((mState.mPreLayoutHolderMap.isEmpty()
                        || !mState.mPreLayoutHolderMap.containsKey(itemHolder))) {
                    mState.mPostLayoutHolderMap.removeAt(i);
                    Rect initialBounds = (appearingViewInitialBounds != null)
                            ? appearingViewInitialBounds.get(itemHolder.itemView)
                            : null;
                    animateAppearance(itemHolder, initialBounds, info.left, info.top);
                }
            }
        }
        // Step 6: Animate PERSISTENT items
        count = mState.mPostLayoutHolderMap.size();
        for (int i = 0; i < count; ++i) {
            ViewHolder postHolder = mState.mPostLayoutHolderMap.keyAt(i);
            ItemHolderInfo postInfo = mState.mPostLayoutHolderMap.valueAt(i);
            ItemHolderInfo preInfo = mState.mPreLayoutHolderMap.get(postHolder);
            if (preInfo != null && postInfo != null) {
                if (preInfo.left != postInfo.left || preInfo.top != postInfo.top) {
                    postHolder.setIsRecyclable(false);
                    if (DEBUG) {
                        Log.d(TAG, "PERSISTENT: " + postHolder + " with view " + postHolder.itemView);
                    }
                    if (mItemAnimator.animateMove(postHolder, preInfo.left, preInfo.top, postInfo.left,
                            postInfo.top)) {
                        postAnimationRunner();
                    }
                }
            }
        }
        // Step 7: Animate CHANGING items
        count = mState.mOldChangedHolders != null ? mState.mOldChangedHolders.size() : 0;
        // traverse reverse in case view gets recycled while we are traversing the list.
        for (int i = count - 1; i >= 0; i--) {
            long key = mState.mOldChangedHolders.keyAt(i);
            ViewHolder oldHolder = mState.mOldChangedHolders.get(key);
            View oldView = oldHolder.itemView;
            if (oldHolder.shouldIgnore()) {
                continue;
            }
            // We probably don't need this check anymore since these views are removed from
            // the list if they are recycled.
            if (mRecycler.mChangedScrap != null && mRecycler.mChangedScrap.contains(oldHolder)) {
                animateChange(oldHolder, newChangedHolders.get(key));
            } else if (DEBUG) {
                Log.e(TAG, "cannot find old changed holder in changed scrap :/" + oldHolder);
            }
        }
    }
    resumeRequestLayout(false);
    mLayout.removeAndRecycleScrapInt(mRecycler);
    mState.mPreviousLayoutItemCount = mState.mItemCount;
    mDataSetHasChangedAfterLayout = false;
    mState.mRunSimpleAnimations = false;
    mState.mRunPredictiveAnimations = false;
    mRunningLayoutOrScroll = false;
    mLayout.mRequestedSimpleAnimations = false;
    if (mRecycler.mChangedScrap != null) {
        mRecycler.mChangedScrap.clear();
    }
    mState.mOldChangedHolders = null;
}

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

@TargetApi(11)
private void setupChild(View child, int position, int top, int left, boolean flow, boolean selected,
        boolean recycled) {
    final boolean isSelected = selected && shouldShowSelector();
    final boolean updateChildSelected = isSelected != child.isSelected();
    final int touchMode = mTouchMode;

    final boolean isPressed = touchMode > TOUCH_MODE_DOWN && touchMode < TOUCH_MODE_DRAGGING
            && mMotionPosition == position;

    final boolean updateChildPressed = isPressed != child.isPressed();
    final boolean needToMeasure = !recycled || updateChildSelected || child.isLayoutRequested();

    // Respect layout params that are already in the view. Otherwise make some up...
    LayoutParams lp = (LayoutParams) child.getLayoutParams();
    if (lp == null) {
        lp = generateDefaultLayoutParams();
    }/*from  ww  w .  j a  v a2 s.  c o  m*/

    lp.viewType = mAdapter.getItemViewType(position);

    if (recycled && !lp.forceAdd) {
        attachViewToParent(child, (flow ? -1 : 0), lp);
    } else {
        lp.forceAdd = false;
        addViewInLayout(child, (flow ? -1 : 0), lp, true);
    }

    if (updateChildSelected) {
        child.setSelected(isSelected);
    }

    if (updateChildPressed) {
        child.setPressed(isPressed);
    }

    if (mChoiceMode.compareTo(ChoiceMode.NONE) != 0 && mCheckStates != null) {
        if (child instanceof Checkable) {
            ((Checkable) child).setChecked(mCheckStates.get(position));
        } else if (getContext().getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.HONEYCOMB) {
            child.setActivated(mCheckStates.get(position));
        }
    }

    if (needToMeasure) {
        measureChild(child, lp);
    } else {
        cleanupLayoutState(child);
    }

    final int w = child.getMeasuredWidth();
    final int h = child.getMeasuredHeight();

    final int childTop = (mIsVertical && !flow ? top - h : top);
    final int childLeft = (!mIsVertical && !flow ? left - w : left);

    if (needToMeasure) {
        final int childRight = childLeft + w;
        final int childBottom = childTop + h;

        child.layout(childLeft, childTop, childRight, childBottom);
    } else {
        child.offsetLeftAndRight(childLeft - child.getLeft());
        child.offsetTopAndBottom(childTop - child.getTop());
    }
}

From source file:android.support.v7.widget.RecyclerViewEx.java

/**
 * Does not perform bounds checking. Used by internal methods that have already validated input.
 *//*  ww  w .java  2s . c  o m*/
void scrollByInternal(int x, int y) {
    int overscrollX = 0, overscrollY = 0;
    int hresult = 0, vresult = 0;
    consumePendingUpdateOperations();
    if (mAdapter != null) {
        eatRequestLayout();
        mRunningLayoutOrScroll = true;
        if (x != 0) {
            hresult = mLayout.scrollHorizontallyBy(x, mRecycler, mState);
            overscrollX = x - hresult;
        }
        if (y != 0) {
            vresult = mLayout.scrollVerticallyBy(y, mRecycler, mState);
            overscrollY = y - vresult;
        }
        if (supportsChangeAnimations()) {
            // Fix up shadow views used by changing animations
            int count = mChildHelper.getChildCount();
            for (int i = 0; i < count; i++) {
                View view = mChildHelper.getChildAt(i);
                ViewHolder holder = getChildViewHolder(view);
                if (holder != null && holder.mShadowingHolder != null) {
                    ViewHolder shadowingHolder = holder.mShadowingHolder;
                    View shadowingView = shadowingHolder != null ? shadowingHolder.itemView : null;
                    if (shadowingView != null) {
                        int left = view.getLeft();
                        int top = view.getTop();
                        if (left != shadowingView.getLeft() || top != shadowingView.getTop()) {
                            shadowingView.layout(left, top, left + shadowingView.getWidth(),
                                    top + shadowingView.getHeight());
                        }
                    }
                }
            }
        }
        mRunningLayoutOrScroll = false;
        resumeRequestLayout(false);
    }
    if (!mItemDecorations.isEmpty()) {
        invalidate();
    }
    if (ViewCompat.getOverScrollMode(this) != ViewCompat.OVER_SCROLL_NEVER) {
        considerReleasingGlowsOnScroll(x, y);
        pullGlows(overscrollX, overscrollY);
    }
    if (hresult != 0 || vresult != 0) {
        onScrollChanged(0, 0, 0, 0); // dummy values, View's implementation does not use these.
        if (mScrollListener != null) {
            mScrollListener.onScrolled(this, hresult, vresult);
        }
    }
    if (!awakenScrollBars()) {
        invalidate();
    }
}

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

@TargetApi(11)
private void setupChild(View child, int position, int top, int left, boolean flow, boolean selected,
        boolean recycled) {
    final boolean isSelected = selected && shouldShowSelector();
    final boolean updateChildSelected = isSelected != child.isSelected();
    final int touchMode = mTouchMode;

    final boolean isPressed = touchMode > TOUCH_MODE_DOWN && touchMode < TOUCH_MODE_DRAGGING
            && mMotionPosition == position;

    final boolean updateChildPressed = isPressed != child.isPressed();
    final boolean needToMeasure = !recycled || updateChildSelected || child.isLayoutRequested();

    // Respect layout params that are already in the view. Otherwise make
    // some up...
    LayoutParams lp = (LayoutParams) child.getLayoutParams();
    if (lp == null) {
        lp = generateDefaultLayoutParams();
    }//from  w  ww . j av  a 2s . co  m

    lp.viewType = mAdapter.getItemViewType(position);

    if (recycled && !lp.forceAdd) {
        attachViewToParent(child, (flow ? -1 : 0), lp);
    } else {
        lp.forceAdd = false;
        addViewInLayout(child, (flow ? -1 : 0), lp, true);
    }

    if (updateChildSelected) {
        child.setSelected(isSelected);
    }

    if (updateChildPressed) {
        child.setPressed(isPressed);
    }

    if (mChoiceMode.compareTo(ChoiceMode.NONE) != 0 && mCheckStates != null) {
        if (child instanceof Checkable) {
            ((Checkable) child).setChecked(mCheckStates.get(position));
        } else if (getContext().getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.HONEYCOMB) {
            child.setActivated(mCheckStates.get(position));
        }
    }

    if (needToMeasure) {
        measureChild(child, lp);
    } else {
        cleanupLayoutState(child);
    }

    final int w = child.getMeasuredWidth();
    final int h = child.getMeasuredHeight();

    final int childTop = (mIsVertical && !flow ? top - h : top);
    final int childLeft = (!mIsVertical && !flow ? left - w : left);

    if (needToMeasure) {
        final int childRight = childLeft + w;
        final int childBottom = childTop + h;

        child.layout(childLeft, childTop, childRight, childBottom);
    } else {
        child.offsetLeftAndRight(childLeft - child.getLeft());
        child.offsetTopAndBottom(childTop - child.getTop());
    }
}

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

@Override
public boolean onTouchEvent(MotionEvent ev) {
    if (!isEnabled()) {
        // A disabled view that is clickable still consumes the touch
        // events, it just doesn't respond to them.
        return isClickable() || isLongClickable();
    }/*from   w  w w.  jav a2 s.  co m*/

    if (mPositionScroller != null) {
        mPositionScroller.stop();
    }

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

    final int action = ev.getAction();

    View v;

    initVelocityTrackerIfNotExists();
    mVelocityTracker.addMovement(ev);

    switch (action & MotionEvent.ACTION_MASK) {
    case MotionEvent.ACTION_DOWN: {
        switch (mTouchMode) {
        case TOUCH_MODE_OVERFLING: {
            mFlingRunnable.endFling();
            if (mPositionScroller != null) {
                mPositionScroller.stop();
            }
            mTouchMode = TOUCH_MODE_OVERSCROLL;
            mMotionX = mLastX = (int) ev.getX();
            mMotionY = (int) ev.getY();
            mMotionCorrection = 0;
            mActivePointerId = ev.getPointerId(0);
            mDirection = 0;
            break;
        }

        default: {
            mActivePointerId = ev.getPointerId(0);
            final int x = (int) ev.getX();
            final int y = (int) ev.getY();
            int motionPosition = pointToPosition(x, y);
            if (!mDataChanged) {
                if ((mTouchMode != TOUCH_MODE_FLING) && (motionPosition >= 0)
                        && (getAdapter().isEnabled(motionPosition))) {
                    // User clicked on an actual view (and was not stopping a fling).
                    // It might be a click or a scroll. Assume it is a click until
                    // proven otherwise
                    mTouchMode = TOUCH_MODE_DOWN;
                    // FIXME Debounce
                    if (mPendingCheckForTap == null) {
                        mPendingCheckForTap = new CheckForTap();
                    }
                    postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
                } else {
                    if (mTouchMode == TOUCH_MODE_FLING) {
                        // Stopped a fling. It is a scroll.
                        createScrollingCache();
                        mTouchMode = TOUCH_MODE_SCROLL;
                        mMotionCorrection = 0;
                        motionPosition = findMotionCol(x);
                        mFlingRunnable.flywheelTouch();
                    }
                }
            }

            if (motionPosition >= 0) {
                // Remember where the motion event started
                v = getChildAt(motionPosition - mFirstPosition);
                mMotionViewOriginalLeft = v.getLeft();
            }
            mMotionX = x;
            mMotionY = y;
            mMotionPosition = motionPosition;
            mLastX = Integer.MIN_VALUE;
            break;
        }
        }

        if (performButtonActionOnTouchDownUnhide(ev)) {
            if (mTouchMode == TOUCH_MODE_DOWN) {
                removeCallbacks(mPendingCheckForTap);
            }
        }
        break;
    }

    case MotionEvent.ACTION_MOVE: {
        int pointerIndex = ev.findPointerIndex(mActivePointerId);
        if (pointerIndex == -1) {
            pointerIndex = 0;
            mActivePointerId = ev.getPointerId(pointerIndex);
        }
        final int x = (int) ev.getX(pointerIndex);

        if (mDataChanged) {
            // Re-sync everything if data has been changed
            // since the scroll operation can query the adapter.
            layoutChildren();
        }

        switch (mTouchMode) {
        case TOUCH_MODE_DOWN:
        case TOUCH_MODE_TAP:
        case TOUCH_MODE_DONE_WAITING:
            // Check if we have moved far enough that it looks more like a
            // scroll than a tap
            startScrollIfNeeded(x);
            break;
        case TOUCH_MODE_SCROLL:
        case TOUCH_MODE_OVERSCROLL:
            scrollIfNeeded(x);
            break;
        }
        break;
    }

    case MotionEvent.ACTION_UP: {
        switch (mTouchMode) {
        case TOUCH_MODE_DOWN:
        case TOUCH_MODE_TAP:
        case TOUCH_MODE_DONE_WAITING:
            final int motionPosition = mMotionPosition;
            final View child = getChildAt(motionPosition - mFirstPosition);

            final float y = ev.getY();
            final boolean inList = y > mListPadding.top && y < getHeight() - mListPadding.bottom;

            if (child != null && !child.hasFocusable() && inList) {
                if (mTouchMode != TOUCH_MODE_DOWN) {
                    child.setPressed(false);
                }

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

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

                mResurrectToPosition = motionPosition;

                if (mTouchMode == TOUCH_MODE_DOWN || mTouchMode == TOUCH_MODE_TAP) {
                    final Handler handler = getHandler();
                    if (handler != null) {
                        handler.removeCallbacks(mTouchMode == TOUCH_MODE_DOWN ? mPendingCheckForTap
                                : mPendingCheckForLongPress);
                    }
                    mLayoutMode = LAYOUT_NORMAL;
                    if (!mDataChanged && mAdapter.isEnabled(motionPosition)) {
                        mTouchMode = TOUCH_MODE_TAP;
                        setSelectedPositionInt(mMotionPosition);
                        layoutChildren();
                        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() {
                                mTouchModeReset = null;
                                mTouchMode = TOUCH_MODE_REST;
                                child.setPressed(false);
                                setPressed(false);
                                if (!mDataChanged) {
                                    performClick.run();
                                }
                            }
                        };
                        postDelayed(mTouchModeReset, ViewConfiguration.getPressedStateDuration());
                    } else {
                        mTouchMode = TOUCH_MODE_REST;
                        updateSelectorState();
                    }
                    return true;
                } else if (!mDataChanged && mAdapter.isEnabled(motionPosition)) {
                    performClick.run();
                }
            }
            mTouchMode = TOUCH_MODE_REST;
            updateSelectorState();
            break;
        case TOUCH_MODE_SCROLL:
            final int childCount = getChildCount();
            if (childCount > 0) {
                final int firstChildLeft = getChildAt(0).getLeft();
                final int lastChildRight = getChildAt(childCount - 1).getRight();
                final int contentLeft = mListPadding.left;
                final int contentRight = getWidth() - mListPadding.right;
                if (mFirstPosition == 0 && firstChildLeft >= contentLeft
                        && mFirstPosition + childCount < mItemCount
                        && lastChildRight <= getWidth() - contentRight) {
                    mTouchMode = TOUCH_MODE_REST;
                    reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE);
                } else {
                    final VelocityTracker velocityTracker = mVelocityTracker;
                    velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);

                    final int initialVelocity = (int) (velocityTracker.getXVelocity(mActivePointerId)
                            * mVelocityScale);
                    // Fling if we have enough velocity and we aren't at a boundary.
                    // Since we can potentially overfling more than we can overscroll, don't
                    // allow the weird behavior where you can scroll to a boundary then
                    // fling further.
                    if (Math.abs(initialVelocity) > mMinimumVelocity
                            && !((mFirstPosition == 0 && firstChildLeft == contentLeft - mOverscrollDistance)
                                    || (mFirstPosition + childCount == mItemCount
                                            && lastChildRight == contentRight + mOverscrollDistance))) {
                        if (mFlingRunnable == null) {
                            mFlingRunnable = new FlingRunnable();
                        }
                        reportScrollStateChange(OnScrollListener.SCROLL_STATE_FLING);

                        mFlingRunnable.start(-initialVelocity);
                    } else {
                        mTouchMode = TOUCH_MODE_REST;
                        reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE);
                        if (mFlingRunnable != null) {
                            mFlingRunnable.endFling();
                        }
                        if (mPositionScroller != null) {
                            mPositionScroller.stop();
                        }
                    }
                }
            } else {
                mTouchMode = TOUCH_MODE_REST;
                reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE);
            }
            break;

        case TOUCH_MODE_OVERSCROLL:
            if (mFlingRunnable == null) {
                mFlingRunnable = new FlingRunnable();
            }
            final VelocityTracker velocityTracker = mVelocityTracker;
            velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
            final int initialVelocity = (int) velocityTracker.getXVelocity(mActivePointerId);

            reportScrollStateChange(OnScrollListener.SCROLL_STATE_FLING);
            if (Math.abs(initialVelocity) > mMinimumVelocity) {
                mFlingRunnable.startOverfling(-initialVelocity);
            } else {
                mFlingRunnable.startSpringback();
            }

            break;
        }

        setPressed(false);

        if (mEdgeGlowLeft != null) {
            mEdgeGlowLeft.onRelease();
            mEdgeGlowRight.onRelease();
        }

        // Need to redraw since we probably aren't drawing the selector anymore
        invalidate();

        final Handler handler = getHandler();
        if (handler != null) {
            handler.removeCallbacks(mPendingCheckForLongPress);
        }

        recycleVelocityTracker();

        mActivePointerId = INVALID_POINTER;

        if (PROFILE_SCROLLING) {
            if (mScrollProfilingStarted) {
                Debug.stopMethodTracing();
                mScrollProfilingStarted = false;
            }
        }

        // FIXME not needed bacaues we could not implement strict span (j.m.)
        //            if (mScrollStrictSpan != null) {
        //                mScrollStrictSpan.finish();
        //                mScrollStrictSpan = null;
        //            }
        break;
    }

    case MotionEvent.ACTION_CANCEL: {
        switch (mTouchMode) {
        case TOUCH_MODE_OVERSCROLL:
            if (mFlingRunnable == null) {
                mFlingRunnable = new FlingRunnable();
            }
            mFlingRunnable.startSpringback();
            break;

        case TOUCH_MODE_OVERFLING:
            // Do nothing - let it play out.
            break;

        default:
            mTouchMode = TOUCH_MODE_REST;
            setPressed(false);
            View motionView = this.getChildAt(mMotionPosition - mFirstPosition);
            if (motionView != null) {
                motionView.setPressed(false);
            }
            clearScrollingCache();

            final Handler handler = getHandler();
            if (handler != null) {
                handler.removeCallbacks(mPendingCheckForLongPress);
            }

            recycleVelocityTracker();
        }

        if (mEdgeGlowLeft != null) {
            mEdgeGlowLeft.onRelease();
            mEdgeGlowRight.onRelease();
        }
        mActivePointerId = INVALID_POINTER;
        break;
    }

    case MotionEvent.ACTION_POINTER_UP: {
        onSecondaryPointerUp(ev);
        final int x = mMotionX;
        final int y = mMotionY;
        final int motionPosition = pointToPosition(x, y);
        if (motionPosition >= 0) {
            // Remember where the motion event started
            v = getChildAt(motionPosition - mFirstPosition);
            mMotionViewOriginalLeft = v.getLeft();
            mMotionPosition = motionPosition;
        }
        mLastX = x;
        break;
    }

    case MotionEvent.ACTION_POINTER_DOWN: {
        // New pointers take over dragging duties
        final int index = ev.getActionIndex();
        final int id = ev.getPointerId(index);
        final int x = (int) ev.getX(index);
        final int y = (int) ev.getY(index);
        mMotionCorrection = 0;
        mActivePointerId = id;
        mMotionX = x;
        mMotionY = y;
        final int motionPosition = pointToPosition(x, y);
        if (motionPosition >= 0) {
            // Remember where the motion event started
            v = getChildAt(motionPosition - mFirstPosition);
            mMotionViewOriginalLeft = v.getLeft();
            mMotionPosition = motionPosition;
        }
        mLastX = x;
        break;
    }
    }

    return true;
}

From source file:android.support.v7.widget.RecyclerViewEx.java

/**
 * A LayoutManager may want to layout a view just to animate disappearance.
 * This method handles those views and triggers remove animation on them.
 *//*from  w  w  w.  j a v  a2  s. c  o m*/
private void processDisappearingList(ArrayMap<View, Rect> appearingViews) {
    final int count = mDisappearingViewsInLayoutPass.size();
    for (int i = 0; i < count; i++) {
        View view = mDisappearingViewsInLayoutPass.get(i);
        ViewHolder vh = getChildViewHolderInt(view);
        final ItemHolderInfo info = mState.mPreLayoutHolderMap.remove(vh);
        if (!mState.isPreLayout()) {
            mState.mPostLayoutHolderMap.remove(vh);
        }
        if (appearingViews.remove(view) != null) {
            mLayout.removeAndRecycleView(view, mRecycler);
            continue;
        }
        if (info != null) {
            animateDisappearance(info);
        } else {
            // let it disappear from the position it becomes visible
            animateDisappearance(
                    new ItemHolderInfo(vh, view.getLeft(), view.getTop(), view.getRight(), view.getBottom()));
        }
    }
    mDisappearingViewsInLayoutPass.clear();
}