@android.support.annotation.VisibleForTesting

Here are the examples of the java api @android.support.annotation.VisibleForTesting taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

325 Examples 7

19 Source : RealmComputableLiveData.java
with Apache License 2.0
from Zhuinden

/**
 * Created by Zhuinden on 2017.10.27..
 */
abstract clreplaced RealmComputableLiveData<T> {

    private final MutableLiveData<T> mLiveData;

    private final RealmPaginationManager realmPaginationManager;

    private final RealmQueryExecutor realmQueryExecutor;

    private AtomicBoolean mInvalid = new AtomicBoolean(true);

    private AtomicBoolean mComputing = new AtomicBoolean(false);

    /**
     * Creates a computable live data which is computed when there are active observers.
     * <p>
     * It can also be invalidated via {@link #invalidate()} which will result in a call to
     * {@link #compute()} if there are active observers (or when they start observing)
     */
    @SuppressWarnings("WeakerAccess")
    public RealmComputableLiveData(RealmPaginationManager realmPaginationManager) {
        this.realmPaginationManager = realmPaginationManager;
        this.realmQueryExecutor = realmPaginationManager.getRealmQueryExecutor();
        mLiveData = new MutableLiveData<T>() {

            @Override
            protected void onActive() {
                realmQueryExecutor.execute(mRefreshRunnable);
            }
        };
    }

    /**
     * Returns the LiveData managed by this clreplaced.
     *
     * @return A LiveData that is controlled by ComputableLiveData.
     */
    @SuppressWarnings("WeakerAccess")
    @NonNull
    public LiveData<T> getLiveData() {
        return mLiveData;
    }

    @VisibleForTesting
    final Runnable mRefreshRunnable = new Runnable() {

        @WorkerThread
        @Override
        public void run() {
            boolean computed;
            do {
                computed = false;
                // compute can happen only in 1 thread but no reason to lock others.
                if (mComputing.compareAndSet(false, true)) {
                    // as long as it is invalid, keep computing.
                    try {
                        T value = null;
                        while (mInvalid.compareAndSet(true, false)) {
                            computed = true;
                            value = compute();
                        }
                        if (computed) {
                            mLiveData.postValue(value);
                        }
                    } finally {
                        // release compute lock
                        mComputing.set(false);
                    }
                }
            // check invalid after releasing compute lock to avoid the following scenario.
            // Thread A runs compute()
            // Thread A checks invalid, it is false
            // Main thread sets invalid to true
            // Thread B runs, fails to acquire compute lock and skips
            // Thread A releases compute lock
            // We've left invalid in set state. The check below recovers.
            } while (computed && mInvalid.get());
        }
    };

    // invalidation check always happens on the main thread
    @VisibleForTesting
    final Runnable mInvalidationRunnable = new Runnable() {

        @MainThread
        @Override
        public void run() {
            boolean isActive = mLiveData.hasActiveObservers();
            if (mInvalid.compareAndSet(false, true)) {
                if (isActive) {
                    realmQueryExecutor.execute(mRefreshRunnable);
                }
            }
        }
    };

    /**
     * Invalidates the LiveData.
     * <p>
     * When there are active observers, this will trigger a call to {@link #compute()}.
     */
    public void invalidate() {
        realmPaginationManager.getMainThreadExecutor().execute(mInvalidationRunnable);
    }

    @SuppressWarnings("WeakerAccess")
    @WorkerThread
    protected abstract T compute();
}

19 Source : SampleListActivity.java
with Apache License 2.0
from zawadz88

@NonNull
@VisibleForTesting
protected PendingIntent getActionPendingIntent() {
    return PendingIntent.getActivity(this, 0, new Intent(Intent.ACTION_VIEW, Uri.parse(PLAY_STORE_URL)), PendingIntent.FLAG_UPDATE_CURRENT);
}

19 Source : Time.java
with Apache License 2.0
from YukiMatsumura

@VisibleForTesting
protected static void fixedCurrentTime(NowProvider provider) {
    nowProvider = provider;
}

19 Source : Time.java
with Apache License 2.0
from YukiMatsumura

@VisibleForTesting
protected static void tickCurrentTime() {
    nowProvider = systemCurrentTimeProvider;
}

19 Source : SpanEZ.java
with Apache License 2.0
from yombunker

/**
 * Applies the given {@code span} to the specified range from
 *
 * @param targetRange the range were the span will be applied to
 * @param span        the span to be applied
 */
@SuppressWarnings("WeakerAccess")
@VisibleForTesting
protected void addSpan(@NonNull TargetRange targetRange, @NonNull Object span) {
    final int start = targetRange.getStart();
    final int end = targetRange.getEnd();
    // Added 1 to the span, because it seems that internally it does exclusive range
    spannableContent.setSpan(span, start, end + 1, spanFlags);
}

19 Source : ISwipeRefreshLayout.java
with Apache License 2.0
from yangjiantao

/**
 * 修改官方SwipeRefreshLayout源码自定义刷新控件
 * 主要修改:
 * 1、内置默认下拉效果
 * 2、允许添加自定义的下拉效果
 * Created by jiantao on 2017/6/15.
 */
public clreplaced ISwipeRefreshLayout extends ViewGroup implements NestedScrollingParent, NestedScrollingChild {

    @VisibleForTesting
    private static final int DEFAULT_HEADER_HEIGHT = 40;

    private final int HEADER_VIEW_MIN_HEIGHT;

    private static final String LOG_TAG = ISwipeRefreshLayout.clreplaced.getSimpleName();

    private static final int MAX_ALPHA = 255;

    private static final int STARTING_PROGRESS_ALPHA = (int) (.3f * MAX_ALPHA);

    private static final float DECELERATE_INTERPOLATION_FACTOR = 2f;

    private static final int INVALID_POINTER = -1;

    private static final float DRAG_RATE = .5f;

    // Max amount of circle that can be filled by progress during swipe gesture,
    // where 1.0 is a full circle
    private static final float MAX_PROGRESS_ANGLE = .8f;

    private static final int SCALE_DOWN_DURATION = 300;

    private static final int ALPHA_ANIMATION_DURATION = 300;

    private static final int ANIMATE_TO_TRIGGER_DURATION = 200;

    private static final int ANIMATE_TO_START_DURATION = 200;

    // Default background for the progress spinner
    private static final int CIRCLE_BG_LIGHT = 0xFFFAFAFA;

    // Default offset in dips from the top of the view to where the headerview should stop
    private static final int DEFAULT_HEADER_TARGET = 64;

    // the target of the gesture
    private View mTarget;

    ISwipeRefreshLayout.OnRefreshListener mListener;

    boolean mRefreshing = false;

    private int mTouchSlop;

    private float mTotalDragDistance = -1;

    // If nested scrolling is enabled, the total amount that needed to be
    // consumed by this as the nested scrolling parent is used in place of the
    // overscroll determined by MOVE events in the onTouch handler
    private float mTotalUnconsumed;

    private final NestedScrollingParentHelper mNestedScrollingParentHelper;

    private final NestedScrollingChildHelper mNestedScrollingChildHelper;

    private final int[] mParentScrollConsumed = new int[2];

    private final int[] mParentOffsetInWindow = new int[2];

    private boolean mNestedScrollInProgress;

    private int mMediumAnimationDuration;

    private float mInitialMotionY;

    private float mInitialDownY;

    private boolean mIsBeingDragged;

    private int mActivePointerId = INVALID_POINTER;

    // Whether this item is scaled up rather than clipped
    boolean mScale;

    // Target is returning to its start offset because it was cancelled or a
    // refresh was triggered.
    private boolean mReturningToStart;

    private final DecelerateInterpolator mDecelerateInterpolator;

    private static final int[] LAYOUT_ATTRS = new int[] { android.R.attr.enabled };

    private View mRefreshView;

    private int mRefreshViewIndex = -1;

    float mStartingScale;

    protected int mOriginalOffsetTop;

    private Animation mScaleDownAnimation;

    private Animation mScaleDownToStartAnimation;

    boolean mNotify;

    private int mRefreshViewHeight;

    // Whether the client has set a custom starting position;
    boolean mUsingCustomStart;

    private ISwipeRefreshLayout.OnChildScrollUpCallback mChildScrollUpCallback;

    private Animation.AnimationListener mRefreshListener = new Animation.AnimationListener() {

        @Override
        public void onAnimationStart(Animation animation) {
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }

        @SuppressLint("NewApi")
        @Override
        public void onAnimationEnd(Animation animation) {
            if (mRefreshing) {
                // Make sure the progress view is fully visible
                getRefreshTrigger().onRefreshing();
                if (mNotify) {
                    if (mListener != null) {
                        // System.out.println(" onRefresh !!!");
                        mListener.onRefresh();
                    }
                }
            } else {
                reset();
            }
        }
    };

    void reset() {
        mRefreshView.clearAnimation();
        // Return the circle to its start position
        if (mScale) {
            setAnimationProgress(0);
        } else {
            translateContentViews(0f);
        }
    }

    @Override
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        if (!enabled) {
            reset();
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        reset();
    }

    /**
     * Simple constructor to use when creating a ISwipeRefreshLayout from code.
     *
     * @param context
     */
    public ISwipeRefreshLayout(Context context) {
        this(context, null);
    }

    /**
     * Constructor that is called when inflating ISwipeRefreshLayout from XML.
     *
     * @param context
     * @param attrs
     */
    public ISwipeRefreshLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
        mMediumAnimationDuration = getResources().getInteger(android.R.integer.config_mediumAnimTime);
        setWillNotDraw(false);
        mDecelerateInterpolator = new DecelerateInterpolator(DECELERATE_INTERPOLATION_FACTOR);
        final DisplayMetrics metrics = getResources().getDisplayMetrics();
        mRefreshViewHeight = (int) (DEFAULT_HEADER_HEIGHT * metrics.density);
        HEADER_VIEW_MIN_HEIGHT = mRefreshViewHeight;
        ViewCompat.setChildrenDrawingOrderEnabled(this, true);
        mTotalDragDistance = (int) (DEFAULT_HEADER_TARGET * metrics.density);
        mNestedScrollingParentHelper = new NestedScrollingParentHelper(this);
        mNestedScrollingChildHelper = new NestedScrollingChildHelper(this);
        setNestedScrollingEnabled(true);
        final TypedArray a = context.obtainStyledAttributes(attrs, LAYOUT_ATTRS);
        setEnabled(a.getBoolean(0, true));
        a.recycle();
        // add default refreshview
        setRefreshHeaderView(new ClreplacedicIRefreshHeaderView(getContext()));
    }

    @Override
    protected int getChildDrawingOrder(int childCount, int i) {
        if (mRefreshViewIndex < 0) {
            return i;
        } else if (i == childCount - 1) {
            // Draw the selected child last
            return mRefreshViewIndex;
        } else if (i >= mRefreshViewIndex) {
            // Move the children after the selected child earlier one
            return i + 1;
        } else {
            // Keep the children before the selected child the same
            return i;
        }
    }

    /**
     * @param view
     */
    public void setRefreshHeaderView(View view) {
        if (view == null) {
            return;
        }
        removeView(mRefreshView);
        this.mRefreshView = view;
        view.setMinimumHeight(HEADER_VIEW_MIN_HEIGHT);
        addView(view);
        getRefreshTrigger().init();
    }

    /**
     * Set the listener to be notified when a refresh is triggered via the swipe
     * gesture.
     */
    public void setOnRefreshListener(ISwipeRefreshLayout.OnRefreshListener listener) {
        mListener = listener;
    }

    /**
     * Notify the widget that refresh state has changed. Do not call this when
     * refresh is triggered by a swipe gesture.
     *
     * @param refreshing Whether or not the view should show refresh progress.
     */
    public void setRefreshing(boolean refreshing) {
        // System.out.println("setRefreshing refreshing "+refreshing);
        if (mRefreshView == null || !isEnabled()) {
            return;
        }
        if (refreshing && mRefreshing != refreshing) {
            // scale and show
            mRefreshing = refreshing;
            // 移动到刷新位置
            animateOffsetToCorrectPosition(mRefreshListener);
            mNotify = false;
            startScaleUpAnimation();
        } else {
            setRefreshing(refreshing, false);
        }
    }

    @SuppressLint("NewApi")
    private void startScaleUpAnimation() {
        mRefreshView.setVisibility(View.VISIBLE);
        ValueAnimator animator = ValueAnimator.ofFloat(0.0f, 1.0f);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                setAnimationProgress(((float) animation.getAnimatedValue()));
            // listener.onAnimationEnd(null);
            }
        });
        animator.setDuration(mMediumAnimationDuration);
        animator.start();
    }

    /**
     * Pre API 11, this does an alpha animation.
     *
     * @param progress
     */
    void setAnimationProgress(float progress) {
        mRefreshView.setScaleX(progress);
        mRefreshView.setScaleY(progress);
    }

    private void setRefreshing(boolean refreshing, final boolean notify) {
        if (mRefreshing != refreshing) {
            mNotify = notify;
            ensureTarget();
            mRefreshing = refreshing;
            if (mRefreshing) {
                animateOffsetToCorrectPosition(mRefreshListener);
            } else {
                startScaleDownAnimation(mRefreshListener);
            }
        }
    }

    void startScaleDownAnimation(Animation.AnimationListener listener) {
        mScaleDownAnimation = new Animation() {

            @Override
            public void applyTransformation(float interpolatedTime, Transformation t) {
                setAnimationProgress(1 - interpolatedTime);
                translateContentViews((mTarget.getTranslationY() * (1 - interpolatedTime)));
            // System.out.println(" mScaleDownAnimation interpolatedTime = " + interpolatedTime);
            }
        };
        mScaleDownAnimation.setDuration(SCALE_DOWN_DURATION);
        mScaleDownAnimation.setAnimationListener(listener);
        // 刷新完成,延时200ms,用于展示完成状态.但最好是有一个完成的动画。TODO
        mScaleDownAnimation.setStartOffset(listener != null ? 500 : -1);
        mRefreshView.clearAnimation();
        mRefreshView.startAnimation(mScaleDownAnimation);
        if (listener != null) {
            // 刷新完成
            getRefreshTrigger().onComplete();
        }
    }

    /**
     * @return Whether the SwipeRefreshWidget is actively showing refresh
     * progress.
     */
    public boolean isRefreshing() {
        return mRefreshing;
    }

    private void ensureTarget() {
        // Don't bother getting the parent height if the parent hasn't been laid
        // out yet.
        if (mTarget == null) {
            for (int i = 0; i < getChildCount(); i++) {
                View child = getChildAt(i);
                if (!child.equals(mRefreshView)) {
                    mTarget = child;
                    break;
                }
            }
        }
    }

    /**
     * Set the distance to trigger a sync in dips
     *
     * @param distance
     */
    public void setDistanceToTriggerSync(int distance) {
        mTotalDragDistance = distance;
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        final int width = getMeasuredWidth();
        final int height = getMeasuredHeight();
        if (getChildCount() == 0) {
            return;
        }
        if (mTarget == null) {
            ensureTarget();
        }
        if (mTarget == null) {
            return;
        }
        final View child = mTarget;
        final int childLeft = getPaddingLeft();
        final int childTop = getPaddingTop();
        final int childWidth = width - getPaddingLeft() - getPaddingRight();
        final int childHeight = height - getPaddingTop() - getPaddingBottom();
        child.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight);
        if (mRefreshView != null) {
            int refreshWidth = mRefreshView.getMeasuredWidth();
            // 使mRefreshView相对父控件水平方向居中,竖直方向在父控件的上面位置,刚好看不见。
            mRefreshView.layout((width / 2 - refreshWidth / 2), childTop - mRefreshViewHeight, (width / 2 + refreshWidth / 2), childTop);
        }
    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (mTarget == null) {
            ensureTarget();
        }
        if (mTarget == null) {
            return;
        }
        mTarget.measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth() - getPaddingLeft() - getPaddingRight(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(getMeasuredHeight() - getPaddingTop() - getPaddingBottom(), MeasureSpec.EXACTLY));
        if (mRefreshView != null) {
            // 计算view宽高
            measureChild(mRefreshView, widthMeasureSpec, heightMeasureSpec);
            // 缓存一些变量
            updateBaseValues(mRefreshView.getMeasuredHeight());
            mRefreshViewIndex = -1;
            // Get the index of the circleview.
            for (int index = 0; index < getChildCount(); index++) {
                if (getChildAt(index) == mRefreshView) {
                    mRefreshViewIndex = index;
                    break;
                }
            }
        }
    }

    // 更新基础信息
    private void updateBaseValues(int refreshViewHeight) {
        mRefreshViewHeight = refreshViewHeight;
        mOriginalOffsetTop = -mRefreshViewHeight;
        setDistanceToTriggerSync(Math.round(mRefreshViewHeight * 1.5f));
    }

    /**
     * @return Whether it is possible for the child view of this layout to
     * scroll up. Override this if the child view is a custom view.
     */
    public boolean canChildScrollUp() {
        if (mChildScrollUpCallback != null) {
            return mChildScrollUpCallback.canChildScrollUp(this, mTarget);
        }
        return ViewCompat.canScrollVertically(mTarget, -1);
    }

    /**
     * Set a callback to override {@link ISwipeRefreshLayout#canChildScrollUp()} method. Non-null
     * callback will return the value provided by the callback and ignore all internal logic.
     *
     * @param callback Callback that should be called when canChildScrollUp() is called.
     */
    public void setOnChildScrollUpCallback(@Nullable ISwipeRefreshLayout.OnChildScrollUpCallback callback) {
        mChildScrollUpCallback = callback;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        ensureTarget();
        final int action = ev.getActionMasked();
        int pointerIndex;
        if (mReturningToStart && action == MotionEvent.ACTION_DOWN) {
            mReturningToStart = false;
        }
        // System.out.println("isEnabled "+ isEnabled()+"; mReturningToStart "+mReturningToStart+"; canChildScrollUp() "+canChildScrollUp()+" " +
        // " mRefreshing "+mRefreshing+"; mNestedScrollInProgress "+mNestedScrollInProgress+" ; mRefreshView "+mRefreshView);
        if (canNotPullToRefresh()) {
            // Fail fast if we're not in a state where a swipe is possible
            return false;
        }
        switch(action) {
            case MotionEvent.ACTION_DOWN:
                translateContentViews(0f);
                mActivePointerId = ev.getPointerId(0);
                mIsBeingDragged = false;
                pointerIndex = ev.findPointerIndex(mActivePointerId);
                if (pointerIndex < 0) {
                    return false;
                }
                mInitialDownY = ev.getY(pointerIndex);
                break;
            case MotionEvent.ACTION_MOVE:
                if (mActivePointerId == INVALID_POINTER) {
                    Log.e(LOG_TAG, "Got ACTION_MOVE event but don't have an active pointer id.");
                    return false;
                }
                pointerIndex = ev.findPointerIndex(mActivePointerId);
                if (pointerIndex < 0) {
                    return false;
                }
                final float y = ev.getY(pointerIndex);
                startDragging(y);
                break;
            case MotionEvent.ACTION_POINTER_UP:
                onSecondaryPointerUp(ev);
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                mIsBeingDragged = false;
                mActivePointerId = INVALID_POINTER;
                break;
        }
        return mIsBeingDragged;
    }

    @Override
    public void requestDisallowInterceptTouchEvent(boolean b) {
        // if this is a List < L or another view that doesn't support nested
        // scrolling, ignore this request so that the vertical scroll event
        // isn't stolen
        if ((android.os.Build.VERSION.SDK_INT < 21 && mTarget instanceof AbsListView) || (mTarget != null && !ViewCompat.isNestedScrollingEnabled(mTarget))) {
        // Nope.
        } else {
            super.requestDisallowInterceptTouchEvent(b);
        }
    }

    // NestedScrollingParent
    @Override
    public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) {
        return isEnabled() && !mReturningToStart && !mRefreshing && (nestedScrollAxes & ViewCompat.SCROLL_AXIS_VERTICAL) != 0;
    }

    @Override
    public void onNestedScrollAccepted(View child, View target, int axes) {
        // Reset the counter of how much leftover scroll needs to be consumed.
        mNestedScrollingParentHelper.onNestedScrollAccepted(child, target, axes);
        // Dispatch up to the nested parent
        startNestedScroll(axes & ViewCompat.SCROLL_AXIS_VERTICAL);
        mTotalUnconsumed = 0;
        mNestedScrollInProgress = true;
    }

    @Override
    public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) {
        // If we are in the middle of consuming, a scroll, then we want to move the spinner back up
        // before allowing the list to scroll
        if (dy > 0 && mTotalUnconsumed > 0) {
            if (dy > mTotalUnconsumed) {
                consumed[1] = dy - (int) mTotalUnconsumed;
                mTotalUnconsumed = 0;
            } else {
                mTotalUnconsumed -= dy;
                consumed[1] = dy;
            }
            moveSpinner(mTotalUnconsumed);
        }
        // If a client layout is using a custom start position for the circle
        // view, they mean to hide it again before scrolling the child view
        // If we get back to mTotalUnconsumed == 0 and there is more to go, hide
        // the circle so it isn't exposed if its blocking content is moved
        if (mUsingCustomStart && dy > 0 && mTotalUnconsumed == 0 && Math.abs(dy - consumed[1]) > 0) {
            mRefreshView.setVisibility(View.GONE);
        }
        // Now let our nested parent consume the leftovers
        final int[] parentConsumed = mParentScrollConsumed;
        if (dispatchNestedPreScroll(dx - consumed[0], dy - consumed[1], parentConsumed, null)) {
            consumed[0] += parentConsumed[0];
            consumed[1] += parentConsumed[1];
        }
    }

    @Override
    public int getNestedScrollAxes() {
        return mNestedScrollingParentHelper.getNestedScrollAxes();
    }

    @Override
    public void onStopNestedScroll(View target) {
        mNestedScrollingParentHelper.onStopNestedScroll(target);
        mNestedScrollInProgress = false;
        // Finish the spinner for nested scrolling if we ever consumed any
        // unconsumed nested scroll
        if (mTotalUnconsumed > 0) {
            finishSpinner(mTotalUnconsumed);
            mTotalUnconsumed = 0;
        }
        // Dispatch up our nested parent
        stopNestedScroll();
    }

    @Override
    public void onNestedScroll(final View target, final int dxConsumed, final int dyConsumed, final int dxUnconsumed, final int dyUnconsumed) {
        // Dispatch up to the nested parent first
        dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, mParentOffsetInWindow);
        // This is a bit of a hack. Nested scrolling works from the bottom up, and as we are
        // sometimes between two nested scrolling views, we need a way to be able to know when any
        // nested scrolling parent has stopped handling events. We do that by using the
        // 'offset in window 'functionality to see if we have been moved from the event.
        // This is a decent indication of whether we should take over the event stream or not.
        final int dy = dyUnconsumed + mParentOffsetInWindow[1];
        if (dy < 0 && !canChildScrollUp()) {
            mTotalUnconsumed += Math.abs(dy);
            moveSpinner(mTotalUnconsumed);
        }
    }

    // NestedScrollingChild
    @Override
    public void setNestedScrollingEnabled(boolean enabled) {
        mNestedScrollingChildHelper.setNestedScrollingEnabled(enabled);
    }

    @Override
    public boolean isNestedScrollingEnabled() {
        return mNestedScrollingChildHelper.isNestedScrollingEnabled();
    }

    @Override
    public boolean startNestedScroll(int axes) {
        return mNestedScrollingChildHelper.startNestedScroll(axes);
    }

    @Override
    public void stopNestedScroll() {
        mNestedScrollingChildHelper.stopNestedScroll();
    }

    @Override
    public boolean hasNestedScrollingParent() {
        return mNestedScrollingChildHelper.hasNestedScrollingParent();
    }

    @Override
    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) {
        return mNestedScrollingChildHelper.dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, offsetInWindow);
    }

    @Override
    public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) {
        return mNestedScrollingChildHelper.dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow);
    }

    @Override
    public boolean onNestedPreFling(View target, float velocityX, float velocityY) {
        return dispatchNestedPreFling(velocityX, velocityY);
    }

    @Override
    public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) {
        return dispatchNestedFling(velocityX, velocityY, consumed);
    }

    @Override
    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
        return mNestedScrollingChildHelper.dispatchNestedFling(velocityX, velocityY, consumed);
    }

    @Override
    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
        return mNestedScrollingChildHelper.dispatchNestedPreFling(velocityX, velocityY);
    }

    private boolean isAnimationRunning(Animation animation) {
        return animation != null && animation.hreplacedtarted() && !animation.hasEnded();
    }

    @SuppressLint("NewApi")
    private void moveSpinner(float overscrollTop) {
        // where 1.0f is a full circle
        if (mRefreshView.getVisibility() != View.VISIBLE) {
            mRefreshView.setVisibility(View.VISIBLE);
        }
        if (!mScale) {
            mRefreshView.setScaleX(1f);
            mRefreshView.setScaleY(1f);
        }
        if (mScale) {
            // 大小缩放动画
            setAnimationProgress(Math.min(1f, overscrollTop / mTotalDragDistance));
        }
        float progress = overscrollTop / mTotalDragDistance;
        if (progress < 1.0f) {
            // 下拉至触发点的百分比
            getRefreshTrigger().onPullDownState(progress);
        } else {
            // 释放即可触发刷新
            getRefreshTrigger().onReleaseToRefresh();
        }
        // 下拉过程view的移动距离
        final float tranlationY = overscrollTop > mTotalDragDistance ? mTotalDragDistance : overscrollTop;
        // 执行移动动画
        translateContentViews(tranlationY);
    }

    private IRefreshTrigger getRefreshTrigger() {
        try {
            return ((IRefreshTrigger) mRefreshView);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(" mRefreshHeadview must implements IRefreshTrigger !!!");
        }
    }

    private void finishSpinner(float overscrollTop) {
        // System.out.println(" finishSpinner overescrollTop " + overscrollTop + "; mTotalDragDistance = " + mTotalDragDistance);
        if (overscrollTop > mTotalDragDistance) {
            setRefreshing(true, true);
        } else {
            // cancel refresh
            mRefreshing = false;
            Animation.AnimationListener listener = null;
            if (!mScale) {
                listener = new Animation.AnimationListener() {

                    @Override
                    public void onAnimationStart(Animation animation) {
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        if (!mScale) {
                            startScaleDownAnimation(null);
                        }
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {
                    }
                };
            }
            animateOffsetToStartPosition(listener);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        final int action = ev.getActionMasked();
        int pointerIndex = -1;
        if (mReturningToStart && action == MotionEvent.ACTION_DOWN) {
            mReturningToStart = false;
        }
        if (canNotPullToRefresh()) {
            // Fail fast if we're not in a state where a swipe is possible
            return false;
        }
        switch(action) {
            case MotionEvent.ACTION_DOWN:
                mActivePointerId = ev.getPointerId(0);
                mIsBeingDragged = false;
                break;
            case MotionEvent.ACTION_MOVE:
                {
                    pointerIndex = ev.findPointerIndex(mActivePointerId);
                    if (pointerIndex < 0) {
                        Log.e(LOG_TAG, "Got ACTION_MOVE event but have an invalid active pointer id.");
                        return false;
                    }
                    final float y = ev.getY(pointerIndex);
                    startDragging(y);
                    if (mIsBeingDragged) {
                        final float overscrollTop = (y - mInitialMotionY) * DRAG_RATE;
                        if (overscrollTop > 0) {
                            moveSpinner(overscrollTop);
                        } else {
                            return false;
                        }
                    }
                    break;
                }
            case MotionEvent.ACTION_POINTER_DOWN:
                {
                    pointerIndex = ev.getActionIndex();
                    if (pointerIndex < 0) {
                        Log.e(LOG_TAG, "Got ACTION_POINTER_DOWN event but have an invalid action index.");
                        return false;
                    }
                    mActivePointerId = ev.getPointerId(pointerIndex);
                    break;
                }
            case MotionEvent.ACTION_POINTER_UP:
                onSecondaryPointerUp(ev);
                break;
            case MotionEvent.ACTION_UP:
                {
                    pointerIndex = ev.findPointerIndex(mActivePointerId);
                    if (pointerIndex < 0) {
                        Log.e(LOG_TAG, "Got ACTION_UP event but don't have an active pointer id.");
                        return false;
                    }
                    if (mIsBeingDragged) {
                        final float y = ev.getY(pointerIndex);
                        final float overscrollTop = (y - mInitialMotionY) * DRAG_RATE;
                        mIsBeingDragged = false;
                        finishSpinner(overscrollTop);
                    }
                    mActivePointerId = INVALID_POINTER;
                    return false;
                }
            case MotionEvent.ACTION_CANCEL:
                return false;
        }
        return true;
    }

    /**
     * @return 不能下拉刷新状态
     */
    private boolean canNotPullToRefresh() {
        return !isEnabled() || mReturningToStart || canChildScrollUp() || mRefreshing || mNestedScrollInProgress || mRefreshView == null;
    }

    @SuppressLint("NewApi")
    private void startDragging(float y) {
        final float yDiff = y - mInitialDownY;
        if (yDiff > mTouchSlop && !mIsBeingDragged) {
            mInitialMotionY = mInitialDownY + mTouchSlop;
            mIsBeingDragged = true;
        // mProgress.setAlpha(STARTING_PROGRESS_ALPHA);
        }
    }

    private void animateOffsetToCorrectPosition(Animation.AnimationListener listener) {
        mAnimateToCorrectPosition.reset();
        mAnimateToCorrectPosition.setDuration(ANIMATE_TO_TRIGGER_DURATION);
        mAnimateToCorrectPosition.setInterpolator(mDecelerateInterpolator);
        if (listener != null) {
            mAnimateToCorrectPosition.setAnimationListener(listener);
        }
        mRefreshView.clearAnimation();
        mRefreshView.startAnimation(mAnimateToCorrectPosition);
    }

    private void animateOffsetToStartPosition(Animation.AnimationListener listener) {
        if (mScale) {
            // Scale the item back down
            startScaleDownReturnToStartAnimation(listener);
        } else {
            mAnimateToStartPosition.reset();
            mAnimateToStartPosition.setDuration(ANIMATE_TO_START_DURATION);
            mAnimateToStartPosition.setInterpolator(mDecelerateInterpolator);
            if (listener != null) {
                mAnimateToStartPosition.setAnimationListener(listener);
            }
            mRefreshView.clearAnimation();
            mRefreshView.startAnimation(mAnimateToStartPosition);
        }
    }

    /**
     * 回到刷新位置的动画
     */
    private final Animation mAnimateToCorrectPosition = new Animation() {

        @Override
        public void applyTransformation(float interpolatedTime, Transformation t) {
            final float translationY = mRefreshView.getTranslationY() + (mRefreshViewHeight - mRefreshView.getTranslationY()) * interpolatedTime;
            translateContentViews(translationY);
        }
    };

    void moveToStart(float interpolatedTime) {
        translateContentViews(mRefreshView.getTranslationY() * (1 - interpolatedTime));
    }

    private final Animation mAnimateToStartPosition = new Animation() {

        @Override
        public void applyTransformation(float interpolatedTime, Transformation t) {
            moveToStart(interpolatedTime);
        }
    };

    @SuppressLint("NewApi")
    private void startScaleDownReturnToStartAnimation(Animation.AnimationListener listener) {
        mStartingScale = mRefreshView.getScaleX();
        mScaleDownToStartAnimation = new Animation() {

            @Override
            public void applyTransformation(float interpolatedTime, Transformation t) {
                float targetScale = (mStartingScale + (-mStartingScale * interpolatedTime));
                setAnimationProgress(targetScale);
                moveToStart(interpolatedTime);
            }
        };
        mScaleDownToStartAnimation.setDuration(SCALE_DOWN_DURATION);
        if (listener != null) {
            mScaleDownToStartAnimation.setAnimationListener(listener);
        }
        mRefreshView.clearAnimation();
        mRefreshView.startAnimation(mScaleDownToStartAnimation);
    }

    private void translateContentViews(float transY) {
        if (mRefreshView != null) {
            mRefreshView.bringToFront();
            ViewCompat.setTranslationY(mRefreshView, transY);
        }
        // mTarget translationY offset
        if (mTarget != null) {
            final float maxValue = mRefreshView.getTranslationY() + mRefreshViewHeight;
            ViewCompat.setTranslationY(mTarget, transY > maxValue ? maxValue : transY);
        }
    }

    private void onSecondaryPointerUp(MotionEvent ev) {
        final int pointerIndex = ev.getActionIndex();
        final int pointerId = ev.getPointerId(pointerIndex);
        if (pointerId == mActivePointerId) {
            // This was our active pointer going up. Choose a new
            // active pointer and adjust accordingly.
            final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
            mActivePointerId = ev.getPointerId(newPointerIndex);
        }
    }

    /**
     * Clreplacedes that wish to be notified when the swipe gesture correctly
     * triggers a refresh should implement this interface.
     */
    public interface OnRefreshListener {

        /**
         * Called when a swipe gesture triggers a refresh.
         */
        void onRefresh();
    }

    /**
     * Clreplacedes that wish to override {@link ISwipeRefreshLayout#canChildScrollUp()} method
     * behavior should implement this interface.
     */
    public interface OnChildScrollUpCallback {

        /**
         * Callback that will be called when {@link ISwipeRefreshLayout#canChildScrollUp()} method
         * is called to allow the implementer to override its behavior.
         *
         * @param parent ISwipeRefreshLayout that this callback is overriding.
         * @param child  The child view of ISwipeRefreshLayout.
         * @return Whether it is possible for the child view of parent layout to scroll up.
         */
        boolean canChildScrollUp(ISwipeRefreshLayout parent, @Nullable View child);
    }
}

19 Source : ViewPagerBottomSheetBehavior.java
with Apache License 2.0
from y1xian

@VisibleForTesting
View findScrollingChild(View view) {
    if (ViewCompat.isNestedScrollingEnabled(view)) {
        return view;
    }
    if (view instanceof ViewPager) {
        ViewPager viewPager = (ViewPager) view;
        View currentViewPagerChild = ViewPagerUtils.getCurrentView(viewPager);
        if (currentViewPagerChild == null) {
            return null;
        }
        View scrollingChild = findScrollingChild(currentViewPagerChild);
        if (scrollingChild != null) {
            return scrollingChild;
        }
    } else if (view instanceof ViewGroup) {
        ViewGroup group = (ViewGroup) view;
        for (int i = 0, count = group.getChildCount(); i < count; i++) {
            View scrollingChild = findScrollingChild(group.getChildAt(i));
            if (scrollingChild != null) {
                return scrollingChild;
            }
        }
    }
    return null;
}

19 Source : ViewPagerBottomSheetBehavior.java
with Apache License 2.0
from y1xian

@VisibleForTesting
int getPeekHeightMin() {
    return mPeekHeightMin;
}

19 Source : Closeables.java
with MIT License
from xiandanin

/**
 * Utility methods for working with {@link Closeable} objects.
 *
 * @author Michael Lancaster
 * @since 1.0
 */
public clreplaced Closeables {

    @VisibleForTesting
    static final Logger logger = Logger.getLogger(Closeables.clreplaced.getName());

    private Closeables() {
    }

    /**
     * Closes the given {@link InputStream}, logging any {@code IOException} that's thrown rather
     * than propagating it.
     *
     * <p>While it's not safe in the general case to ignore exceptions that are thrown when closing
     * an I/O resource, it should generally be safe in the case of a resource that's being used only
     * for reading, such as an {@code InputStream}. Unlike with writable resources, there's no
     * chance that a failure that occurs when closing the stream indicates a meaningful problem such
     * as a failure to flush all bytes to the underlying resource.
     *
     * @param inputStream the input stream to be closed, or {@code null} in which case this method
     *                    does nothing
     * @since 17.0
     */
    public static void closeQuietly(@Nullable InputStream inputStream) {
        try {
            close(inputStream, true);
        } catch (IOException impossible) {
            throw new replacedertionError(impossible);
        }
    }

    /**
     * Closes a {@link Closeable}, with control over whether an {@code IOException} may be thrown.
     * This is primarily useful in a finally block, where a thrown exception needs to be logged but
     * not propagated (otherwise the original exception will be lost).
     *
     * <p>If {@code swallowIOException} is true then we never throw {@code IOException} but merely log
     * it.
     *
     * <p>Example: <pre>   {@code
     *
     *   public void useStreamNicely() throws IOException {
     *     SomeStream stream = new SomeStream("foo");
     *     boolean threw = true;
     *     try {
     *       // ... code which does something with the stream ...
     *       threw = false;
     *     } finally {
     *       // If an exception occurs, rethrow it only if threw==false:
     *       Closeables.close(stream, threw);
     *     }
     *   }}</pre>
     *
     * @param closeable          the {@code Closeable} object to be closed, or null, in which case this method
     *                           does nothing
     * @param swallowIOException if true, don't propagate IO exceptions thrown by the {@code close}
     *                           methods
     * @throws IOException if {@code swallowIOException} is false and {@code close} throws an
     *                     {@code IOException}.
     */
    public static void close(@Nullable Closeable closeable, boolean swallowIOException) throws IOException {
        if (closeable == null) {
            return;
        }
        try {
            closeable.close();
        } catch (IOException e) {
            if (swallowIOException) {
                logger.log(Level.WARNING, "IOException thrown while closing Closeable.", e);
            } else {
                throw e;
            }
        }
    }
}

19 Source : SmsListener.java
with GNU General Public License v3.0
from XecureIT

@VisibleForTesting
String parseChallenge(String messageBody) {
    Matcher challengeMatcher = CHALLENGE_PATTERN.matcher(messageBody);
    if (!challengeMatcher.matches()) {
        throw new replacedertionError("Expression should match.");
    }
    return challengeMatcher.group(2) + challengeMatcher.group(3);
}

19 Source : AttachmentDatabase.java
with GNU General Public License v3.0
from XecureIT

@VisibleForTesting
@Nullable
protected InputStream getDataStream(MasterSecret masterSecret, AttachmentId attachmentId, String dataType) {
    File dataFile = getAttachmentDataFile(attachmentId, dataType);
    try {
        if (dataFile != null)
            return DecryptingPartInputStream.createFor(masterSecret, dataFile);
        else
            return null;
    } catch (IOException e) {
        Log.w(TAG, e);
        return null;
    }
}

19 Source : AttachmentDatabase.java
with GNU General Public License v3.0
from XecureIT

@VisibleForTesting
@Nullable
public DatabaseAttachment getAttachment(@Nullable MasterSecret masterSecret, AttachmentId attachmentId) {
    SQLiteDatabase database = databaseHelper.getReadableDatabase();
    Cursor cursor = null;
    try {
        cursor = database.query(TABLE_NAME, PROJECTION, PART_ID_WHERE, attachmentId.toStrings(), null, null, null);
        if (cursor != null && cursor.moveToFirst())
            return getAttachment(masterSecret, cursor);
        else
            return null;
    } finally {
        if (cursor != null)
            cursor.close();
    }
}

19 Source : TasksActivity.java
with MIT License
from why168

@VisibleForTesting
public IdlingResource getCountingIdlingResource() {
    return EspressoIdlingResource.getIdlingResource();
}

19 Source : LogcatDumper.java
with Apache License 2.0
from weexteam

@VisibleForTesting
@Nullable
public Handler getHandler() {
    return mHandler;
}

19 Source : WXInspectorItemView.java
with Apache License 2.0
from weexteam

@VisibleForTesting
static String getPureValue(@Nullable String rawValue) {
    if (rawValue == null || "".equals(rawValue.trim())) {
        return "0";
    }
    // 四舍五入 去掉小数点
    // 去掉px/wx等单位
    String digits = rawValue.replaceAll("[^0-9.-]", "");
    int dotIndex = digits.indexOf('.');
    int len = digits.length();
    if (dotIndex >= 0) {
        if (len - 1 > dotIndex) {
            try {
                double d = Double.valueOf(digits);
                d = Math.round(d);
                return String.valueOf((int) d);
            } catch (Exception e) {
                return digits.substring(0, dotIndex);
            }
        } else {
            return digits.substring(0, dotIndex);
        }
    } else {
        return digits;
    }
}

19 Source : NetworkEventInspector.java
with Apache License 2.0
from weexteam

@VisibleForTesting
@NonNull
static NetworkEventInspector createInstance(@NonNull LocalBroadcastManager manager, @NonNull OnMessageReceivedListener listener) {
    NetworkEventInspector reporter = new NetworkEventInspector(manager);
    reporter.setOnMessageReceivedListener(listener);
    return reporter;
}

19 Source : BorderDrawable.java
with Apache License 2.0
from weexext

@VisibleForTesting
float getBorderRadius(@BorderRadiusType int position) {
    return getBorderRadius(mOverlappingBorderRadius, position);
}

19 Source : WXTimerModule.java
with Apache License 2.0
from weexext

@VisibleForTesting
void setHandler(Handler handler) {
    this.handler = handler;
}

19 Source : SearchUserPresenter.java
with Apache License 2.0
from VictorAlbertos

@VisibleForTesting
void getUserByUserName(String username) {
    if (username.isEmpty()) {
        notifications.showSnackBar(R.string.fill_missing_fields);
        return;
    }
    userRepository.searchByUserName(username).compose(transformations.safely()).compose(transformations.loading()).compose(transformations.reportOnSnackBar()).subscribe(user -> {
        userState = user;
        view.showUser(user);
    });
}

19 Source : ExceptionFormatter.java
with Apache License 2.0
from VictorAlbertos

@VisibleForTesting
boolean isBuildConfigDebug() {
    return BuildConfig.DEBUG;
}

19 Source : GraywaterAdapter.java
with Apache License 2.0
from tumblr

/**
 * Computes the position of the item and the position of the binder within the item's binder list.
 * Note that this is an <i>O(n)</i> operation.
 *
 * @param viewHolderPosition
 * 		the position of the view holder in the adapter.
 * @return the item position and the position of the binder in the item's binder list.
 */
@VisibleForTesting
BinderResult computeItemAndBinderIndex(final int viewHolderPosition) {
    // subtract off the length of each list until we get to the desired item
    final int itemIndex = mViewHolderToItemPositionCache.get(viewHolderPosition);
    final T item = mItems.get(itemIndex);
    final List<Provider<Binder<? super T, VH, ? extends VH>>> binders = mBinderListCache.get(itemIndex);
    // index of the first item in the set of viewholders for the current item.
    final int firstVHPosForItem = mItemPositionToFirstViewHolderPositionCache.get(itemIndex);
    return new BinderResult(item, itemIndex, binders, viewHolderPosition - firstVHPosForItem);
}

19 Source : GraywaterAdapter.java
with Apache License 2.0
from tumblr

/**
 * Note that this is an <i>O(n)</i> operation, but it does not query for the list of binders.
 *
 * @param itemPosition
 * 		the position in the list of items.
 * @return the number of viewholders before the given item position.
 */
@VisibleForTesting
public int getViewHolderCount(final int itemPosition) {
    if (itemPosition >= 0 && !mItemPositionToFirstViewHolderPositionCache.isEmpty()) {
        if (itemPosition >= mItemPositionToFirstViewHolderPositionCache.size()) {
            return mViewHolderToItemPositionCache.size();
        } else {
            return mItemPositionToFirstViewHolderPositionCache.get(itemPosition);
        }
    } else {
        return 0;
    }
}

19 Source : BaseActivity.java
with GNU General Public License v3.0
from TudorCretu

public clreplaced BaseActivity extends FragmentActivity {

    @VisibleForTesting
    public ProgressDialog mProgressDialog;

    public void showProgressDialog() {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage(getString(R.string.loading));
            mProgressDialog.setIndeterminate(true);
        }
        mProgressDialog.show();
    }

    public void hideProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        hideProgressDialog();
    }
}

19 Source : AdminApi.java
with BSD 3-Clause "New" or "Revised" License
from tresorit

@VisibleForTesting
@NonNull
public IdlingResource getIdlingResource() {
    if (idlingResource == null)
        idlingResource = new ZerokitCountingIdlingResource();
    return idlingResource;
}

19 Source : MainActivity.java
with Apache License 2.0
from tmurakami

public final clreplaced MainActivity extends Activity {

    @VisibleForTesting
    MyService myService = new MyService();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myService.doIt();
    }
}

19 Source : FastScroller.java
with GNU General Public License v2.0
from TelePlusDev

@VisibleForTesting
boolean isPointInsideHorizontalThumb(float x, float y) {
    return (y >= mRecyclerViewHeight - mHorizontalThumbHeight) && x >= mHorizontalThumbCenterX - mHorizontalThumbWidth / 2 && x <= mHorizontalThumbCenterX + mHorizontalThumbWidth / 2;
}

19 Source : FastScroller.java
with GNU General Public License v2.0
from TelePlusDev

@VisibleForTesting
Drawable getVerticalThumbDrawable() {
    return mVerticalThumbDrawable;
}

19 Source : FastScroller.java
with GNU General Public License v2.0
from TelePlusDev

@VisibleForTesting
Drawable getHorizontalThumbDrawable() {
    return mHorizontalThumbDrawable;
}

19 Source : FastScroller.java
with GNU General Public License v2.0
from TelePlusDev

@VisibleForTesting
void hide(int duration) {
    switch(mAnimationState) {
        case ANIMATION_STATE_FADING_IN:
            mShowHideAnimator.cancel();
        // fall through
        case ANIMATION_STATE_IN:
            mAnimationState = ANIMATION_STATE_FADING_OUT;
            mShowHideAnimator.setFloatValues((float) mShowHideAnimator.getAnimatedValue(), 0);
            mShowHideAnimator.setDuration(duration);
            mShowHideAnimator.start();
            break;
    }
}

19 Source : FastScroller.java
with GNU General Public License v2.0
from TelePlusDev

@VisibleForTesting
Drawable getHorizontalTrackDrawable() {
    return mHorizontalTrackDrawable;
}

19 Source : FastScroller.java
with GNU General Public License v2.0
from TelePlusDev

@VisibleForTesting
Drawable getVerticalTrackDrawable() {
    return mVerticalTrackDrawable;
}

19 Source : FastScroller.java
with GNU General Public License v2.0
from TelePlusDev

@VisibleForTesting
boolean isPointInsideVerticalThumb(float x, float y) {
    return (isLayoutRTL() ? x <= mVerticalThumbWidth / 2 : x >= mRecyclerViewWidth - mVerticalThumbWidth) && y >= mVerticalThumbCenterY - mVerticalThumbHeight / 2 && y <= mVerticalThumbCenterY + mVerticalThumbHeight / 2;
}

19 Source : FastScroller.java
with GNU General Public License v2.0
from TelePlusDev

@VisibleForTesting
boolean isHidden() {
    return mState == STATE_HIDDEN;
}

19 Source : FastScroller.java
with GNU General Public License v2.0
from TelePlusDev

@VisibleForTesting
boolean isVisible() {
    return mState == STATE_VISIBLE;
}

19 Source : ParsingVideoView.java
with GNU Lesser General Public License v2.1
from TedaLIEz

@VisibleForTesting
void setUrl(String url) {
    mUri = url;
}

19 Source : ParsingMediaManager.java
with GNU Lesser General Public License v2.1
from TedaLIEz

@VisibleForTesting
void playOrigin(String uri) {
    mCurrentPlayerProxy = quickCheckInMap(uri);
    mCurrentPlayerProxy.setVideoPath(uri);
}

19 Source : Extractor.java
with GNU Lesser General Public License v2.1
from TedaLIEz

@VisibleForTesting
private IVideoInfo extract(@NonNull Request request) {
    try {
        Response response = mClient.newCall(request).execute();
        VideoInfoImpl videoInfoImpl = createInfo(response);
        return cutDownVideoInfo(videoInfoImpl);
    } catch (IOException e) {
        e.printStackTrace();
    }
    throw new ExtractException("Can't extract video info");
}

19 Source : AttractionRepository.java
with Apache License 2.0
from SrChip15

@VisibleForTesting
static AttractionCollection buildBreweriesCollection() {
    ArrayList<Attraction> attractions = new ArrayList<>();
    attractions.add(new Attraction(R.drawable.new_belgium, R.string.new_belgium_replacedle, R.string.new_belgium_free_tours, R.string.new_belgium_detailed_desc, R.string.mq_new_belgium));
    attractions.add(new Attraction(R.drawable.odell_brewing, R.string.odell_brewing_replacedle, R.string.odell_microbrew, R.string.odell_brewing_detailed_desc, R.string.mq_odell_brewing));
    attractions.add(new Attraction(R.drawable.anheuser_busch, R.string.anheuser_busch_replacedle, R.string.grand_tour, R.string.anheuser_busch_detailed_desc, R.string.mq_anheuser_busch));
    attractions.add(new Attraction(R.drawable.coopersmith_brewing, R.string.coopersmith_replacedle, R.string.coopersmith_mixed_desc, R.string.coopersmith_detailed_desc, R.string.mq_coopersmith));
    return new AttractionCollection(R.string.top_breweries, attractions);
}

19 Source : AttractionRepository.java
with Apache License 2.0
from SrChip15

@VisibleForTesting
static AttractionCollection buildRestaurantsCollection() {
    ArrayList<Attraction> attractions = new ArrayList<>();
    attractions.add(new Attraction(R.drawable.the_melting_pot, R.string.melting_pot_replacedle, R.string.amazing_fondue, R.string.the_melting_pot_detailed_desc, R.string.mq_the_melting_pot));
    attractions.add(new Attraction(R.drawable.maza_kabob, R.string.maza_kabob_replacedle, R.string.afghan_specialty, R.string.maza_kabob_detailed_desc, R.string.mq_maza_kabob));
    attractions.add(new Attraction(R.drawable.rio_grande, R.string.rio_grande_replacedle, R.string.amazing_margarita, R.string.rio_grande_detailed_desc, R.string.mq_rio_grande));
    attractions.add(new Attraction(R.drawable.star_of_india, R.string.star_of_india_replacedle, R.string.indian_buffet, R.string.star_of_india_detailed_desc, R.string.mq_star_of_india));
    attractions.add(new Attraction(R.drawable.lucile_creole, R.string.lucile_replacedle, R.string.breakfast_place, R.string.lucile_creole_detailed_desc, R.string.mq_lucile));
    attractions.add(new Attraction(R.drawable.cafe_athens, R.string.cafe_athens_replacedle, R.string.greek_mediterranean, R.string.cafe_athens_detailed_desc, R.string.mq_cafe_athens));
    attractions.add(new Attraction(R.drawable.cafe_de_bangkok, R.string.cafe_de_bangkok_replacedle, R.string.traditional_thai, R.string.cafe_de_bangkok_detailed_desc, R.string.mq_cafe_de_bangkok));
    return new AttractionCollection(R.string.top_restaurants, attractions);
}

19 Source : AttractionRepository.java
with Apache License 2.0
from SrChip15

@VisibleForTesting
static AttractionCollection buildNightLifeCollection() {
    ArrayList<Attraction> attractions = new ArrayList<>();
    attractions.add(new Attraction(R.drawable.social, R.string.social_replacedle, R.string.creative_replacedtails, R.string.social_detailed_desc, R.string.mq_social));
    attractions.add(new Attraction(R.drawable.mayor_old_town, R.string.mayor_old_town_replacedle, R.string.mayor_great_selction, R.string.mayor_of_old_town_detailed_desc, R.string.mq_mayor_old_town));
    attractions.add(new Attraction(R.drawable.colorado_room, R.string.colorado_room_replacedle, R.string.colorado_beers_and_spirits, R.string.the_colorado_room_detailed_desc, R.string.mq_the_colorado_room));
    attractions.add(new Attraction(R.drawable.ace_gilletts, R.string.ace_gilletts_replacedle, R.string.gilletts_crafted_beers, R.string.ace_gilletts_detailed_desc, R.string.mq_ace_gilletts));
    attractions.add(new Attraction(R.drawable.elliot_martini_bar, R.string.elliots_martini_replacedle, R.string.elliot_martini_variety, R.string.elliot_martini_bar_detailed_desc, R.string.mq_elliot_martini_bar));
    return new AttractionCollection(R.string.top_bars_nightlife, attractions);
}

19 Source : SEDApp.java
with MIT License
from SoftwareEngineeringDaily

/**
 * Created by Kurian on 25-Sep-17.
 */
public clreplaced SEDApp extends Application {

    @VisibleForTesting
    public static AppComponent component;

    @Override
    public void onCreate() {
        super.onCreate();
        CalligraphyConfig.initDefault(new CalligraphyConfig.Builder().setDefaultFontPath("Roboto-RobotoRegular.ttf").setFontAttrId(R.attr.fontPath).build());
        initLeakCanary();
        initDependencies();
        createLogger();
        // Enable RxJava replacedembly stack collection, to make RxJava crash reports clear and unique
        // Make sure this is called AFTER setting up any Crash reporting mechanism as Crashlytics
        RxJava2Debug.enableRxJava2replacedemblyTracking(new String[] { BuildConfig.APPLICATION_ID });
    }

    private void initLeakCanary() {
        if (LeakCanary.isInreplacedyzerProcess(this)) {
            // This process is dedicated to LeakCanary for heap replacedysis.
            // You should not init your app in this process.
            return;
        }
        LeakCanary.install(this);
    }

    private void createLogger() {
        if (BuildConfig.DEBUG) {
            Timber.plant(new Timber.DebugTree());
        }
    }

    private void initDependencies() {
        if (component == null) {
            component = DaggerAppComponent.builder().appModule(new AppModule(this)).build();
        }
    }

    public static AppComponent component() {
        return component;
    }
}

19 Source : DatabaseManager.java
with GNU General Public License v3.0
from shymmq

@VisibleForTesting
public ReactiveEnreplacedyStore<Persistable> getDataStore() {
    return dataStore;
}

19 Source : ReplyRepository.java
with Apache License 2.0
from saket

@VisibleForTesting
void recycleOldDrafts(Map<String, ReplyDraft> allDrafts) {
    DateTime nowDateTime = DateTime.now(TimeZone.getTimeZone("UTC"));
    DateTime draftDateLimit = nowDateTime.minusDays(recycleDraftsOlderThanNumDays);
    long draftDateLimitMillis = draftDateLimit.getMilliseconds(TimeZone.getTimeZone("UTC"));
    SharedPreferences.Editor sharedPrefsEditor = sharedPrefs.edit();
    for (Map.Entry<String, ReplyDraft> entry : allDrafts.entrySet()) {
        ReplyDraft draftEntry = entry.getValue();
        if (draftEntry.createdTimeMillis() < draftDateLimitMillis) {
            // Stale draft.
            sharedPrefsEditor.remove(entry.getKey());
        }
    }
    sharedPrefsEditor.apply();
}

19 Source : ReplyRepository.java
with Apache License 2.0
from saket

@VisibleForTesting
static String keyForDraft(Identifiable contribution) {
    Preconditions.checkNotNull(contribution.getFullName(), "fullname");
    return "replyDraftFor_" + contribution.getFullName();
}

19 Source : GoogleMapsBottomSheetBehavior.java
with The Unlicense
from reline

@VisibleForTesting
private View findScrollingChild(View view) {
    if (ViewCompat.isNestedScrollingEnabled(view)) {
        return view;
    }
    if (view instanceof ViewGroup) {
        ViewGroup group = (ViewGroup) view;
        for (int i = 0, count = group.getChildCount(); i < count; i++) {
            View scrollingChild = findScrollingChild(group.getChildAt(i));
            if (scrollingChild != null) {
                return scrollingChild;
            }
        }
    }
    return null;
}

19 Source : GoogleMapsBottomSheetBehavior.java
with The Unlicense
from reline

@VisibleForTesting
private int getPeekHeightMin() {
    return mPeekHeightMin;
}

19 Source : OtherAnnotation.java
with Apache License 2.0
from RealMoMo

// =======================
// 3.VisibleForTesting
@VisibleForTesting
private void forTest() {
}

19 Source : MyBottomBehavior.java
with Apache License 2.0
from qwd

@VisibleForTesting
int getPeekHeightMin() {
    return this.peekHeightMin;
}

19 Source : MyBottomBehavior.java
with Apache License 2.0
from qwd

@VisibleForTesting
View findScrollingChild(View view) {
    if (ViewCompat.isNestedScrollingEnabled(view)) {
        return view;
    } else {
        if (view instanceof ViewGroup) {
            ViewGroup group = (ViewGroup) view;
            int i = 0;
            for (int count = group.getChildCount(); i < count; ++i) {
                View scrollingChild = this.findScrollingChild(group.getChildAt(i));
                if (scrollingChild != null) {
                    return scrollingChild;
                }
            }
        }
        return null;
    }
}

19 Source : ButterKnife.java
with Apache License 2.0
from qq542391099

/**
 * Field and method binding for Android views. Use this clreplaced to simplify finding views and
 * attaching listeners by binding them with annotations.
 * <p>
 * Finding views from your activity is as easy as:
 * <pre><code>
 * public clreplaced ExampleActivity extends Activity {
 *   {@literal @}BindView(R.id.replacedle) EditText replacedleView;
 *   {@literal @}BindView(R.id.subreplacedle) EditText subreplacedleView;
 *
 *   {@literal @}Override protected void onCreate(Bundle savedInstanceState) {
 *     super.onCreate(savedInstanceState);
 *     setContentView(R.layout.example_activity);
 *     ButterKnife.bind(this);
 *   }
 * }
 * Group multiple views together into a {@link List} or array.
 * <pre><code>
 * {@literal @}BindView({R.id.first_name, R.id.middle_name, R.id.last_name})
 * List<EditText> nameViews;
 * </code></pre>
 * <p>
 * To bind listeners to your views you can annotate your methods:
 * <pre><code>
 * {@literal @}OnClick(R.id.submit) void onSubmit() {
 *   // React to button click.
 * }
 * </code></pre>
 * Any number of parameters from the listener may be used on the method.
 * <pre><code>
 * {@literal @}OnItemClick(R.id.tweet_list) void onTweetClicked(int position) {
 *   // React to tweet click.
 * }
 * </code></pre>
 * <p>
 * Be default, views are required to be present in the layout for both field and method bindings.
 * If a view is optional add a {@code @Nullable} annotation for fields (such as the one in the
 * <a href="http://tools.android.com/tech-docs/support-annotations">support-annotations</a> library)
 * or the {@code @Optional} annotation for methods.
 * <pre><code>
 * {@literal @}Nullable @BindView(R.id.replacedle) TextView subreplacedleView;
 * </code></pre>
 * Resources can also be bound to fields to simplify programmatically working with views:
 * <pre><code>
 * {@literal @}BindBool(R.bool.is_tablet) boolean isTablet;
 * {@literal @}BindInt(R.integer.columns) int columns;
 * {@literal @}BindColor(R.color.error_red) int errorRed;
 * </code></pre>
 */
public final clreplaced ButterKnife {

    private ButterKnife() {
        throw new replacedertionError("No instances.");
    }

    private static final String TAG = "ButterKnife";

    private static boolean debug = false;

    @VisibleForTesting
    static final Map<Clreplaced<?>, Constructor<? extends Unbinder>> BINDINGS = new LinkedHashMap<>();

    /**
     * Control whether debug logging is enabled.
     */
    public static void setDebug(boolean debug) {
        ButterKnife.debug = debug;
    }

    /**
     * BindView annotated fields and methods in the specified {@link Activity}. The current content
     * view is used as the view root.
     *
     * @param target Target activity for view binding.
     */
    @NonNull
    @UiThread
    public static Unbinder bind(@NonNull Activity target) {
        View sourceView = target.getWindow().getDecorView();
        return createBinding(target, sourceView);
    }

    /**
     * BindView annotated fields and methods in the specified {@code target} using the {@code source}
     * {@link View} as the view root.
     *
     * @param target Target clreplaced for view binding.
     * @param source View root on which IDs will be looked up.
     */
    @NonNull
    @UiThread
    public static Unbinder bind(@NonNull Object target, @NonNull View source) {
        return createBinding(target, source);
    }

    @NonNull
    @UiThread
    public static View bind(@NonNull Fragment target, @NonNull LayoutInflater inflater, @NonNull ViewGroup container) {
        return (View) createFragmentBinding(target, inflater, container).getLayout();
    }

    private static Unbinder createFragmentBinding(@NonNull Object target, LayoutInflater inflater, ViewGroup container) {
        Constructor<? extends Unbinder> constructor = findBindingConstructorForClreplaced(target, false);
        if (constructor == null) {
            return Unbinder.EMPTY;
        }
        // noinspection TryWithIdenticalCatches Resolves to API 19+ only type.
        try {
            return constructor.newInstance(target, inflater, container, 0);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("Unable to invoke " + constructor, e);
        } catch (InstantiationException e) {
            throw new RuntimeException("Unable to invoke " + constructor, e);
        } catch (InvocationTargetException e) {
            Throwable cause = e.getCause();
            if (cause instanceof RuntimeException) {
                throw (RuntimeException) cause;
            }
            if (cause instanceof Error) {
                throw (Error) cause;
            }
            throw new RuntimeException("Unable to create binding instance.", cause);
        }
    }

    private static Unbinder createBinding(@NonNull Object target, @NonNull View source) {
        Constructor<? extends Unbinder> constructor = findBindingConstructorForClreplaced(target, true);
        if (constructor == null) {
            return Unbinder.EMPTY;
        }
        // noinspection TryWithIdenticalCatches Resolves to API 19+ only type.
        try {
            if (target instanceof Activity)
                return constructor.newInstance(target, source, 0);
            else
                // oldFragment
                return constructor.newInstance(target, source);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("Unable to invoke " + constructor, e);
        } catch (InstantiationException e) {
            throw new RuntimeException("Unable to invoke " + constructor, e);
        } catch (InvocationTargetException e) {
            Throwable cause = e.getCause();
            if (cause instanceof RuntimeException) {
                throw (RuntimeException) cause;
            }
            if (cause instanceof Error) {
                throw (Error) cause;
            }
            throw new RuntimeException("Unable to create binding instance.", cause);
        }
    }

    @Nullable
    @CheckResult
    @UiThread
    private static Constructor<? extends Unbinder> findBindingConstructorForClreplaced(Object target, boolean oldFragment) {
        Clreplaced<?> cls = target.getClreplaced();
        Constructor<? extends Unbinder> bindingCtor = BINDINGS.get(cls);
        if (bindingCtor != null) {
            if (debug)
                Log.d(TAG, "HIT: Cached in binding map.");
            return bindingCtor;
        }
        String clsName = cls.getName();
        if (clsName.startsWith("android.") || clsName.startsWith("java.")) {
            if (debug)
                Log.d(TAG, "MISS: Reached framework clreplaced. Abandoning search.");
            return null;
        }
        try {
            Clreplaced<?> bindingClreplaced = cls.getClreplacedLoader().loadClreplaced(clsName + "_ViewBinding");
            if (target instanceof Activity)
                bindingCtor = (Constructor<? extends Unbinder>) bindingClreplaced.getConstructor(cls, View.clreplaced, int.clreplaced);
            else if (target instanceof Fragment)
                if (oldFragment)
                    bindingCtor = (Constructor<? extends Unbinder>) bindingClreplaced.getConstructor(cls, View.clreplaced);
                else
                    bindingCtor = (Constructor<? extends Unbinder>) bindingClreplaced.getConstructor(cls, LayoutInflater.clreplaced, ViewGroup.clreplaced, int.clreplaced);
            else
                bindingCtor = (Constructor<? extends Unbinder>) bindingClreplaced.getConstructor(cls, View.clreplaced);
            if (debug)
                Log.d(TAG, "HIT: Loaded binding clreplaced and constructor.");
        } catch (ClreplacedNotFoundException e) {
            if (debug)
                Log.d(TAG, "Not found. Trying superclreplaced " + cls.getSuperclreplaced().getName());
            bindingCtor = findBindingConstructorForClreplaced(target, oldFragment);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException("Unable to find binding constructor for " + clsName, e);
        }
        BINDINGS.put(cls, bindingCtor);
        return bindingCtor;
    }

    /**
     * Simpler version of {@link View#findViewById(int)} which infers the target type.
     */
    // Checked by runtime cast. Public API.
    @SuppressWarnings({ "unchecked", "UnusedDeclaration" })
    @CheckResult
    public static <T extends View> T findById(@NonNull View view, @IdRes int id) {
        return (T) view.findViewById(id);
    }

    /**
     * Simpler version of {@link Activity#findViewById(int)} which infers the target type.
     */
    // Checked by runtime cast. Public API.
    @SuppressWarnings({ "unchecked", "UnusedDeclaration" })
    @CheckResult
    public static <T extends View> T findById(@NonNull Activity activity, @IdRes int id) {
        return (T) activity.findViewById(id);
    }

    /**
     * Simpler version of {@link Dialog#findViewById(int)} which infers the target type.
     */
    // Checked by runtime cast. Public API.
    @SuppressWarnings({ "unchecked", "UnusedDeclaration" })
    @CheckResult
    public static <T extends View> T findById(@NonNull Dialog dialog, @IdRes int id) {
        return (T) dialog.findViewById(id);
    }
}

See More Examples