Java tutorial
/** * * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * * 1. Definitions. * * "License" shall mean the terms and conditions for use, reproduction, * and distribution as defined by Sections 1 through 9 of this document. * * "Licensor" shall mean the copyright owner or entity authorized by * the copyright owner that is granting the License. * * "Legal Entity" shall mean the union of the acting entity and all * other entities that control, are controlled by, or are under common * control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the * direction or management of such entity, whether by contract or * otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * * "You" (or "Your") shall mean an individual or Legal Entity * exercising permissions granted by this License. * * "Source" form shall mean the preferred form for making modifications, * including but not limited to software source code, documentation * source, and configuration files. * * "Object" form shall mean any form resulting from mechanical * transformation or translation of a Source form, including but * not limited to compiled object code, generated documentation, * and conversions to other media types. * * "Work" shall mean the work of authorship, whether in Source or * Object form, made available under the License, as indicated by a * copyright notice that is included in or attached to the work * (an example is provided in the Appendix below). * * "Derivative Works" shall mean any work, whether in Source or Object * form, that is based on (or derived from) the Work and for which the * editorial revisions, annotations, elaborations, or other modifications * represent, as a whole, an original work of authorship. For the purposes * of this License, Derivative Works shall not include works that remain * separable from, or merely link (or bind by name) to the interfaces of, * the Work and Derivative Works thereof. * * "Contribution" shall mean any work of authorship, including * the original version of the Work and any modifications or additions * to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner * or by an individual or Legal Entity authorized to submit on behalf of * the copyright owner. For the purposes of this definition, "submitted" * means any form of electronic, verbal, or written communication sent * to the Licensor or its representatives, including but not limited to * communication on electronic mailing lists, source code control systems, * and issue tracking systems that are managed by, or on behalf of, the * Licensor for the purpose of discussing and improving the Work, but * excluding communication that is conspicuously marked or otherwise * designated in writing by the copyright owner as "Not a Contribution." * * "Contributor" shall mean Licensor and any individual or Legal Entity * on behalf of whom a Contribution has been received by Licensor and * subsequently incorporated within the Work. * * 2. Grant of Copyright License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * copyright license to reproduce, prepare Derivative Works of, * publicly display, publicly perform, sublicense, and distribute the * Work and such Derivative Works in Source or Object form. * * 3. Grant of Patent License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, * use, offer to sell, sell, import, and otherwise transfer the Work, * where such license applies only to those patent claims licensable * by such Contributor that are necessarily infringed by their * Contribution(s) alone or by combination of their Contribution(s) * with the Work to which such Contribution(s) was submitted. If You * institute patent litigation against any entity (including a * cross-claim or counterclaim in a lawsuit) alleging that the Work * or a Contribution incorporated within the Work constitutes direct * or contributory patent infringement, then any patent licenses * granted to You under this License for that Work shall terminate * as of the date such litigation is filed. * * 4. Redistribution. You may reproduce and distribute copies of the * Work or Derivative Works thereof in any medium, with or without * modifications, and in Source or Object form, provided that You * meet the following conditions: * * (a) You must give any other recipients of the Work or * Derivative Works a copy of this License; and * * (b) You must cause any modified files to carry prominent notices * stating that You changed the files; and * * (c) You must retain, in the Source form of any Derivative Works * that You distribute, all copyright, patent, trademark, and * attribution notices from the Source form of the Work, * excluding those notices that do not pertain to any part of * the Derivative Works; and * * (d) If the Work includes a "NOTICE" text file as part of its * distribution, then any Derivative Works that You distribute must * include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not * pertain to any part of the Derivative Works, in at least one * of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or * documentation, if provided along with the Derivative Works; or, * within a display generated by the Derivative Works, if and * wherever such third-party notices normally appear. The contents * of the NOTICE file are for informational purposes only and * do not modify the License. You may add Your own attribution * notices within Derivative Works that You distribute, alongside * or as an addendum to the NOTICE text from the Work, provided * that such additional attribution notices cannot be construed * as modifying the License. * * You may add Your own copyright statement to Your modifications and * may provide additional or different license terms and conditions * for use, reproduction, or distribution of Your modifications, or * for any such Derivative Works as a whole, provided Your use, * reproduction, and distribution of the Work otherwise complies with * the conditions stated in this License. * * 5. Submission of Contributions. Unless You explicitly state otherwise, * any Contribution intentionally submitted for inclusion in the Work * by You to the Licensor shall be under the terms and conditions of * this License, without any additional terms or conditions. * Notwithstanding the above, nothing herein shall supersede or modify * the terms of any separate license agreement you may have executed * with Licensor regarding such Contributions. * * 6. Trademarks. This License does not grant permission to use the trade * names, trademarks, service marks, or product names of the Licensor, * except as required for reasonable and customary use in describing the * origin of the Work and reproducing the content of the NOTICE file. * * 7. Disclaimer of Warranty. Unless required by applicable law or * agreed to in writing, Licensor provides the Work (and each * Contributor provides its Contributions) on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied, including, without limitation, any warranties or conditions * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the * appropriateness of using or redistributing the Work and assume any * risks associated with Your exercise of permissions under this License. * * 8. Limitation of Liability. In no event and under no legal theory, * whether in tort (including negligence), contract, or otherwise, * unless required by applicable law (such as deliberate and grossly * negligent acts) or agreed to in writing, shall any Contributor be * liable to You for damages, including any direct, indirect, special, * incidental, or consequential damages of any character arising as a * result of this License or out of the use or inability to use the * Work (including but not limited to damages for loss of goodwill, * work stoppage, computer failure or malfunction, or any and all * other commercial damages or losses), even if such Contributor * has been advised of the possibility of such damages. * * 9. Accepting Warranty or Additional Liability. While redistributing * the Work or Derivative Works thereof, You may choose to offer, * and charge a fee for, acceptance of support, warranty, indemnity, * or other liability obligations and/or rights consistent with this * License. However, in accepting such obligations, You may act only * on Your own behalf and on Your sole responsibility, not on behalf * of any other Contributor, and only if You agree to indemnify, * defend, and hold each Contributor harmless for any liability * incurred by, or claims asserted against, such Contributor by reason * of your accepting any such warranty or additional liability. * * END OF TERMS AND CONDITIONS * * APPENDIX: How to apply the Apache License to your work. * * To apply the Apache License to your work, attach the following * boilerplate notice, with the fields enclosed by brackets "[]" * replaced with your own identifying information. (Don't include * the brackets!) The text should be enclosed in the appropriate * comment syntax for the file format. We also recommend that a * file or class name and description of purpose be included on the * same "printed page" as the copyright notice for easier * identification within third-party archives. * * Copyright 2016 Alibaba Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.taobao.weex.ui.view.refresh.core; import android.animation.Animator; import android.animation.ValueAnimator; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Color; import android.os.Build; import android.support.v4.view.NestedScrollingParent; import android.support.v4.view.NestedScrollingParentHelper; import android.support.v4.view.ViewCompat; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.TypedValue; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.widget.AbsListView; import android.widget.FrameLayout; public class WXSwipeLayout extends FrameLayout implements NestedScrollingParent { private NestedScrollingParentHelper parentHelper; private WXOnRefreshListener onRefreshListener; private WXOnLoadingListener onLoadingListener; /** * On refresh Callback, call on start refresh */ public interface WXOnRefreshListener { void onRefresh(); void onPullingDown(float dy, int pullOutDistance, float viewHeight); } /** * On loadmore Callback, call on start loadmore */ public interface WXOnLoadingListener { void onLoading(); void onPullingUp(float dy, int pullOutDistance, float viewHeight); } static class WXRefreshAnimatorListener implements Animator.AnimatorListener { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } } private WXRefreshView headerView; private WXRefreshView footerView; private View mTargetView; private static final int INVALID = -1; private static final int PULL_REFRESH = 0; private static final int LOAD_MORE = 1; // Enable PullRefresh and Loadmore private boolean mPullRefreshEnable = false; private boolean mPullLoadEnable = false; // Is Refreshing volatile private boolean mRefreshing = false; // RefreshView Height private volatile float refreshViewHeight = 0; private volatile float loadingViewHeight = 0; // RefreshView Over Flow Height private volatile float refreshViewFlowHeight = 0; private volatile float loadingViewFlowHeight = 0; private static final float overFlow = 1.0f; private static final float DAMPING = 0.4f; // Drag Action private int mCurrentAction = -1; private boolean isConfirm = false; // RefreshView Attrs private int mRefreshViewBgColor; private int mProgressBgColor; private int mProgressColor; public WXSwipeLayout(Context context) { super(context); initAttrs(context, null); } public WXSwipeLayout(Context context, AttributeSet attrs) { super(context, attrs); initAttrs(context, attrs); } public WXSwipeLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initAttrs(context, attrs); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public WXSwipeLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); initAttrs(context, attrs); } private void initAttrs(Context context, AttributeSet attrs) { if (getChildCount() > 1) { throw new RuntimeException("WXSwipeLayout should not have more than one child"); } parentHelper = new NestedScrollingParentHelper(this); if (isInEditMode() && attrs == null) { return; } mRefreshViewBgColor = Color.TRANSPARENT; mProgressBgColor = Color.TRANSPARENT; mProgressColor = Color.RED; } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); mTargetView = getChildAt(0); setRefreshView(); } /** * Init refresh view or loading view */ private void setRefreshView() { // SetUp HeaderView FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, 0); headerView = new WXRefreshView(getContext()); headerView.setStartEndTrim(0, 0.75f); headerView.setBackgroundColor(mRefreshViewBgColor); headerView.setProgressBgColor(mProgressBgColor); headerView.setProgressColor(mProgressColor); headerView.setContentGravity(Gravity.BOTTOM); addView(headerView, lp); // SetUp FooterView lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, 0); lp.gravity = Gravity.BOTTOM; footerView = new WXRefreshView(getContext()); footerView.setStartEndTrim(0.5f, 1.25f); footerView.setBackgroundColor(mRefreshViewBgColor); footerView.setProgressBgColor(mProgressBgColor); footerView.setProgressColor(mProgressColor); footerView.setContentGravity(Gravity.TOP); addView(footerView, lp); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { if ((!mPullRefreshEnable && !mPullLoadEnable)) { return false; } return super.onInterceptTouchEvent(ev); } /*********************************** NestedScrollParent *************************************/ @Override public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) { return true; } @Override public void onNestedScrollAccepted(View child, View target, int axes) { parentHelper.onNestedScrollAccepted(child, target, axes); } /** * Callback on TouchEvent.ACTION_CANCLE or TouchEvent.ACTION_UP * handler : refresh or loading * @param child : child view of SwipeLayout,RecyclerView or Scroller */ @Override public void onStopNestedScroll(View child) { parentHelper.onStopNestedScroll(child); handlerAction(); } /** * With child view to processing move events * @param target the child view * @param dx move x * @param dy move y * @param consumed parent consumed move distance */ @Override public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) { if ((!mPullRefreshEnable && !mPullLoadEnable)) { return; } dy = (int) calculateDistanceY(target, dy); if (!isConfirm) { if (dy < 0 && !canChildScrollUp()) { mCurrentAction = PULL_REFRESH; isConfirm = true; } else if (dy > 0 && !canChildScrollDown()) { mCurrentAction = LOAD_MORE; isConfirm = true; } } if (moveSpinner(-dy)) { consumed[1] += dy; } } @Override public void onNestedScroll(View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) { } @Override public int getNestedScrollAxes() { return parentHelper.getNestedScrollAxes(); } @Override public boolean onNestedPreFling(View target, float velocityX, float velocityY) { return false; } @Override public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) { return false; } private double calculateDistanceY(View target, int dy) { int viewHeight = target.getMeasuredHeight(); double ratio = (viewHeight - Math.abs(target.getY())) / 1.0d / viewHeight * DAMPING; if (ratio <= 0.01d) { //Filter tiny scrolling action ratio = 0.01d; } return ratio * dy; } /** * Adjust the refresh or loading view according to the size of the gesture * * @param distanceY move distance of Y */ private boolean moveSpinner(float distanceY) { if (mRefreshing) { return false; } if (!canChildScrollUp() && mPullRefreshEnable && mCurrentAction == PULL_REFRESH) { // Pull Refresh LayoutParams lp = (LayoutParams) headerView.getLayoutParams(); lp.height += distanceY; if (lp.height < 0) { lp.height = 0; } if (lp.height == 0) { isConfirm = false; mCurrentAction = INVALID; } headerView.setLayoutParams(lp); onRefreshListener.onPullingDown(distanceY, lp.height, refreshViewFlowHeight); headerView.setProgressRotation(lp.height / refreshViewFlowHeight); moveTargetView(lp.height); return true; } else if (!canChildScrollDown() && mPullLoadEnable && mCurrentAction == LOAD_MORE) { // Load more LayoutParams lp = (LayoutParams) footerView.getLayoutParams(); lp.height -= distanceY; if (lp.height < 0) { lp.height = 0; } if (lp.height == 0) { isConfirm = false; mCurrentAction = INVALID; } footerView.setLayoutParams(lp); onLoadingListener.onPullingUp(distanceY, lp.height, loadingViewFlowHeight); footerView.setProgressRotation(lp.height / loadingViewFlowHeight); moveTargetView(-lp.height); return true; } return false; } /** * Adjust contentView(Scroller or List) at refresh or loading time * @param h Height of refresh view or loading view */ private void moveTargetView(float h) { mTargetView.setTranslationY(h); } /** * Decide on the action refresh or loadmore */ private void handlerAction() { if (isRefreshing()) { return; } isConfirm = false; LayoutParams lp; if (mPullRefreshEnable && mCurrentAction == PULL_REFRESH) { lp = (LayoutParams) headerView.getLayoutParams(); if (lp.height >= refreshViewHeight) { startRefresh(lp.height); } else if (lp.height > 0) { resetHeaderView(lp.height); } else { resetRefreshState(); } } if (mPullLoadEnable && mCurrentAction == LOAD_MORE) { lp = (LayoutParams) footerView.getLayoutParams(); if (lp.height >= loadingViewHeight) { startLoadmore(lp.height); } else if (lp.height > 0) { resetFootView(lp.height); } else { resetLoadmoreState(); } } } /** * Start Refresh * @param headerViewHeight */ private void startRefresh(int headerViewHeight) { mRefreshing = true; ValueAnimator animator = ValueAnimator.ofFloat(headerViewHeight, refreshViewHeight); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { LayoutParams lp = (LayoutParams) headerView.getLayoutParams(); lp.height = (int) ((Float) animation.getAnimatedValue()).floatValue(); headerView.setLayoutParams(lp); moveTargetView(lp.height); } }); animator.addListener(new WXRefreshAnimatorListener() { @Override public void onAnimationEnd(Animator animation) { headerView.startAnimation(); //TODO updateLoadText if (onRefreshListener != null) { onRefreshListener.onRefresh(); } } }); animator.setDuration(300); animator.start(); } /** * Reset refresh state * @param headerViewHeight */ private void resetHeaderView(int headerViewHeight) { headerView.stopAnimation(); headerView.setStartEndTrim(0, 0.75f); ValueAnimator animator = ValueAnimator.ofFloat(headerViewHeight, 0); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { LayoutParams lp = (LayoutParams) headerView.getLayoutParams(); lp.height = (int) ((Float) animation.getAnimatedValue()).floatValue(); headerView.setLayoutParams(lp); moveTargetView(lp.height); } }); animator.addListener(new WXRefreshAnimatorListener() { @Override public void onAnimationEnd(Animator animation) { resetRefreshState(); } }); animator.setDuration(300); animator.start(); } private void resetRefreshState() { mRefreshing = false; isConfirm = false; mCurrentAction = -1; //TODO updateLoadText } /** * Start loadmore * @param headerViewHeight */ private void startLoadmore(int headerViewHeight) { mRefreshing = true; ValueAnimator animator = ValueAnimator.ofFloat(headerViewHeight, loadingViewHeight); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { LayoutParams lp = (LayoutParams) footerView.getLayoutParams(); lp.height = (int) ((Float) animation.getAnimatedValue()).floatValue(); footerView.setLayoutParams(lp); moveTargetView(-lp.height); } }); animator.addListener(new WXRefreshAnimatorListener() { @Override public void onAnimationEnd(Animator animation) { footerView.startAnimation(); //TODO updateLoadText if (onLoadingListener != null) { onLoadingListener.onLoading(); } } }); animator.setDuration(300); animator.start(); } /** * Reset loadmore state * @param headerViewHeight */ private void resetFootView(int headerViewHeight) { footerView.stopAnimation(); footerView.setStartEndTrim(0.5f, 1.25f); ValueAnimator animator = ValueAnimator.ofFloat(headerViewHeight, 0); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { LayoutParams lp = (LayoutParams) footerView.getLayoutParams(); lp.height = (int) ((Float) animation.getAnimatedValue()).floatValue(); footerView.setLayoutParams(lp); moveTargetView(-lp.height); } }); animator.addListener(new WXRefreshAnimatorListener() { @Override public void onAnimationEnd(Animator animation) { resetLoadmoreState(); } }); animator.setDuration(300); animator.start(); } private void resetLoadmoreState() { mRefreshing = false; isConfirm = false; mCurrentAction = -1; //TODO updateLoadText } /** * Whether child view can scroll up * @return */ public boolean canChildScrollUp() { if (mTargetView == null) { return false; } if (Build.VERSION.SDK_INT < 14) { if (mTargetView instanceof AbsListView) { final AbsListView absListView = (AbsListView) mTargetView; return absListView.getChildCount() > 0 && (absListView.getFirstVisiblePosition() > 0 || absListView.getChildAt(0).getTop() < absListView.getPaddingTop()); } else { return ViewCompat.canScrollVertically(mTargetView, -1) || mTargetView.getScrollY() > 0; } } else { return ViewCompat.canScrollVertically(mTargetView, -1); } } /** * Whether child view can scroll down * @return */ public boolean canChildScrollDown() { if (mTargetView == null) { return false; } if (Build.VERSION.SDK_INT < 14) { if (mTargetView instanceof AbsListView) { final AbsListView absListView = (AbsListView) mTargetView; if (absListView.getChildCount() > 0) { int lastChildBottom = absListView.getChildAt(absListView.getChildCount() - 1).getBottom(); return absListView.getLastVisiblePosition() == absListView.getAdapter().getCount() - 1 && lastChildBottom <= absListView.getMeasuredHeight(); } else { return false; } } else { return ViewCompat.canScrollVertically(mTargetView, 1) || mTargetView.getScrollY() > 0; } } else { return ViewCompat.canScrollVertically(mTargetView, 1); } } public float dipToPx(Context context, float value) { DisplayMetrics metrics = context.getResources().getDisplayMetrics(); return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, metrics); } public void setOnLoadingListener(WXOnLoadingListener onLoadingListener) { this.onLoadingListener = onLoadingListener; } public void setOnRefreshListener(WXOnRefreshListener onRefreshListener) { this.onRefreshListener = onRefreshListener; } /** * Callback on refresh finish */ public void finishPullRefresh() { if (mCurrentAction == PULL_REFRESH) { resetHeaderView(headerView == null ? 0 : headerView.getMeasuredHeight()); } } /** * Callback on loadmore finish */ public void finishPullLoad() { if (mCurrentAction == LOAD_MORE) { resetFootView(footerView == null ? 0 : footerView.getMeasuredHeight()); } } public WXRefreshView getHeaderView() { return headerView; } public WXRefreshView getFooterView() { return footerView; } public boolean isPullLoadEnable() { return mPullLoadEnable; } public void setPullLoadEnable(boolean mPullLoadEnable) { this.mPullLoadEnable = mPullLoadEnable; } public boolean isPullRefreshEnable() { return mPullRefreshEnable; } public void setPullRefreshEnable(boolean mPullRefreshEnable) { this.mPullRefreshEnable = mPullRefreshEnable; } public boolean isRefreshing() { return mRefreshing; } public void setRefreshHeight(int height) { refreshViewHeight = height; refreshViewFlowHeight = refreshViewHeight * overFlow; } public void setLoadingHeight(int height) { loadingViewHeight = height; loadingViewFlowHeight = loadingViewHeight * overFlow; } public void setRefreshBgColor(int color) { headerView.setBackgroundColor(color); } public void setLoadingBgColor(int color) { footerView.setBackgroundColor(color); } }