├── .gitignore ├── LICENSE ├── README.md ├── build.gradle ├── card.gif ├── cardstackview ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── me │ │ └── brucezz │ │ └── cardstackview │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── me │ │ │ └── brucezz │ │ │ └── cardstackview │ │ │ ├── AnimationCancelListener.java │ │ │ ├── CardAdapter.java │ │ │ ├── CardFactory.java │ │ │ ├── CardHolder.java │ │ │ ├── CardStackView.java │ │ │ ├── Options.java │ │ │ ├── SlidingResistanceCalculator.java │ │ │ ├── Util.java │ │ │ └── ViewUpdateListener.java │ └── res │ │ └── values │ │ ├── attrs.xml │ │ └── strings.xml │ └── test │ └── java │ └── me │ └── brucezz │ └── cardstackview │ └── ExampleUnitTest.java ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── sample ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── me │ │ └── brucezz │ │ └── sample │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── me │ │ │ └── brucezz │ │ │ └── sample │ │ │ ├── Card.java │ │ │ ├── DetailActivity.java │ │ │ ├── DisplayUtil.java │ │ │ ├── MainActivity.java │ │ │ └── SimpleCardAdapter.java │ └── res │ │ ├── drawable-hdpi │ │ ├── calendar.png │ │ ├── knowledge.png │ │ ├── post.png │ │ └── task.png │ │ ├── layout │ │ ├── activity_detail.xml │ │ ├── activity_main.xml │ │ └── item_card.xml │ │ ├── menu │ │ └── menu_main.xml │ │ ├── mipmap-hdpi │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxxhdpi │ │ └── ic_launcher.png │ │ ├── values-w820dp │ │ └── dimens.xml │ │ └── values │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── me │ └── brucezz │ └── sample │ └── ExampleUnitTest.java └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea 5 | .DS_Store 6 | /build 7 | /captures 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CardStackView 2 | 3 | [![](https://jitpack.io/v/brucezz/CardStackView.svg)](https://jitpack.io/#brucezz/CardStackView) 4 | 5 | ![](card.gif) 6 | 7 | ## Installation 8 | 9 | **Step 1.** Add the JitPack repository to your build file 10 | 11 | Add it in your root build.gradle at the end of repositories: 12 | 13 | ```groovy 14 | allprojects { 15 | repositories { 16 | ... 17 | maven { url "https://jitpack.io" } 18 | } 19 | } 20 | ``` 21 | 22 | **Step 2.** Add the dependency 23 | 24 | ```groovy 25 | dependencies { 26 | compile 'com.github.brucezz:CardStackView:1.3' 27 | } 28 | ``` 29 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | repositories { 5 | jcenter() 6 | } 7 | dependencies { 8 | classpath 'com.android.tools.build:gradle:2.2.2' 9 | classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5' 10 | 11 | // NOTE: Do not place your application dependencies here; they belong 12 | // in the individual module build.gradle files 13 | } 14 | } 15 | 16 | allprojects { 17 | repositories { 18 | jcenter() 19 | } 20 | } 21 | 22 | task clean(type: Delete) { 23 | delete rootProject.buildDir 24 | } 25 | -------------------------------------------------------------------------------- /card.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bruce3x/CardStackView/7990803a0ffa479dfe7a86b01ecf4f4093a73fc5/card.gif -------------------------------------------------------------------------------- /cardstackview/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /cardstackview/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'com.github.dcendents.android-maven' 3 | 4 | group = 'com.github.brucezz' 5 | 6 | android { 7 | compileSdkVersion 24 8 | buildToolsVersion "24.0.0" 9 | 10 | defaultConfig { 11 | minSdkVersion 14 12 | targetSdkVersion 24 13 | versionCode 5 14 | versionName "1.4.1" 15 | } 16 | buildTypes { 17 | release { 18 | minifyEnabled false 19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 20 | } 21 | } 22 | } 23 | 24 | dependencies { 25 | compile fileTree(dir: 'libs', include: ['*.jar']) 26 | compile 'com.android.support:appcompat-v7:24.2.1' 27 | testCompile 'junit:junit:4.12' 28 | } 29 | // 指定编码 30 | tasks.withType(JavaCompile) { 31 | options.encoding = "UTF-8" 32 | } 33 | 34 | // 打包源码 35 | task sourcesJar(type: Jar) { 36 | from android.sourceSets.main.java.srcDirs 37 | classifier = 'sources' 38 | } 39 | 40 | artifacts { 41 | archives sourcesJar 42 | } -------------------------------------------------------------------------------- /cardstackview/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/bruce/Library/Android/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /cardstackview/src/androidTest/java/me/brucezz/cardstackview/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package me.brucezz.cardstackview; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumentation test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() throws Exception { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("me.brucezz.cardstackview.test", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /cardstackview/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /cardstackview/src/main/java/me/brucezz/cardstackview/AnimationCancelListener.java: -------------------------------------------------------------------------------- 1 | package me.brucezz.cardstackview; 2 | 3 | import android.animation.Animator; 4 | 5 | /** 6 | * Created by brucezz on 2016-10-12. 7 | * Github: https://github.com/brucezz 8 | * Email: im.brucezz@gmail.com 9 | */ 10 | 11 | public class AnimationCancelListener implements Animator.AnimatorListener { 12 | private CardHolder mRunning; 13 | private CardHolder mDragging; 14 | 15 | public AnimationCancelListener(CardHolder running, CardHolder dragging) { 16 | mRunning = running; 17 | mDragging = dragging; 18 | } 19 | 20 | @Override 21 | public void onAnimationStart(Animator animation) { 22 | } 23 | 24 | @Override 25 | public void onAnimationEnd(Animator animation) { 26 | } 27 | 28 | @Override 29 | public void onAnimationCancel(Animator animation) { 30 | if (mDragging != null && !mRunning.mDrawOrderUpdated) { 31 | mRunning.updateDrawOrder(mDragging); 32 | } 33 | } 34 | 35 | @Override 36 | public void onAnimationRepeat(Animator animation) { 37 | 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /cardstackview/src/main/java/me/brucezz/cardstackview/CardAdapter.java: -------------------------------------------------------------------------------- 1 | package me.brucezz.cardstackview; 2 | 3 | import android.database.DataSetObservable; 4 | import android.database.DataSetObserver; 5 | import android.view.View; 6 | import android.view.ViewGroup; 7 | 8 | /** 9 | * Created by brucezz on 2016-10-12. 10 | * Github: https://github.com/brucezz 11 | * Email: im.brucezz@gmail.com 12 | */ 13 | 14 | public abstract class CardAdapter { 15 | /** 16 | * 会在 {@link CardStackView} 初始化的时候把所有的 View 都初始化添加进去 17 | */ 18 | public abstract View getView(View oldView, int position, ViewGroup parent); 19 | 20 | /** 21 | * 获取 View 的数量 22 | */ 23 | public abstract int getItemCount(); 24 | 25 | /** 26 | * 获取卡片的排序位置 27 | * 如 原始第 1 张卡片,现在要摆放在第 3 的位置 28 | * 则 getOrder(1) return 3; 29 | * 30 | * @param position 原始卡片的位置 31 | * @return 当前排序所处的位置 32 | */ 33 | public abstract int getOrder(int position); 34 | 35 | private final DataSetObservable mObservable = new DataSetObservable(); 36 | 37 | public final void notifyDataSetChanged() { 38 | mObservable.notifyChanged(); 39 | } 40 | 41 | public void registerDataSetObserver(DataSetObserver observer) { 42 | mObservable.registerObserver(observer); 43 | } 44 | 45 | public void unregisterDataSetObserver(DataSetObserver observer) { 46 | mObservable.unregisterObserver(observer); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /cardstackview/src/main/java/me/brucezz/cardstackview/CardFactory.java: -------------------------------------------------------------------------------- 1 | package me.brucezz.cardstackview; 2 | 3 | import android.support.annotation.NonNull; 4 | import android.view.View; 5 | import android.view.ViewGroup; 6 | import java.util.ArrayList; 7 | import java.util.Arrays; 8 | import java.util.Collections; 9 | import java.util.List; 10 | 11 | /** 12 | * Created by brucezz on 2016-10-12. 13 | * Github: https://github.com/brucezz 14 | * Email: im.brucezz@gmail.com 15 | */ 16 | 17 | public class CardFactory { 18 | private ArrayList mCardHolders = new ArrayList<>(); 19 | 20 | private Options mOptions; 21 | private ViewGroup mParent; 22 | 23 | public CardFactory(ViewGroup parent, Options options, int count) { 24 | mParent = parent; 25 | mOptions = options; 26 | for (int i = 0; i < count; i++) { 27 | mCardHolders.add(null);// 添加 null 占位 28 | } 29 | } 30 | 31 | public void add(int orderIndex, int childIndex, View child) { 32 | if (mCardHolders.size() > orderIndex && mCardHolders.get(orderIndex) != null) { 33 | throw new IllegalArgumentException("You have put a card to order #%d" + orderIndex); 34 | } 35 | mCardHolders.set(orderIndex, new CardHolder(mParent, child, childIndex, orderIndex, mOptions)); 36 | } 37 | 38 | public int size() { 39 | return mCardHolders.size(); 40 | } 41 | 42 | public CardHolder get(int index) { 43 | return mCardHolders.get(index); 44 | } 45 | 46 | public CardHolder findByView(@NonNull View view) { 47 | for (CardHolder holder : mCardHolders) { 48 | if (view.equals(holder.mView)) { 49 | return holder; 50 | } 51 | } 52 | return null; 53 | } 54 | 55 | public CardHolder findByDrawOrder(int order) { 56 | for (CardHolder holder : mCardHolders) { 57 | if (order == holder.mDrawOrder) { 58 | return holder; 59 | } 60 | } 61 | return null; 62 | } 63 | 64 | public CardHolder findByRealIndex(int index) { 65 | for (CardHolder holder : mCardHolders) { 66 | if (index == holder.mRealIndex) { 67 | return holder; 68 | } 69 | } 70 | return null; 71 | } 72 | 73 | public CardHolder findByTouch(float touchY) { 74 | if (mCardHolders.size() == 0) return null; 75 | 76 | int index; 77 | int count = mCardHolders.size() - 1; 78 | int span = count * mOptions.CARD_SPAN_CURRENT; 79 | if (touchY > span + mOptions.CARD_HEIGHT) { 80 | return null; 81 | } else if (touchY > span) { 82 | index = count; 83 | } else { 84 | index = (int) Math.floor(touchY / mOptions.CARD_SPAN_CURRENT); 85 | } 86 | 87 | return findByRealIndex(index); 88 | } 89 | 90 | public void swapRealIndex(int one, int another) { 91 | Collections.swap(mCardHolders, one, another); 92 | mCardHolders.get(one).mRealIndex = one; 93 | mCardHolders.get(another).mRealIndex = another; 94 | } 95 | 96 | public List getAllPosition() { 97 | Integer[] orders = new Integer[mCardHolders.size()]; 98 | for (int i = 0; i < mCardHolders.size(); i++) { 99 | int childIndex = mCardHolders.get(i).mChildIndex; 100 | orders[childIndex] = i; 101 | } 102 | 103 | return Arrays.asList(orders); 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /cardstackview/src/main/java/me/brucezz/cardstackview/CardHolder.java: -------------------------------------------------------------------------------- 1 | package me.brucezz.cardstackview; 2 | 3 | import android.animation.ValueAnimator; 4 | import android.view.View; 5 | import android.view.ViewGroup; 6 | import android.view.animation.OvershootInterpolator; 7 | 8 | /** 9 | * Created by brucezz on 2016-10-12. 10 | * Github: https://github.com/brucezz 11 | * Email: im.brucezz@gmail.com 12 | */ 13 | 14 | public class CardHolder { 15 | private static final String TAG = "CardHolder"; 16 | 17 | public ViewGroup mParent; 18 | 19 | public View mView; 20 | /** 21 | * 在 ViewGroup 中的位置 22 | */ 23 | public int mChildIndex; 24 | /** 25 | * 卡片位置 26 | */ 27 | public int mRealIndex; 28 | 29 | /** 30 | * 绘制顺序 31 | */ 32 | public int mDrawOrder; 33 | 34 | /** 35 | * 绘制顺序是否已更新 36 | */ 37 | public boolean mDrawOrderUpdated; 38 | 39 | /** 40 | * 正在执行的动画 41 | */ 42 | public ValueAnimator mRunningAnimator; 43 | 44 | public Options mOptions; 45 | 46 | public CardHolder(ViewGroup parent, View view, int childIndex, int realIndex, Options options) { 47 | this.mParent = parent; 48 | this.mView = view; 49 | this.mChildIndex = childIndex; 50 | this.mRealIndex = realIndex; 51 | this.mDrawOrder = realIndex; 52 | this.mOptions = options; 53 | } 54 | 55 | public int getFixedLeft() { 56 | return mParent.getPaddingLeft(); 57 | } 58 | 59 | public int getFixedRight() { 60 | return getFixedLeft() + mView.getMeasuredWidth(); 61 | } 62 | 63 | public int getFixedTop() { 64 | return mParent.getPaddingTop() + mRealIndex * mOptions.CARD_SPAN_CURRENT; 65 | } 66 | 67 | public int getFixedBottom() { 68 | return getFixedTop() + mOptions.CARD_HEIGHT; 69 | } 70 | 71 | /** 72 | * 固定位置 73 | */ 74 | public void layoutFixed() { 75 | this.mView.layout(getFixedLeft(), getFixedTop(), getFixedRight(), getFixedBottom()); 76 | } 77 | 78 | /** 79 | * View 重置到某位置 80 | */ 81 | public void reset() { 82 | checkIfAnimatorRunning(); 83 | 84 | final int start = this.mView.getTop(); 85 | final int end = getFixedTop(); 86 | 87 | mRunningAnimator = ValueAnimator.ofFloat(0f, 1f).setDuration(mOptions.CARD_RESET_DURATION); 88 | mRunningAnimator.addUpdateListener(new ViewUpdateListener(this, null, start, end, end)); 89 | mRunningAnimator.start(); 90 | } 91 | 92 | /** 93 | * 如果正在执行动画,取消掉 94 | */ 95 | private void checkIfAnimatorRunning() { 96 | if (isAnimating()) { 97 | mRunningAnimator.cancel(); 98 | } 99 | } 100 | 101 | /** 102 | * 两段位移运动,根据进度计算更新位置 103 | */ 104 | public void updateView(CardHolder dragging, int start, int mid, int end, float percent) { 105 | 106 | int firstDown = mid - start; 107 | int thenUp = mid - end; 108 | 109 | int total = firstDown + thenUp; 110 | float corner = ((float) firstDown) / total; // 转折点 111 | 112 | if (dragging != null && percent > corner && !mDrawOrderUpdated) { 113 | // 更新卡片的绘制顺序 114 | updateDrawOrder(dragging); 115 | } 116 | 117 | int dy; 118 | if (percent <= corner) { 119 | dy = (int) (percent / corner * firstDown); 120 | } else { 121 | dy = (int) (firstDown - (percent - corner) / (1 - corner) * thenUp); 122 | } 123 | 124 | mView.layout(getFixedLeft(), start + dy, getFixedRight(), start + dy + mOptions.CARD_HEIGHT); 125 | } 126 | 127 | /** 128 | * 更新卡片的绘制顺序, 跟 mRealIndex 是一致的 129 | */ 130 | public void updateDrawOrder(CardHolder dragging) { 131 | this.mDrawOrder = this.mRealIndex; 132 | if (dragging == null) return; 133 | dragging.mDrawOrder = dragging.mRealIndex; 134 | } 135 | 136 | /** 137 | * 触发交换动画 138 | */ 139 | public void onSwap(final CardHolder dragging) { 140 | checkIfAnimatorRunning(); 141 | 142 | boolean up = dragging.mRealIndex < this.mRealIndex; 143 | 144 | final int directionFlag = up ? 1 : -1; 145 | final int downDistance = 146 | (int) (mOptions.CARD_HEIGHT - (1 - mOptions.CARD_SWAP_THRESHOLD) * mOptions.CARD_SPAN_CURRENT * directionFlag); 147 | final int upDistance = 148 | (int) (mOptions.CARD_HEIGHT + mOptions.CARD_SWAP_THRESHOLD * mOptions.CARD_SPAN_CURRENT * directionFlag); 149 | 150 | final int start = this.mView.getTop(); 151 | final int mid = getFixedTop() + downDistance; 152 | final int end = mid - upDistance; 153 | 154 | mDrawOrderUpdated = false; 155 | 156 | mRunningAnimator = ValueAnimator.ofFloat(0f, 1f); 157 | mRunningAnimator.setDuration(mOptions.CARD_SWAP_DURATION); 158 | mRunningAnimator.addUpdateListener(new ViewUpdateListener(this, dragging, start, mid, end)); 159 | mRunningAnimator.addListener(new AnimationCancelListener(this, dragging)); 160 | mRunningAnimator.setInterpolator(new OvershootInterpolator(1f)); 161 | mRunningAnimator.start(); 162 | } 163 | 164 | /** 165 | * 判断是否在执行动画 166 | */ 167 | public boolean isAnimating() { 168 | return mRunningAnimator != null && mRunningAnimator.isRunning(); 169 | } 170 | 171 | /** 172 | * 被选中时上浮动画 173 | */ 174 | public void onSelect() { 175 | 176 | final int start = this.mView.getTop(); 177 | final int end = start - mOptions.CARD_FLOAT_UP; 178 | 179 | mRunningAnimator = ValueAnimator.ofFloat(0f, 1f).setDuration(mOptions.CARD_FLOAT_DURATION); 180 | mRunningAnimator.addUpdateListener(new ViewUpdateListener(this, null, start, end, end)); 181 | mRunningAnimator.start(); 182 | } 183 | } 184 | -------------------------------------------------------------------------------- /cardstackview/src/main/java/me/brucezz/cardstackview/CardStackView.java: -------------------------------------------------------------------------------- 1 | package me.brucezz.cardstackview; 2 | 3 | import android.animation.ValueAnimator; 4 | import android.content.Context; 5 | import android.content.res.TypedArray; 6 | import android.database.DataSetObserver; 7 | import android.support.v4.view.GestureDetectorCompat; 8 | import android.support.v4.widget.ViewDragHelper; 9 | import android.util.AttributeSet; 10 | import android.view.GestureDetector; 11 | import android.view.MotionEvent; 12 | import android.view.View; 13 | import android.view.ViewGroup; 14 | import android.view.animation.OvershootInterpolator; 15 | import java.util.List; 16 | 17 | /** 18 | * Created by brucezz on 2016-10-08. 19 | * Github: https://github.com/brucezz 20 | * Email: im.brucezz@gmail.com 21 | */ 22 | 23 | public class CardStackView extends ViewGroup { 24 | private static final String TAG = "CardStackView"; 25 | 26 | private final DataSetObserver mObserver = new CardStackViewDataObserver(); 27 | 28 | private CardFactory mCardFactory; 29 | private Options mOptions; 30 | 31 | private CardAdapter mCardAdapter; 32 | 33 | private ViewDragHelper mViewDragHelper; 34 | private GestureDetectorCompat mGestureDetector; 35 | private OnCardClickListener mOnCardClickListener; 36 | private OnPositionChangedListener mOnPositionChangedListener; 37 | /** 38 | * 阻力滑动计算 39 | */ 40 | private SlidingResistanceCalculator mSlidingResistanceCalculator; 41 | 42 | private CardHolder mSelected; 43 | 44 | private boolean mSkipLayout = false; 45 | private boolean mSkipTouch = false; 46 | private int mCardHeight; 47 | private int mCardMinSpan; 48 | 49 | public void setSkipLayout(boolean skipLayout) { 50 | mSkipLayout = skipLayout; 51 | } 52 | 53 | public void setSkipTouch(boolean skipTouch) { 54 | mSkipTouch = skipTouch; 55 | } 56 | 57 | public CardStackView(Context context) { 58 | this(context, null); 59 | } 60 | 61 | public CardStackView(Context context, AttributeSet attrs) { 62 | this(context, attrs, 0); 63 | } 64 | 65 | public CardStackView(Context context, AttributeSet attrs, int defStyleAttr) { 66 | super(context, attrs, defStyleAttr); 67 | 68 | TypedArray ta = getContext().getTheme().obtainStyledAttributes(attrs, R.styleable.CardStackView, defStyleAttr, 0); 69 | mCardHeight = ta.getDimensionPixelSize(R.styleable.CardStackView_card_height, Util.dp2px(getContext(), 160)); 70 | mCardMinSpan = ta.getDimensionPixelSize(R.styleable.CardStackView_card_min_span, Util.dp2px(getContext(), 40)); 71 | ta.recycle(); 72 | 73 | initTouchCallback(); 74 | 75 | setChildrenDrawingOrderEnabled(true); 76 | setClipToPadding(false); 77 | } 78 | 79 | private void initViews() { 80 | mOptions = new Options(); 81 | mCardFactory = new CardFactory(this, mOptions, mCardAdapter.getItemCount()); 82 | 83 | for (int i = 0; i < mCardAdapter.getItemCount(); i++) { 84 | View child = mCardAdapter.getView(null, i, this); 85 | this.addView(child); 86 | mCardFactory.add(mCardAdapter.getOrder(i), i, child); 87 | } 88 | 89 | mSlidingResistanceCalculator = new SlidingResistanceCalculator(2000f, mOptions.CARD_SPAN_OFFSET); 90 | 91 | updateOptions(); 92 | } 93 | 94 | private void initTouchCallback() { 95 | 96 | ViewDragHelper.Callback dragCallback = new ViewDragHelper.Callback() { 97 | @Override 98 | public boolean tryCaptureView(View child, int pointerId) { 99 | return false; 100 | } 101 | 102 | @Override 103 | public void onViewReleased(final View releasedChild, float xvel, float yvel) { 104 | CardHolder view = mCardFactory.findByView(releasedChild); 105 | if (view != null) { 106 | view.reset(); 107 | } 108 | 109 | mSelected = null; 110 | } 111 | 112 | @Override 113 | public int clampViewPositionVertical(View child, int top, int dy) { 114 | return top; 115 | } 116 | 117 | @Override 118 | public int clampViewPositionHorizontal(View child, int left, int dx) { 119 | //return left; 120 | CardHolder holder = mCardFactory.findByView(child); 121 | return holder != null ? holder.getFixedLeft() : left; 122 | } 123 | 124 | @Override 125 | public int getOrderedChildIndex(int index) { 126 | return getChildDrawingOrder(mCardFactory.size(), index); 127 | } 128 | 129 | @Override 130 | public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) { 131 | if (changedView != mSelected.mView) return; 132 | 133 | CardHolder holder = mCardFactory.findByView(changedView); 134 | if (holder == null) return; 135 | 136 | int diff = top - holder.getFixedTop(); // 位移距离 137 | 138 | float threshold = mOptions.CARD_SWAP_THRESHOLD * mOptions.CARD_SPAN_CURRENT; 139 | 140 | if (Math.abs(diff) < threshold) return; 141 | 142 | // 如果是两个边缘的卡片,不交换 143 | if ((diff > 0 && holder.mRealIndex < mCardFactory.size() - 1) || (diff < 0 && holder.mRealIndex > 0)) { 144 | int directionFlag = diff > 0 ? 1 : -1; 145 | 146 | mCardFactory.findByRealIndex(holder.mRealIndex + directionFlag).onSwap(holder); 147 | 148 | mCardFactory.swapRealIndex(holder.mRealIndex, holder.mRealIndex + directionFlag); 149 | if (mOnPositionChangedListener != null) { 150 | mOnPositionChangedListener.onPositionChanged(mCardFactory.getAllPosition()); 151 | } 152 | } 153 | } 154 | }; 155 | 156 | mViewDragHelper = ViewDragHelper.create(this, dragCallback); 157 | 158 | GestureDetector.OnGestureListener gestureListener = new GestureDetector.SimpleOnGestureListener() { 159 | @Override 160 | public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { 161 | float distance = e2.getY() - e1.getY(); 162 | 163 | if (mSelected == null) { 164 | mOptions.CARD_SPAN_CURRENT = 165 | (int) (mOptions.CARD_SPAN_NORMAL + mSlidingResistanceCalculator.getOutput(distance)); 166 | updateCardPosition(); 167 | return true; 168 | } 169 | return false; 170 | } 171 | 172 | @Override 173 | public boolean onDown(MotionEvent e) { 174 | return true; 175 | } 176 | 177 | @Override 178 | public void onLongPress(MotionEvent e) { 179 | //Log.d(TAG, String.format("onLongPress: %f, %f", e.getX(), e.getY())); 180 | mSelected = mCardFactory.findByTouch(e.getY() - getPaddingTop()); 181 | if (mSelected != null) { 182 | mSelected.onSelect(); 183 | mViewDragHelper.captureChildView(mSelected.mView, 0); 184 | } 185 | } 186 | 187 | @Override 188 | public boolean onSingleTapUp(MotionEvent e) { 189 | final CardHolder touch = mCardFactory.findByTouch(e.getY() - getPaddingTop()); 190 | if (touch != null && mOnCardClickListener != null) { 191 | mOnCardClickListener.onClick(touch.mView, touch.mRealIndex, touch.mChildIndex); 192 | } 193 | return true; 194 | } 195 | }; 196 | mGestureDetector = new GestureDetectorCompat(getContext(), gestureListener); 197 | } 198 | 199 | /** 200 | * 计算一些常量值 201 | */ 202 | private void updateOptions() { 203 | int parentH = getMeasuredHeight() - getPaddingTop() - getPaddingBottom(); 204 | int parentW = getMeasuredWidth() - getPaddingLeft() - getPaddingRight(); 205 | 206 | mOptions.CARD_HEIGHT = mCardHeight; 207 | mOptions.CARD_WIDTH = parentW; 208 | 209 | mOptions.CARD_SPAN_NORMAL_MIN = mCardMinSpan; 210 | int span = (parentH - mOptions.CARD_HEIGHT) / (mCardAdapter.getItemCount() - 1); 211 | mOptions.CARD_SPAN_NORMAL = Math.max(span, mOptions.CARD_SPAN_NORMAL_MIN); 212 | 213 | mOptions.CARD_SPAN_CURRENT = mOptions.CARD_SPAN_NORMAL; 214 | mOptions.CARD_SPAN_OFFSET = (int) (mOptions.CARD_SPAN_NORMAL * mOptions.CARD_SPAN_OFFSET_PERCENT); 215 | 216 | mOptions.CARD_FLOAT_UP = (int) (mOptions.CARD_SPAN_NORMAL * mOptions.CARD_FLOAT_UP_PERCENT); 217 | 218 | if (mSlidingResistanceCalculator != null) { 219 | mSlidingResistanceCalculator.setMaxOutput(mOptions.CARD_SPAN_OFFSET); 220 | } 221 | } 222 | 223 | @Override 224 | public boolean onTouchEvent(MotionEvent event) { 225 | 226 | if (mSkipTouch) return false; 227 | 228 | if (event.getAction() == MotionEvent.ACTION_UP && mSelected == null) { 229 | resetCardSpan(); 230 | } 231 | 232 | mViewDragHelper.processTouchEvent(event); 233 | 234 | return mGestureDetector.onTouchEvent(event); 235 | } 236 | 237 | @Override 238 | public boolean onInterceptTouchEvent(MotionEvent ev) { 239 | return mViewDragHelper.shouldInterceptTouchEvent(ev); 240 | } 241 | 242 | @Override 243 | protected int getChildDrawingOrder(int childCount, int order) { 244 | CardHolder holder = mCardFactory.findByDrawOrder(order); 245 | return holder != null ? holder.mChildIndex : 0; 246 | } 247 | 248 | @Override 249 | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 250 | 251 | int width = 0, height = 0; 252 | 253 | int maxWidth = 0; 254 | for (int i = 0; i < getChildCount(); i++) { 255 | View child = getChildAt(i); 256 | measureChild(child, widthMeasureSpec, heightMeasureSpec); 257 | maxWidth = Math.max(maxWidth, child.getMeasuredWidth()); 258 | } 259 | 260 | if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST) { 261 | // wrap_content use min span 262 | if (existsValidChild()) { 263 | width = maxWidth; 264 | height = mOptions.CARD_SPAN_NORMAL_MIN * (getChildCount() - 1) + mOptions.CARD_HEIGHT; 265 | } 266 | width += (getPaddingLeft() + getPaddingRight()); 267 | height += (getPaddingTop() + getPaddingBottom()); 268 | } else { 269 | width = MeasureSpec.getSize(widthMeasureSpec); 270 | height = MeasureSpec.getSize(heightMeasureSpec); 271 | } 272 | setMeasuredDimension(width, height); 273 | //Log.d(TAG, "onMeasure: w="+width+", h="+height); 274 | updateOptions(); 275 | } 276 | 277 | /** 278 | * 存在有效的卡片 View 279 | */ 280 | private boolean existsValidChild() { 281 | return mOptions != null && mCardFactory != null && mCardFactory.size() != 0; 282 | } 283 | 284 | @Override 285 | protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 286 | if (mSkipLayout) return; 287 | updateCardPosition(); 288 | } 289 | 290 | /** 291 | * 更新卡片位置 292 | */ 293 | public void updateCardPosition() { 294 | if (!existsValidChild()) return; 295 | 296 | for (int i = 0; i < mCardFactory.size(); i++) { 297 | CardHolder holder = mCardFactory.get(i); 298 | if (!holder.isAnimating()) { 299 | holder.layoutFixed(); 300 | } 301 | } 302 | } 303 | 304 | public void setAdapter(CardAdapter adapter) { 305 | if (mCardAdapter != null) { 306 | mCardAdapter.unregisterDataSetObserver(mObserver); 307 | } 308 | 309 | this.mCardAdapter = adapter; 310 | if (mCardAdapter != null && mCardAdapter.getItemCount() > 0) { 311 | mCardAdapter.registerDataSetObserver(mObserver); 312 | initViews(); 313 | } 314 | } 315 | 316 | public void setOnCardClickListener(OnCardClickListener listener) { 317 | this.mOnCardClickListener = listener; 318 | } 319 | 320 | public void setOnPositionChangedListener(OnPositionChangedListener onPositionChangedListener) { 321 | mOnPositionChangedListener = onPositionChangedListener; 322 | } 323 | 324 | /** 325 | * 重置卡片间距 326 | */ 327 | private void resetCardSpan() { 328 | ValueAnimator spanResetAnimator = ValueAnimator.ofInt(mOptions.CARD_SPAN_CURRENT, mOptions.CARD_SPAN_NORMAL); 329 | spanResetAnimator.setDuration(mOptions.SPAN_RESET_DURATION); 330 | spanResetAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { 331 | @Override 332 | public void onAnimationUpdate(ValueAnimator animation) { 333 | mOptions.CARD_SPAN_CURRENT = (int) animation.getAnimatedValue(); 334 | updateCardPosition(); 335 | } 336 | }); 337 | spanResetAnimator.setInterpolator(new OvershootInterpolator()); 338 | spanResetAnimator.start(); 339 | } 340 | 341 | public interface OnCardClickListener { 342 | 343 | /** 344 | * @param view 被点击的 View 345 | * @param realIndex 当前 View 的位置 346 | * @param initialIndex 初始化时 View 的位置 347 | */ 348 | void onClick(View view, int realIndex, int initialIndex); 349 | } 350 | 351 | public interface OnPositionChangedListener { 352 | /** 353 | * @param position 原始卡片对应当前排序的位置 354 | * 如原始第 1 张卡片现在排在第 3 个,则 position.get(1) = 3 355 | */ 356 | void onPositionChanged(List position); 357 | } 358 | 359 | private class CardStackViewDataObserver extends DataSetObserver { 360 | @Override 361 | public void onChanged() { 362 | for (int i = 0; i < mCardFactory.size(); i++) { 363 | CardHolder holder = mCardFactory.get(i); 364 | holder.mView = mCardAdapter.getView(holder.mView, holder.mChildIndex, CardStackView.this); 365 | } 366 | } 367 | 368 | @Override 369 | public void onInvalidated() { 370 | for (int i = 0; i < mCardFactory.size(); i++) { 371 | CardHolder holder = mCardFactory.get(i); 372 | holder.mView.postInvalidate(); 373 | } 374 | } 375 | } 376 | } 377 | -------------------------------------------------------------------------------- /cardstackview/src/main/java/me/brucezz/cardstackview/Options.java: -------------------------------------------------------------------------------- 1 | package me.brucezz.cardstackview; 2 | 3 | /** 4 | * Created by brucezz on 2016-10-12. 5 | * Github: https://github.com/brucezz 6 | * Email: im.brucezz@gmail.com 7 | */ 8 | 9 | public class Options { 10 | /** 11 | * 卡片当前绘制的间距 12 | */ 13 | public int CARD_SPAN_CURRENT; 14 | /** 15 | * 卡片正常情况下的间距 16 | */ 17 | public int CARD_SPAN_NORMAL; 18 | /** 19 | * 卡片正常情况下最小间距 20 | */ 21 | public int CARD_SPAN_NORMAL_MIN; 22 | /** 23 | * 卡片间距可偏移的距离 24 | */ 25 | public int CARD_SPAN_OFFSET; 26 | /** 27 | * 滑动时卡片间距可偏移的幅度 28 | */ 29 | public float CARD_SPAN_OFFSET_PERCENT = .33f; 30 | /** 31 | * 卡片的高度 32 | */ 33 | public int CARD_HEIGHT; 34 | /** 35 | * 卡片的宽度 36 | */ 37 | public int CARD_WIDTH; 38 | 39 | /** 40 | * 长按时卡片浮起的高度 41 | */ 42 | public int CARD_FLOAT_UP; 43 | /** 44 | * 长按卡片浮起的幅度 45 | */ 46 | public float CARD_FLOAT_UP_PERCENT = 0.33f; 47 | /** 48 | * 卡片移动触发交换动画的距离阈值 49 | */ 50 | public float CARD_SWAP_THRESHOLD = 0.65f; 51 | /** 52 | * 交换动画时长 53 | */ 54 | public long CARD_SWAP_DURATION = 300L; 55 | /** 56 | * 重置动画时长 57 | */ 58 | public long CARD_RESET_DURATION = 150L; 59 | /** 60 | * 浮起动画时长 61 | */ 62 | public long CARD_FLOAT_DURATION = 150L; 63 | /** 64 | * 卡片间距重置动画时长 65 | */ 66 | public long SPAN_RESET_DURATION = 300L; 67 | /** 68 | * 点击卡片之后移除其他卡片 69 | */ 70 | public boolean CLICK_TO_SEPARATE = true; 71 | /** 72 | * 移出屏幕的动画时长 73 | */ 74 | public long CARD_SLIP_OUT = 500L; 75 | 76 | @Override 77 | public String toString() { 78 | return "Options{" + 79 | ", \nCARD_SPAN_CURRENT=" + CARD_SPAN_CURRENT + 80 | ", \nCARD_SPAN_NORMAL=" + CARD_SPAN_NORMAL + 81 | ", \nCARD_SPAN_NORMAL_MIN=" + CARD_SPAN_NORMAL_MIN + 82 | ", \nCARD_SPAN_OFFSET=" + CARD_SPAN_OFFSET + 83 | ", \nCARD_SPAN_OFFSET_PERCENT=" + CARD_SPAN_OFFSET_PERCENT + 84 | ", \nCARD_HEIGHT=" + CARD_HEIGHT + 85 | ", \nCARD_WIDTH=" + CARD_WIDTH + 86 | ", \nCARD_FLOAT_UP=" + CARD_FLOAT_UP + 87 | ", \nCARD_FLOAT_UP_PERCENT=" + CARD_FLOAT_UP_PERCENT + 88 | ", \nCARD_SWAP_THRESHOLD=" + CARD_SWAP_THRESHOLD + 89 | ", \nCARD_SWAP_DURATION=" + CARD_SWAP_DURATION + 90 | ", \nCARD_RESET_DURATION=" + CARD_RESET_DURATION + 91 | ", \nCARD_FLOAT_DURATION=" + CARD_FLOAT_DURATION + 92 | ", \nSPAN_RESET_DURATION=" + SPAN_RESET_DURATION + 93 | "\n}"; 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /cardstackview/src/main/java/me/brucezz/cardstackview/SlidingResistanceCalculator.java: -------------------------------------------------------------------------------- 1 | package me.brucezz.cardstackview; 2 | 3 | /** 4 | * Created by brucezz on 2016-10-12. 5 | * Github: https://github.com/brucezz 6 | * Email: im.brucezz@gmail.com 7 | */ 8 | 9 | /** 10 | * 模拟滑动的阻力的计算 11 | * 12 | * 计算函数图像: http://ww4.sinaimg.cn/large/801b780agw1f8pkoxfwa8j20xa0ooq5a.jpg 13 | */ 14 | public class SlidingResistanceCalculator { 15 | 16 | private float mMaxInput; 17 | private float mMaxOutput; 18 | 19 | /** 20 | * @param maxInput 最大输入值(估计) 21 | * @param maxOutput 最大输出值(趋近于它) 22 | */ 23 | public SlidingResistanceCalculator(float maxInput, float maxOutput) { 24 | mMaxInput = maxInput; 25 | mMaxOutput = maxOutput; 26 | } 27 | 28 | public float getOutput(float input) { 29 | return (float) (mMaxOutput * (2 / (1 + Math.exp(-5 * input / mMaxInput)) - 1)); 30 | } 31 | 32 | public void setMaxInput(float maxInput) { 33 | mMaxInput = maxInput; 34 | } 35 | 36 | public void setMaxOutput(float maxOutput) { 37 | mMaxOutput = maxOutput; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /cardstackview/src/main/java/me/brucezz/cardstackview/Util.java: -------------------------------------------------------------------------------- 1 | package me.brucezz.cardstackview; 2 | 3 | import android.content.Context; 4 | import android.util.TypedValue; 5 | 6 | /** 7 | * Created by brucezz on 2016-09-26. 8 | * Github: https://github.com/brucezz 9 | * Email: im.brucezz@gmail.com 10 | */ 11 | 12 | public class Util { 13 | 14 | public static int dp2px(Context context, float dpValue) { 15 | return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, context.getResources().getDisplayMetrics()); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /cardstackview/src/main/java/me/brucezz/cardstackview/ViewUpdateListener.java: -------------------------------------------------------------------------------- 1 | package me.brucezz.cardstackview; 2 | 3 | import android.animation.ValueAnimator; 4 | 5 | /** 6 | * Created by brucezz on 2016-10-12. 7 | * Github: https://github.com/brucezz 8 | * Email: im.brucezz@gmail.com 9 | */ 10 | 11 | public class ViewUpdateListener implements ValueAnimator.AnimatorUpdateListener { 12 | 13 | private CardHolder mRunning; 14 | private CardHolder mDragging; 15 | private int mStart, mMid, mEnd; 16 | 17 | public ViewUpdateListener(CardHolder running, CardHolder dragging, int start, int mid, int end) { 18 | mRunning = running; 19 | mDragging = dragging; 20 | mStart = start; 21 | mMid = mid; 22 | mEnd = end; 23 | } 24 | 25 | @Override 26 | public void onAnimationUpdate(ValueAnimator animation) { 27 | float value = (float) animation.getAnimatedValue(); 28 | mRunning.updateView(mDragging, mStart, mMid, mEnd, value); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /cardstackview/src/main/res/values/attrs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /cardstackview/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | cardstackview 3 | 4 | -------------------------------------------------------------------------------- /cardstackview/src/test/java/me/brucezz/cardstackview/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package me.brucezz.cardstackview; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() throws Exception { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | org.gradle.jvmargs=-Xmx1536m 13 | 14 | # When configured, Gradle will run in incubating parallel mode. 15 | # This option should only be used with decoupled projects. More details, visit 16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 17 | # org.gradle.parallel=true 18 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bruce3x/CardStackView/7990803a0ffa479dfe7a86b01ecf4f4093a73fc5/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Dec 28 10:00:20 PST 2015 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /sample/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /sample/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 24 5 | buildToolsVersion "24.0.0" 6 | 7 | defaultConfig { 8 | applicationId "me.brucezz.cardstackview.sample" 9 | minSdkVersion 14 10 | targetSdkVersion 24 11 | versionCode 1 12 | versionName "1.0" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | } 21 | 22 | dependencies { 23 | compile fileTree(include: ['*.jar'], dir: 'libs') 24 | compile 'com.android.support:appcompat-v7:24.2.1' 25 | testCompile 'junit:junit:4.12' 26 | compile project(':cardstackview') 27 | compile 'com.android.support:cardview-v7:24.2.1' 28 | compile 'com.jaeger.statusbaruitl:library:1.3.0' 29 | compile 'com.makeramen:roundedimageview:2.2.1' 30 | } 31 | -------------------------------------------------------------------------------- /sample/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/bruce/Library/Android/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /sample/src/androidTest/java/me/brucezz/sample/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package me.brucezz.sample; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumentation test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() throws Exception { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("me.brucezz.sample", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /sample/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /sample/src/main/java/me/brucezz/sample/Card.java: -------------------------------------------------------------------------------- 1 | package me.brucezz.sample; 2 | 3 | import android.os.Parcel; 4 | import android.os.Parcelable; 5 | import android.support.annotation.ColorInt; 6 | import android.support.annotation.DrawableRes; 7 | 8 | /** 9 | * Created by brucezz on 2016-10-12. 10 | * Github: https://github.com/brucezz 11 | * Email: im.brucezz@gmail.com 12 | */ 13 | 14 | public class Card implements Parcelable { 15 | 16 | @ColorInt int mBgColor; 17 | @DrawableRes int mImage; 18 | String mTitle; 19 | 20 | public Card(int bgColor, int image, String title) { 21 | mBgColor = bgColor; 22 | mImage = image; 23 | mTitle = title; 24 | } 25 | 26 | @Override 27 | public int describeContents() { 28 | return 0; 29 | } 30 | 31 | @Override 32 | public void writeToParcel(Parcel dest, int flags) { 33 | dest.writeInt(this.mBgColor); 34 | dest.writeInt(this.mImage); 35 | dest.writeString(this.mTitle); 36 | } 37 | 38 | protected Card(Parcel in) { 39 | this.mBgColor = in.readInt(); 40 | this.mImage = in.readInt(); 41 | this.mTitle = in.readString(); 42 | } 43 | 44 | public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { 45 | @Override 46 | public Card createFromParcel(Parcel source) { 47 | return new Card(source); 48 | } 49 | 50 | @Override 51 | public Card[] newArray(int size) { 52 | return new Card[size]; 53 | } 54 | }; 55 | } 56 | -------------------------------------------------------------------------------- /sample/src/main/java/me/brucezz/sample/DetailActivity.java: -------------------------------------------------------------------------------- 1 | package me.brucezz.sample; 2 | 3 | import android.os.Bundle; 4 | import android.support.annotation.Nullable; 5 | import android.support.v7.app.AppCompatActivity; 6 | import android.view.View; 7 | import android.widget.ImageView; 8 | import android.widget.TextView; 9 | import com.jaeger.library.StatusBarUtil; 10 | 11 | /** 12 | * Created by brucezz on 2016-10-28. 13 | * Github: https://github.com/brucezz 14 | * Email: im.brucezz@gmail.com 15 | */ 16 | 17 | public class DetailActivity extends AppCompatActivity { 18 | 19 | ImageView mImageView; 20 | TextView mTextView; 21 | View mContent; 22 | 23 | @Override 24 | protected void onCreate(@Nullable Bundle savedInstanceState) { 25 | super.onCreate(savedInstanceState); 26 | 27 | setContentView(R.layout.activity_detail); 28 | 29 | mImageView = (ImageView) findViewById(R.id.detail_bg); 30 | mTextView = (TextView) findViewById(R.id.detail_title); 31 | mContent = findViewById(R.id.detail_content); 32 | 33 | Card card = getIntent().getParcelableExtra("card"); 34 | mImageView.setImageResource(card.mImage); 35 | StatusBarUtil.setColor(this, card.mBgColor); 36 | mTextView.setText("哈哈哈 改变一下标题 ~" + card.mTitle); 37 | 38 | animContent(); 39 | } 40 | 41 | private void animContent() { 42 | mTextView.animate().alpha(1f).setDuration(500).start(); 43 | mContent.animate().alpha(1f).setDuration(500).start(); 44 | } 45 | 46 | @Override 47 | public void onBackPressed() { 48 | setResult(RESULT_OK); 49 | finish(); 50 | overridePendingTransition(0, 0); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /sample/src/main/java/me/brucezz/sample/DisplayUtil.java: -------------------------------------------------------------------------------- 1 | package me.brucezz.sample; 2 | 3 | import android.content.Context; 4 | import android.content.res.Resources; 5 | import android.util.DisplayMetrics; 6 | import android.util.TypedValue; 7 | 8 | /** 9 | * Created by david on 16/5/26. 10 | * Email: huangdiv5@gmail.com 11 | * GitHub: https://github.com/alighters 12 | */ 13 | public class DisplayUtil { 14 | 15 | private static final String TAG = DisplayUtil.class.getSimpleName(); 16 | 17 | private static Context mContext; 18 | 19 | public static void init(Context context) { 20 | mContext = context; 21 | } 22 | 23 | /** 24 | * 获取屏幕宽度 25 | */ 26 | public static int getScreenWidthPixel() { 27 | return getDisplayMetrics().widthPixels; 28 | } 29 | 30 | /** 31 | * 获取屏幕高度 32 | */ 33 | public static int getScreenHeightPixel() { 34 | return getDisplayMetrics().heightPixels; 35 | } 36 | 37 | /** 38 | * 获取 显示信息 39 | */ 40 | public static DisplayMetrics getDisplayMetrics() { 41 | return mContext.getResources().getDisplayMetrics(); 42 | } 43 | 44 | /** 45 | * px转dp 46 | */ 47 | public static int px2Dp(int px) { 48 | return (int) (px / getDisplayMetrics().density); 49 | } 50 | 51 | /** 52 | * px转dp 53 | */ 54 | public static int dp2Px(float dpValue) { 55 | return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, getDisplayMetrics()); 56 | } 57 | 58 | /** 59 | * sx转dp 60 | */ 61 | public static int sp2Px(float spValue) { 62 | return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spValue, getDisplayMetrics()); 63 | } 64 | 65 | /** 66 | * 获取状态栏高度 67 | */ 68 | public static int getStatusBarHeight(Context context) { 69 | int statusBarHeight = 0; 70 | try { 71 | int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); 72 | if (resourceId > 0) { 73 | statusBarHeight = context.getResources().getDimensionPixelSize(resourceId); 74 | } 75 | } catch (Resources.NotFoundException exception) { 76 | } 77 | return statusBarHeight; 78 | } 79 | 80 | /** 81 | * 获取导航栏高度 82 | */ 83 | public static int getNavigationBarHeight(Context context) { 84 | Resources resources = context.getResources(); 85 | int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android"); 86 | if (resourceId > 0) { 87 | return resources.getDimensionPixelSize(resourceId); 88 | } 89 | return 0; 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /sample/src/main/java/me/brucezz/sample/MainActivity.java: -------------------------------------------------------------------------------- 1 | package me.brucezz.sample; 2 | 3 | import android.animation.Animator; 4 | import android.animation.ArgbEvaluator; 5 | import android.animation.ValueAnimator; 6 | import android.content.Intent; 7 | import android.content.SharedPreferences; 8 | import android.os.Bundle; 9 | import android.preference.PreferenceManager; 10 | import android.support.annotation.ColorInt; 11 | import android.support.v4.util.Pair; 12 | import android.support.v7.app.AppCompatActivity; 13 | import android.support.v7.widget.CardView; 14 | import android.support.v7.widget.Toolbar; 15 | import android.text.TextUtils; 16 | import android.view.View; 17 | import android.view.ViewGroup; 18 | import android.widget.ImageView; 19 | import android.widget.TextView; 20 | import com.jaeger.library.StatusBarUtil; 21 | import java.util.Arrays; 22 | import java.util.List; 23 | import me.brucezz.cardstackview.CardStackView; 24 | 25 | public class MainActivity extends AppCompatActivity { 26 | 27 | public static final int REQ_DETAIL = 0x233; 28 | Toolbar mToolbar; 29 | 30 | CardStackView mCardStackView; 31 | SimpleCardAdapter mCardAdapter; 32 | private List> mCards; 33 | 34 | private AnimationHelper mHelper; 35 | private SharedPreferences mPreferences; 36 | 37 | @Override 38 | protected void onCreate(Bundle savedInstanceState) { 39 | super.onCreate(savedInstanceState); 40 | setContentView(R.layout.activity_main); 41 | 42 | mToolbar = (Toolbar) findViewById(R.id.toolbar); 43 | 44 | mCardStackView = (CardStackView) findViewById(R.id.card_stack_view); 45 | mCardStackView.setOnCardClickListener(new CardStackView.OnCardClickListener() { 46 | @Override 47 | public void onClick(View view, int realIndex, int initialIndex) { 48 | toggleAnimation(view, initialIndex); 49 | } 50 | }); 51 | mCardStackView.setOnPositionChangedListener(new CardStackView.OnPositionChangedListener() { 52 | @Override 53 | public void onPositionChanged(List position) { 54 | StringBuilder sb = new StringBuilder(); 55 | for (Integer integer : position) { 56 | sb.append(integer).append(" "); 57 | } 58 | mPreferences.edit().putString("order", sb.toString()).apply(); 59 | } 60 | }); 61 | 62 | mPreferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this); 63 | String order = mPreferences.getString("order", ""); 64 | int[] orders; 65 | if (TextUtils.isEmpty(order)) { 66 | orders = new int[] { 0, 1, 2, 3 }; 67 | } else { 68 | String[] ordersArr = order.trim().split(" "); 69 | orders = new int[ordersArr.length]; 70 | for (int i = 0; i < ordersArr.length; i++) { 71 | orders[i] = Integer.valueOf(ordersArr[i]); 72 | } 73 | } 74 | mCards = initCards(orders); 75 | mCardAdapter = new SimpleCardAdapter(this, mCards); 76 | 77 | mCardStackView.setAdapter(mCardAdapter); 78 | 79 | mToolbar.setOnClickListener(new View.OnClickListener() { 80 | @Override 81 | public void onClick(View v) { 82 | System.out.println(mPreferences.getString("order", "")); 83 | } 84 | }); 85 | } 86 | 87 | private List> initCards(int... orders) { 88 | return Arrays.asList(Pair.create(orders[0], new Card(0xFF00BACF, R.drawable.knowledge, "知识")), 89 | Pair.create(orders[1], new Card(0xFFE85D72, R.drawable.calendar, "日程")), 90 | Pair.create(orders[2], new Card(0xFF17B084, R.drawable.task, "任务")), 91 | Pair.create(orders[3], new Card(0xFF2196F3, R.drawable.post, "动态"))); 92 | } 93 | 94 | private void toggleAnimation(final View view, final int index) { 95 | mHelper = new AnimationHelper(view, index); 96 | 97 | mHelper.startAnimation(false); 98 | } 99 | 100 | @Override 101 | protected void onActivityResult(int requestCode, int resultCode, Intent data) { 102 | if (mHelper == null) return; 103 | 104 | if (requestCode == REQ_DETAIL && resultCode == RESULT_OK) { 105 | mHelper.startAnimation(true); 106 | } else { 107 | mHelper.resetViews(); 108 | } 109 | } 110 | 111 | private class AnimationHelper { 112 | 113 | private int mIndex; 114 | 115 | private CardView mCardView; 116 | private ImageView mImageView; 117 | private TextView mTitle; 118 | private TextView mFoo; 119 | 120 | private int startLeft, endLeft; 121 | private int startRight, endRight; 122 | private int startTop, endTop; 123 | private int startBottom, endBottom; 124 | 125 | private float startRadius, endRadius; 126 | 127 | private @ColorInt int startColor, endColor; 128 | private ArgbEvaluator mArgbEvaluator = new ArgbEvaluator(); 129 | 130 | private float startElevation; 131 | private float endElevation; 132 | 133 | private static final long ANIMATION_DURATION_CARD = 500L; 134 | private static final long ANIMATION_DURATION_ALPHA = 300L; 135 | 136 | public AnimationHelper(View view, int index) { 137 | mIndex = index; 138 | mCardView = ((CardView) view); 139 | mImageView = (ImageView) mCardView.findViewById(R.id.card_image); 140 | mTitle = (TextView) mCardView.findViewById(R.id.card_title); 141 | mFoo = (TextView) mCardView.findViewById(R.id.card_foo); 142 | 143 | startLeft = mCardView.getLeft(); 144 | startRight = mCardView.getRight(); 145 | startTop = mCardView.getTop(); 146 | startBottom = mCardView.getBottom(); 147 | 148 | endLeft = 0; 149 | endRight = mCardView.getWidth() + 2 * mCardView.getLeft(); 150 | endTop = 0; 151 | endBottom = mCardView.getHeight(); 152 | 153 | startRadius = mCardView.getRadius(); 154 | endRadius = 1f;// radius 减到 0 会自动产生透明度变化 155 | 156 | startColor = getResources().getColor(R.color.colorPrimary); 157 | endColor = mCards.get(mIndex).second.mBgColor; 158 | 159 | startElevation = mCardView.getMaxCardElevation(); 160 | endElevation = 0f; 161 | } 162 | 163 | @ColorInt 164 | private int getColor(float fraction) { 165 | return (int) mArgbEvaluator.evaluate(fraction, startColor, endColor); 166 | } 167 | 168 | private int getInterpolation(int start, int end, float fraction) { 169 | return (int) (start + fraction * (end - start)); 170 | } 171 | 172 | private int getInterpolation(float start, float end, float fraction) { 173 | return (int) (start + fraction * (end - start)); 174 | } 175 | 176 | private float getElevation(float start, float end, float fraction, float threshold) { 177 | if (fraction <= threshold) return start; 178 | 179 | return start + (end - start) * (fraction - threshold) / (1 - threshold); 180 | } 181 | 182 | public void startAnimation(final boolean reverse) { 183 | ValueAnimator animator = 184 | ValueAnimator.ofFloat(reverse ? 1f : 0f, reverse ? 0f : 1f).setDuration(ANIMATION_DURATION_CARD); 185 | animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { 186 | @Override 187 | public void onAnimationUpdate(ValueAnimator animation) { 188 | update((float) animation.getAnimatedValue()); 189 | } 190 | }); 191 | 192 | animator.addListener(new Animator.AnimatorListener() { 193 | @Override 194 | public void onAnimationStart(Animator animation) { 195 | mCardStackView.setSkipLayout(true); 196 | mCardStackView.setSkipTouch(true); 197 | if (!reverse) { 198 | mToolbar.animate().alpha(0f).setDuration(ANIMATION_DURATION_ALPHA).start(); 199 | mTitle.animate().alpha(0f).setDuration(ANIMATION_DURATION_ALPHA).start(); 200 | mFoo.animate().alpha(0f).setDuration(ANIMATION_DURATION_ALPHA).start(); 201 | } 202 | 203 | animOtherCards(mIndex, reverse); 204 | } 205 | 206 | @Override 207 | public void onAnimationEnd(Animator animation) { 208 | if (reverse) { 209 | mToolbar.animate().alpha(1f).setDuration(ANIMATION_DURATION_ALPHA).start(); 210 | mTitle.animate().alpha(1f).setDuration(ANIMATION_DURATION_ALPHA).start(); 211 | mFoo.animate().alpha(1f).setDuration(ANIMATION_DURATION_ALPHA).start(); 212 | } else { 213 | Intent intent = new Intent(MainActivity.this, DetailActivity.class); 214 | intent.putExtra("card", mCards.get(mIndex).second); 215 | startActivityForResult(intent, REQ_DETAIL); 216 | overridePendingTransition(0, 0); 217 | } 218 | mCardStackView.post(new Runnable() { 219 | @Override 220 | public void run() { 221 | mCardStackView.setSkipLayout(false); 222 | mCardStackView.setSkipTouch(false); 223 | } 224 | }); 225 | } 226 | 227 | @Override 228 | public void onAnimationCancel(Animator animation) { 229 | 230 | } 231 | 232 | @Override 233 | public void onAnimationRepeat(Animator animation) { 234 | 235 | } 236 | }); 237 | animator.start(); 238 | } 239 | 240 | private void update(float fraction) { 241 | mCardView.setRadius(getInterpolation(startRadius, endRadius, fraction)); 242 | int right = getInterpolation(startRight, endRight, fraction); 243 | int left = getInterpolation(startLeft, endLeft, fraction); 244 | int top = getInterpolation(startTop, endTop, fraction); 245 | int bottom = getInterpolation(startBottom, endBottom, fraction); 246 | mCardView.getLayoutParams().width = right - left; 247 | mCardView.layout(left, top, right, bottom); 248 | 249 | /** 250 | * 设置了一个阈值 threshold, 进度超过阈值之后才开始进行插值。 251 | * 也就是等到其他卡片都收起来之后,再对当前卡片做阴影动画,避免在 5.x 绘制层级问题。 252 | * 253 | * 最终阴影变为0,避免了在 4.x 上 CardView 自带边距绘制阴影,导致无法无缝切换的问题。 254 | */ 255 | float elevation = 256 | getElevation(startElevation, endElevation, fraction, ANIMATION_DURATION_ALPHA * 1f / ANIMATION_DURATION_CARD); 257 | mCardView.setMaxCardElevation(elevation); 258 | mCardView.setCardElevation(elevation); 259 | 260 | mCardView.requestLayout(); 261 | StatusBarUtil.setColor(MainActivity.this, getColor(fraction)); 262 | } 263 | 264 | /** 265 | * 不作动画直接重置视图 266 | */ 267 | public void resetViews() { 268 | for (int i = 0; i < mCardStackView.getChildCount(); i++) { 269 | if (i == mIndex) continue; 270 | mCardStackView.getChildAt(i).setTranslationY(0f); 271 | } 272 | 273 | update(0f); 274 | mTitle.setAlpha(1f); 275 | mFoo.setAlpha(1f); 276 | mToolbar.setAlpha(1f); 277 | } 278 | 279 | /** 280 | * 其他卡片直接进行简单的 translation 动画沿 Y 轴移动即可 281 | */ 282 | private void animOtherCards(int idx, boolean reverse) { 283 | for (int i = 0; i < mCardStackView.getChildCount(); i++) { 284 | if (i == idx) continue; 285 | 286 | View view = mCardStackView.getChildAt(i); 287 | if (reverse) { 288 | view.animate().translationY(0f).setDuration(AnimationHelper.ANIMATION_DURATION_CARD).start(); 289 | } else { 290 | int start = view.getTop(); 291 | int end = ((ViewGroup) view.getParent()).getBottom(); 292 | view.animate().translationY(end - start).setDuration(AnimationHelper.ANIMATION_DURATION_CARD).start(); 293 | } 294 | } 295 | } 296 | } 297 | } 298 | -------------------------------------------------------------------------------- /sample/src/main/java/me/brucezz/sample/SimpleCardAdapter.java: -------------------------------------------------------------------------------- 1 | package me.brucezz.sample; 2 | 3 | import android.content.Context; 4 | import android.os.Build; 5 | import android.support.v4.util.Pair; 6 | import android.support.v7.widget.CardView; 7 | import android.view.LayoutInflater; 8 | import android.view.View; 9 | import android.view.ViewGroup; 10 | import android.widget.ImageView; 11 | import android.widget.TextView; 12 | import java.util.List; 13 | import me.brucezz.cardstackview.CardAdapter; 14 | 15 | /** 16 | * Created by brucezz on 2016-10-12. 17 | * Github: https://github.com/brucezz 18 | * Email: im.brucezz@gmail.com 19 | */ 20 | 21 | public class SimpleCardAdapter extends CardAdapter { 22 | 23 | private Context mContext; 24 | private List> mCards; 25 | 26 | public SimpleCardAdapter(Context context, List> cards) { 27 | mContext = context; 28 | mCards = cards; 29 | } 30 | 31 | @Override 32 | public View getView(View oldView, int position, ViewGroup parent) { 33 | Card card = mCards.get(position).second; 34 | 35 | ViewHolder holder; 36 | View view; 37 | if (oldView != null && oldView.getTag() instanceof ViewHolder) { 38 | holder = (ViewHolder) oldView.getTag(); 39 | view = oldView; 40 | } else { 41 | holder = new ViewHolder(); 42 | view = LayoutInflater.from(mContext).inflate(R.layout.item_card, parent, false); 43 | holder.mCardView = (CardView) view.findViewById(R.id.card); 44 | holder.mTextView = (TextView) view.findViewById(R.id.card_title); 45 | holder.mImageView = (ImageView) view.findViewById(R.id.card_image); 46 | } 47 | 48 | holder.mTextView.setText(card.mTitle); 49 | holder.mImageView.setImageResource(card.mImage); 50 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { 51 | // BugFix: 4.x 版本: CardView 中填充 ImageView 会有白边 52 | holder.mCardView.setCardBackgroundColor(card.mBgColor); 53 | } 54 | view.setTag(holder); 55 | 56 | return view; 57 | } 58 | 59 | @Override 60 | public int getItemCount() { 61 | return mCards != null ? mCards.size() : 0; 62 | } 63 | 64 | @Override 65 | public int getOrder(int position) { 66 | return mCards.get(position).first; 67 | } 68 | 69 | private static class ViewHolder { 70 | CardView mCardView; 71 | TextView mTextView; 72 | ImageView mImageView; 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /sample/src/main/res/drawable-hdpi/calendar.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bruce3x/CardStackView/7990803a0ffa479dfe7a86b01ecf4f4093a73fc5/sample/src/main/res/drawable-hdpi/calendar.png -------------------------------------------------------------------------------- /sample/src/main/res/drawable-hdpi/knowledge.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bruce3x/CardStackView/7990803a0ffa479dfe7a86b01ecf4f4093a73fc5/sample/src/main/res/drawable-hdpi/knowledge.png -------------------------------------------------------------------------------- /sample/src/main/res/drawable-hdpi/post.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bruce3x/CardStackView/7990803a0ffa479dfe7a86b01ecf4f4093a73fc5/sample/src/main/res/drawable-hdpi/post.png -------------------------------------------------------------------------------- /sample/src/main/res/drawable-hdpi/task.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bruce3x/CardStackView/7990803a0ffa479dfe7a86b01ecf4f4093a73fc5/sample/src/main/res/drawable-hdpi/task.png -------------------------------------------------------------------------------- /sample/src/main/res/layout/activity_detail.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 15 | 16 | 26 | 27 | 37 | -------------------------------------------------------------------------------- /sample/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 | 20 | 21 | 28 | 29 | -------------------------------------------------------------------------------- /sample/src/main/res/layout/item_card.xml: -------------------------------------------------------------------------------- 1 | 2 | 14 | 15 | 21 | 22 | 28 | 29 | 36 | 37 | 42 | 43 | 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /sample/src/main/res/menu/menu_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 8 | -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bruce3x/CardStackView/7990803a0ffa479dfe7a86b01ecf4f4093a73fc5/sample/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bruce3x/CardStackView/7990803a0ffa479dfe7a86b01ecf4f4093a73fc5/sample/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bruce3x/CardStackView/7990803a0ffa479dfe7a86b01ecf4f4093a73fc5/sample/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bruce3x/CardStackView/7990803a0ffa479dfe7a86b01ecf4f4093a73fc5/sample/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bruce3x/CardStackView/7990803a0ffa479dfe7a86b01ecf4f4093a73fc5/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/values-w820dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 64dp 6 | 7 | -------------------------------------------------------------------------------- /sample/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | #FF4081 6 | 7 | -------------------------------------------------------------------------------- /sample/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 192dp 3 | 60dp 4 | 5 | -------------------------------------------------------------------------------- /sample/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | CardStackView Demo 3 | 4 | -------------------------------------------------------------------------------- /sample/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 14 | 15 | -------------------------------------------------------------------------------- /sample/src/test/java/me/brucezz/sample/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package me.brucezz.sample; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() throws Exception { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':cardstackview', ':sample' 2 | --------------------------------------------------------------------------------