17 |
18 | Complete Demo - https://www.youtube.com/watch?v=8VjEa_u3LkM
19 |
20 | Sample app APK - https://github.com/mutualmobile/CardStackUI/releases
21 |
22 | ### Gradle
23 | ```
24 | dependencies {
25 | ...
26 | compile 'com.mutualmobile.android:cardstack:0.6.0'
27 | }
28 | ```
29 |
30 | Usage
31 | -----
32 | ```xml
33 |
43 | ```
44 |
45 | Known Issues
46 | -------
47 |
48 | ```parallax_enabled``` and ```parallax_scale``` are not working currently. Also the drag to move cards also is not working.
49 |
50 | License
51 | -------
52 |
53 | Copyright 2015 - 2019 Mutual Mobile
54 |
55 | Licensed under the Apache License, Version 2.0 (the "License");
56 | you may not use this file except in compliance with the License.
57 | You may obtain a copy of the License at
58 |
59 | http://www.apache.org/licenses/LICENSE-2.0
60 |
61 | Unless required by applicable law or agreed to in writing, software
62 | distributed under the License is distributed on an "AS IS" BASIS,
63 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
64 | See the License for the specific language governing permissions and
65 | limitations under the License.
66 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mutualmobile/cardstack/sample/utils/PrefsUtil.kt:
--------------------------------------------------------------------------------
1 | package com.mutualmobile.cardstack.sample.utils
2 |
3 | import android.content.Context
4 |
5 | import com.mutualmobile.cardstack.CardStackLayout
6 | import com.mutualmobile.cardstack.sample.R.dimen
7 | import com.tramsun.libs.prefcompat.Pref
8 |
9 | object PrefsUtil {
10 |
11 | const val SHOW_INIT_ANIMATION = "showInitAnimation"
12 | const val PARALLAX_ENABLED = "parallaxEnabled"
13 | const val PARALLAX_SCALE = "parallaxScale"
14 | const val CARD_GAP = "cardGap"
15 | const val CARD_GAP_BOTTOM = "cardGapBottom"
16 | private const val REVERSE_CLICK_ANIMATION_ENABLED = "reverseClickAnimationEnabled"
17 | private const val REVERSE_CLICK_ANIMATION_ENABLED_DEFAULT = false
18 |
19 | val isShowInitAnimationEnabled: Boolean
20 | get() = Pref.getBoolean(SHOW_INIT_ANIMATION, CardStackLayout.SHOW_INIT_ANIMATION_DEFAULT)
21 |
22 | val isParallaxEnabled: Boolean
23 | get() = Pref.getBoolean(PARALLAX_ENABLED, CardStackLayout.PARALLAX_ENABLED_DEFAULT)
24 |
25 | var isReverseClickAnimationEnabled: Boolean
26 | get() = Pref.getBoolean(
27 | REVERSE_CLICK_ANIMATION_ENABLED,
28 | REVERSE_CLICK_ANIMATION_ENABLED_DEFAULT
29 | )
30 | set(b) = Pref.putBoolean(REVERSE_CLICK_ANIMATION_ENABLED, b)
31 |
32 | fun getParallaxScale(context: Context): Int {
33 | return Pref.getInt(PARALLAX_SCALE, context.resources.getInteger(com.mutualmobile.cardstack.R.integer.parallax_scale_default))
34 | }
35 |
36 | fun getCardGap(context: Context): Int {
37 | val cardGapDimenInDp = (context.resources.getDimension(dimen.card_gap) / context.resources.displayMetrics.density).toInt()
38 | return Pref.getInt(CARD_GAP, cardGapDimenInDp)
39 | }
40 |
41 | fun getCardGapBottom(context: Context): Int {
42 | val cardGapBottomDimenInDp = (context.resources.getDimension(dimen.card_gap_bottom) / context.resources.displayMetrics.density).toInt()
43 | return Pref.getInt(CARD_GAP_BOTTOM, cardGapBottomDimenInDp)
44 | }
45 |
46 | fun resetDefaults(context: Context) {
47 | val cardGapDimenInDp = (context.resources.getDimension(dimen.card_gap) / context.resources.displayMetrics.density).toInt()
48 | val cardGapBottomDimenInDp = (context.resources.getDimension(dimen.card_gap_bottom) / context.resources.displayMetrics.density).toInt()
49 |
50 | Pref.putBoolean(SHOW_INIT_ANIMATION, CardStackLayout.SHOW_INIT_ANIMATION_DEFAULT)
51 | Pref.putBoolean(PARALLAX_ENABLED, CardStackLayout.PARALLAX_ENABLED_DEFAULT)
52 | isReverseClickAnimationEnabled =
53 | REVERSE_CLICK_ANIMATION_ENABLED_DEFAULT
54 | Pref.putInt(PARALLAX_SCALE, context.resources.getInteger(com.mutualmobile.cardstack.R.integer.parallax_scale_default))
55 | Pref.putInt(CARD_GAP, cardGapDimenInDp)
56 | Pref.putInt(CARD_GAP_BOTTOM, cardGapBottomDimenInDp)
57 | }
58 | }
--------------------------------------------------------------------------------
/cardstack/build.gradle:
--------------------------------------------------------------------------------
1 | // Manifest version information!
2 | def versionMajor = 0
3 | def versionMinor = 6
4 | def versionPatch = 0
5 |
6 | apply plugin: 'com.android.library'
7 | apply plugin: 'kotlin-android-extensions'
8 | apply plugin: 'kotlin-android'
9 | apply plugin: 'com.github.dcendents.android-maven'
10 | apply plugin: 'com.jfrog.bintray'
11 |
12 | def siteUrl = 'https://github.com/mutualmobile/CardStackUI'
13 | def gitUrl = 'https://github.com/mutualmobile/CardStackUI.git'
14 | group = "com.mutualmobile.android"
15 | def vName = versionMajor + '.' + versionMinor + '.' + versionPatch
16 | def vCode = versionMajor * 100 + versionMinor * 10 + versionPatch
17 |
18 | // This is for bintray, DON'T REMOVE
19 | version = vName
20 |
21 | android {
22 | compileSdkVersion rootProject.ext.COMPILE_SDK_VERSION
23 |
24 | defaultConfig {
25 | minSdkVersion rootProject.ext.MIN_SDK_VERSION
26 | targetSdkVersion rootProject.ext.TARGET_SDK_VERSION
27 | versionCode vCode
28 | versionName vName
29 | }
30 | buildTypes {
31 | release {
32 | minifyEnabled true
33 | debuggable true
34 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
35 | }
36 | debug {
37 | debuggable true
38 | minifyEnabled false
39 | }
40 | }
41 | }
42 |
43 | install {
44 | repositories.mavenInstaller {
45 | // This generates POM.xml with proper parameters
46 | pom {
47 | project {
48 | packaging 'aar'
49 | name 'card-stack-ui'
50 | url siteUrl
51 |
52 | // Set your license
53 | licenses {
54 | license {
55 | name 'The Apache Software License, Version 2.0'
56 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
57 | }
58 | }
59 | developers {
60 | developer {
61 | id 'tushar-acharya'
62 | name 'Tushar Acharya'
63 | email 'tushar.acharya@mutualmobile.com'
64 | }
65 | }
66 | scm {
67 | connection gitUrl
68 | developerConnection gitUrl
69 | url siteUrl
70 | }
71 | }
72 | }
73 | }
74 | }
75 |
76 | dependencies {
77 | compile fileTree(dir: 'libs', include: ['*.jar'])
78 | compile "com.android.support:appcompat-v7:${rootProject.ext.SUPPORT_LIB_VERSION}"
79 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
80 | }
81 |
82 | task sourcesJar(type: Jar) {
83 | from android.sourceSets.main.java.srcDirs
84 | classifier = 'sources'
85 | }
86 |
87 | artifacts {
88 | archives sourcesJar
89 | }
90 |
91 | // Fails in CI, un-comment only to deploy new binaries to Bintray
92 |
93 | Properties properties = new Properties()
94 | if (project.rootProject.file('local.properties').exists()) {
95 | properties.load(project.rootProject.file('local.properties').newDataInputStream())
96 | }
97 |
98 | bintray {
99 | user = properties.getProperty("bintray.user")
100 | key = properties.getProperty("bintray.apikey")
101 |
102 | configurations = ['archives']
103 | pkg {
104 | repo = "Android"
105 | name = "card-stack-ui"
106 | userOrg = "mutualmobile"
107 | websiteUrl = siteUrl
108 | vcsUrl = gitUrl
109 | licenses = ["Apache-2.0"]
110 | publish = true
111 | labels = ['aar', 'android', 'ui']
112 | publicDownloadNumbers = true
113 | }
114 | }
115 | apply plugin: 'maven'
116 | repositories {
117 | mavenCentral()
118 | }
--------------------------------------------------------------------------------
/app/src/main/res/layout/settings_card.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
14 |
15 |
25 |
26 |
33 |
34 |
41 |
42 |
49 |
50 |
55 |
56 |
63 |
64 |
73 |
74 |
75 |
76 |
81 |
82 |
89 |
90 |
99 |
100 |
101 |
102 |
107 |
108 |
115 |
116 |
125 |
126 |
127 |
128 |
135 |
136 |
143 |
144 |
--------------------------------------------------------------------------------
/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 |
162 | yes | $ANDROID_HOME/tools/bin/sdkmanager "build-tools;28.0.3"
--------------------------------------------------------------------------------
/app/src/main/java/com/mutualmobile/cardstack/sample/adapters/MyCardStackAdapter.kt:
--------------------------------------------------------------------------------
1 | package com.mutualmobile.cardstack.sample.adapters
2 |
3 | import android.animation.Animator
4 | import android.animation.ObjectAnimator
5 | import android.content.Context
6 | import android.support.v4.content.ContextCompat
7 | import android.support.v7.widget.CardView
8 | import android.view.LayoutInflater
9 | import android.view.View
10 | import android.view.ViewGroup
11 | import android.widget.Button
12 | import android.widget.CompoundButton
13 | import android.widget.EditText
14 | import android.widget.Switch
15 | import android.widget.TextView
16 | import com.mutualmobile.cardstack.CardStackAdapter
17 | import com.mutualmobile.cardstack.sample.MainActivity
18 | import com.mutualmobile.cardstack.sample.R.color
19 | import com.mutualmobile.cardstack.sample.R.id
20 | import com.mutualmobile.cardstack.sample.R.layout
21 | import com.mutualmobile.cardstack.sample.R.string
22 | import com.mutualmobile.cardstack.sample.interfaces.OnRestartRequest
23 | import com.mutualmobile.cardstack.sample.utils.PrefsUtil
24 | import com.tramsun.libs.prefcompat.Pref
25 | import timber.log.Timber
26 |
27 | class MyCardStackAdapter(activity: MainActivity) : CardStackAdapter(activity), CompoundButton.OnCheckedChangeListener {
28 | private val mInflater: LayoutInflater
29 | private val mContext: Context
30 | private val mCallback: OnRestartRequest
31 | private var updateSettingsView: Runnable? = null
32 | private var bgColorIds: IntArray
33 |
34 | init {
35 | mContext = activity
36 | mInflater = LayoutInflater.from(activity)
37 | mCallback = activity
38 | bgColorIds = intArrayOf(
39 | color.card1_bg, color.card2_bg,
40 | color.card3_bg, color.card4_bg,
41 | color.card5_bg, color.card6_bg,
42 | color.card7_bg,
43 | color.card8_bg, color.card9_bg,
44 | color.card10_bg, color.card11_bg,
45 | color.card12_bg, color.card1_bg,
46 | color.card2_bg
47 | )
48 | }
49 |
50 | override fun getCount(): Int {
51 | return bgColorIds.size
52 | }
53 |
54 | override fun onCheckedChanged(
55 | buttonView: CompoundButton,
56 | isChecked: Boolean
57 | ) {
58 | Timber.d("onCheckedChanged() called with: buttonView = [$buttonView], isChecked = [$isChecked]")
59 | when (buttonView.id) {
60 | id.parallax_enabled -> Pref.putBoolean(PrefsUtil.PARALLAX_ENABLED, isChecked)
61 | id.reverse_click_animation -> PrefsUtil.isReverseClickAnimationEnabled = isChecked
62 | id.show_init_animation -> Pref.putBoolean(PrefsUtil.SHOW_INIT_ANIMATION, isChecked)
63 | }
64 | updateSettingsView?.run()
65 | }
66 |
67 | override fun createView(
68 | position: Int,
69 | container: ViewGroup
70 | ): View {
71 | if (position == 0) return getSettingsView(container)
72 |
73 | val root = mInflater.inflate(layout.card, container, false) as CardView
74 | root.setCardBackgroundColor(ContextCompat.getColor(mContext, bgColorIds[position]))
75 | val cardTitle = root.findViewById(id.card_title) as TextView
76 | cardTitle.text = mContext.resources.getString(string.card_title, position)
77 | return root
78 | }
79 |
80 | override fun getAnimatorForView(
81 | view: View,
82 | currentCardPosition: Int,
83 | selectedCardPosition: Int
84 | ): Animator {
85 | return if (PrefsUtil.isReverseClickAnimationEnabled) {
86 |
87 | val offsetTop = scrollOffset
88 |
89 | if (currentCardPosition > selectedCardPosition) {
90 | ObjectAnimator.ofFloat(view, View.Y, view.y, offsetTop + getCardFinalY(currentCardPosition))
91 | } else {
92 | ObjectAnimator.ofFloat(view, View.Y, view.y, offsetTop.toFloat() + getCardOriginalY(0) + currentCardPosition * cardGapBottom)
93 | }
94 | } else {
95 | super.getAnimatorForView(view, currentCardPosition, selectedCardPosition)
96 | }
97 | }
98 |
99 | private fun getSettingsView(container: ViewGroup): View {
100 | val root = mInflater.inflate(layout.settings_card, container, false) as CardView
101 | root.setCardBackgroundColor(ContextCompat.getColor(mContext, color.colorPaleGrey))
102 |
103 | val showInitAnimation = root.findViewById(id.show_init_animation) as Switch
104 | val parallaxEnabled = root.findViewById(id.parallax_enabled) as Switch
105 | val reverseClickAnimation = root.findViewById(id.reverse_click_animation) as Switch
106 | val parallaxScale = root.findViewById(id.parallax_scale) as EditText
107 | val cardGap = root.findViewById(id.card_gap) as EditText
108 | val cardGapBottom = root.findViewById(id.card_gap_bottom) as EditText
109 |
110 | updateSettingsView = Runnable {
111 | showInitAnimation.isChecked = PrefsUtil.isShowInitAnimationEnabled
112 | showInitAnimation.setOnCheckedChangeListener(this@MyCardStackAdapter)
113 |
114 | reverseClickAnimation.isChecked = PrefsUtil.isReverseClickAnimationEnabled
115 | reverseClickAnimation.setOnCheckedChangeListener(this@MyCardStackAdapter)
116 |
117 | val isParallaxEnabled = PrefsUtil.isParallaxEnabled
118 | parallaxEnabled.isChecked = isParallaxEnabled
119 | parallaxEnabled.setOnCheckedChangeListener(this@MyCardStackAdapter)
120 |
121 | parallaxScale.setText("${PrefsUtil.getParallaxScale(mContext)}")
122 | parallaxScale.isEnabled = isParallaxEnabled
123 |
124 | cardGap.setText("${PrefsUtil.getCardGap(mContext)}")
125 |
126 | cardGapBottom.setText("${PrefsUtil.getCardGapBottom(mContext)}")
127 | }
128 |
129 | updateSettingsView?.run()
130 |
131 | val restartActivityButton = root.findViewById(id.restart_activity) as Button
132 | restartActivityButton.setOnClickListener {
133 | updatePrefsIfRequired(parallaxScale)
134 | updatePrefsIfRequired(cardGap)
135 | updatePrefsIfRequired(cardGapBottom)
136 | mCallback.requestRestart()
137 | }
138 |
139 | val resetDefaultsButton = root.findViewById(id.reset_defaults) as Button
140 | resetDefaultsButton.setOnClickListener {
141 | PrefsUtil.resetDefaults(mContext)
142 | updateSettingsView?.run()
143 | }
144 |
145 | return root
146 | }
147 |
148 | private fun updatePrefsIfRequired(view: EditText) {
149 | val text = view.text.toString()
150 | val value: Int
151 |
152 | value = try {
153 | Integer.parseInt(text)
154 | } catch (e: Exception) {
155 | Integer.MIN_VALUE
156 | }
157 |
158 | if (value == Integer.MIN_VALUE) {
159 | Timber.e("Invalid value for ${view.resources.getResourceName(view.id)}")
160 | return
161 | }
162 |
163 | when (view.id) {
164 | id.parallax_scale -> {
165 | Timber.d("parallax_scale now is ${Integer.parseInt(text)}")
166 | Pref.putInt(PrefsUtil.PARALLAX_SCALE, Integer.parseInt(text))
167 | }
168 | id.card_gap -> {
169 | Timber.d("card_gap now is ${Integer.parseInt(text)}")
170 | Pref.putInt(PrefsUtil.CARD_GAP, Integer.parseInt(text))
171 | }
172 | id.card_gap_bottom -> {
173 | Timber.d("card_gap_bottom now is ${Integer.parseInt(text)}")
174 | Pref.putInt(PrefsUtil.CARD_GAP_BOTTOM, Integer.parseInt(text))
175 | }
176 | }
177 | }
178 | }
--------------------------------------------------------------------------------
/cardstack/src/main/java/com/mutualmobile/cardstack/CardStackLayout.kt:
--------------------------------------------------------------------------------
1 | package com.mutualmobile.cardstack
2 |
3 | import android.annotation.TargetApi
4 | import android.content.Context
5 | import android.os.Build
6 | import android.util.AttributeSet
7 | import android.view.MotionEvent
8 | import android.view.View
9 | import android.view.ViewGroup
10 | import android.widget.FrameLayout
11 | import android.widget.ScrollView
12 |
13 | /**
14 | * Displays a list of cards as a stack on the screen.
15 | *
16 | *
17 | * **XML attributes**
18 | *
19 | *
20 | * See [CardStackLayout Attributes][R.styleable.CardStackLayout]
21 | *
22 | *
23 | * [R.styleable.CardStackLayout_showInitAnimation]
24 | * [R.styleable.CardStackLayout_card_gap]
25 | * [R.styleable.CardStackLayout_card_gap_bottom]
26 | * [R.styleable.CardStackLayout_parallax_enabled]
27 | * [R.styleable.CardStackLayout_parallax_scale]
28 | */
29 | class CardStackLayout : ScrollView {
30 | companion object {
31 | const val PARALLAX_ENABLED_DEFAULT = false
32 | const val SHOW_INIT_ANIMATION_DEFAULT = true
33 | }
34 |
35 | /**
36 | * @return gap between the two consecutive cards when collapsed to the bottom of the screen
37 | */
38 | var cardGapBottom: Float = 0.toFloat()
39 | /**
40 | * @return the gap (in pixels) between two consecutive cards
41 | */
42 | /**
43 | * Set the gap (in pixels) between two consecutive cards
44 | */
45 | var cardGap: Float = 0.toFloat()
46 | var isShowInitAnimation: Boolean = false
47 | var isParallaxEnabled: Boolean = false
48 | /**
49 | * @return currently set parallax scale value.
50 | */
51 | /**
52 | * Sets the value of parallax scale. Parallax scale is the factor which decides how much
53 | * distance a card will scroll when the user drags it down.
54 | */
55 | var parallaxScale: Int = 0
56 | /**
57 | * package restricted
58 | */
59 | /**
60 | * Listen on card selection events for [CardStackLayout]. Sends clicked view and it's
61 | * corresponding position in the callback.
62 | *
63 | * @param onCardSelectedListener listener
64 | */
65 | internal var onCardSelectedListener: OnCardSelected? = null
66 |
67 | var isScrollable = true
68 | private set
69 |
70 | private var mAdapter: CardStackAdapter? = null
71 | var frame: FrameLayout? = null
72 | private set
73 |
74 | /**
75 | * @return adapter of type [CardStackAdapter] that is set for this view.
76 | */
77 | /**
78 | * Set the adapter for this [CardStackLayout]
79 | *
80 | * @param adapter Should extend [CardStackAdapter]
81 | */
82 | var adapter: CardStackAdapter?
83 | get() = mAdapter
84 | set(adapter) {
85 | this.mAdapter = adapter
86 | mAdapter?.setAdapterParams(this)
87 | mAdapter?.count?.let { count ->
88 | for (i in 0 until count) {
89 | mAdapter?.addView(i)
90 | }
91 | }
92 |
93 | if (isShowInitAnimation) {
94 | postDelayed({ restoreCards() }, 500)
95 | }
96 | }
97 |
98 | /**
99 | * @return true if a card is selected, false otherwise
100 | */
101 | val isCardSelected: Boolean
102 | get() = mAdapter?.isCardSelected ?: false
103 |
104 | constructor(context: Context) : super(context) {
105 | init(context, null, 0, 0)
106 | }
107 |
108 | constructor(
109 | context: Context,
110 | attrs: AttributeSet
111 | ) : super(context, attrs) {
112 | init(context, attrs, 0, 0)
113 | }
114 |
115 | constructor(
116 | context: Context,
117 | attrs: AttributeSet,
118 | defStyleAttr: Int
119 | ) : super(context, attrs, defStyleAttr) {
120 | init(context, attrs, defStyleAttr, 0)
121 | }
122 |
123 | @TargetApi(Build.VERSION_CODES.LOLLIPOP)
124 | constructor(
125 | context: Context,
126 | attrs: AttributeSet,
127 | defStyleAttr: Int,
128 | defStyleRes: Int
129 | ) : super(context, attrs, defStyleAttr, defStyleRes) {
130 | init(context, attrs, defStyleAttr, defStyleRes)
131 | }
132 |
133 | private fun init(
134 | context: Context,
135 | attrs: AttributeSet?,
136 | defStyleAttr: Int,
137 | defStyleRes: Int
138 | ) {
139 | resetDefaults()
140 |
141 | if (attrs != null) {
142 | val a = context.theme.obtainStyledAttributes(attrs, R.styleable.CardStackLayout, defStyleAttr, defStyleRes)
143 | isParallaxEnabled = a.getBoolean(R.styleable.CardStackLayout_parallax_enabled, PARALLAX_ENABLED_DEFAULT)
144 | isShowInitAnimation = a.getBoolean(R.styleable.CardStackLayout_showInitAnimation, SHOW_INIT_ANIMATION_DEFAULT)
145 | parallaxScale = a.getInteger(R.styleable.CardStackLayout_parallax_scale, resources.getInteger(R.integer.parallax_scale_default))
146 | cardGap = a.getDimension(R.styleable.CardStackLayout_card_gap, resources.getDimension(R.dimen.card_gap))
147 | cardGapBottom = a.getDimension(R.styleable.CardStackLayout_card_gap_bottom, resources.getDimension(R.dimen.card_gap_bottom))
148 | a.recycle()
149 | } else {
150 | isParallaxEnabled = PARALLAX_ENABLED_DEFAULT
151 | isShowInitAnimation = SHOW_INIT_ANIMATION_DEFAULT
152 | parallaxScale = resources.getInteger(R.integer.parallax_scale_default)
153 | cardGap = resources.getDimension(R.dimen.card_gap)
154 | cardGapBottom = resources.getDimension(R.dimen.card_gap_bottom)
155 | }
156 |
157 | isFillViewport = true
158 | isVerticalScrollBarEnabled = false
159 |
160 | frame = CardFrameLayout(this)
161 |
162 | addView(frame, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
163 | }
164 |
165 | fun setScrollingEnabled(enabled: Boolean) {
166 | isScrollable = enabled
167 | }
168 |
169 | override fun onTouchEvent(ev: MotionEvent): Boolean {
170 | return when (ev.action) {
171 | MotionEvent.ACTION_DOWN -> {
172 | // if we can scroll pass the event to the superclass
173 | if (isScrollable) super.onTouchEvent(ev) else false
174 |
175 | // only continue to handle the touch event if scrolling enabled
176 | // mScrollable is always false at this point
177 | }
178 | else -> super.onTouchEvent(ev)
179 | }
180 | }
181 |
182 | override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
183 | // Don't do anything with intercepted touch events if
184 | // we are not scrollable
185 | return isScrollable && super.onInterceptTouchEvent(ev)
186 | }
187 |
188 | private fun resetDefaults() {
189 | onCardSelectedListener = null
190 | }
191 |
192 | /**
193 | * Removes the adapter that was previously set using [.setAdapter]
194 | */
195 | fun removeAdapter() {
196 | frame?.childCount?.let {
197 | if (it > 0) {
198 | frame?.removeAllViews()
199 | }
200 | }
201 |
202 | mAdapter = null
203 | onCardSelectedListener = null
204 | }
205 |
206 | /**
207 | * Animates the cards to their initial position in the layout.
208 | */
209 | @JvmOverloads
210 | fun restoreCards(r: Runnable? = null) {
211 | mAdapter?.resetCards(r)
212 | }
213 |
214 | /**
215 | * Intimates the implementing class about the selection of a card
216 | */
217 | interface OnCardSelected {
218 | fun onCardSelected(
219 | v: View,
220 | position: Int
221 | )
222 | }
223 | }
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/cardstack/src/main/java/com/mutualmobile/cardstack/CardStackAdapter.kt:
--------------------------------------------------------------------------------
1 | package com.mutualmobile.cardstack
2 |
3 | import android.animation.Animator
4 | import android.animation.AnimatorListenerAdapter
5 | import android.animation.AnimatorSet
6 | import android.animation.ObjectAnimator
7 | import android.content.Context
8 | import android.content.res.Resources
9 | import android.view.MotionEvent
10 | import android.view.View
11 | import android.view.ViewGroup
12 | import android.view.animation.DecelerateInterpolator
13 | import android.widget.FrameLayout
14 | import java.util.ArrayList
15 |
16 | /**
17 | * This class acts as an adapter for the [CardStackLayout] view. This adapter is intentionally
18 | * made an abstract class with following abstract methods -
19 | *
20 | *
21 | *
22 | *
23 | * [.getCount] - Decides the number of views present in the view
24 | *
25 | *
26 | * [.createView] - Creates the view for all positions in range [0, [.getCount])
27 | *
28 | *
29 | * Contains the logic for touch events in [.onTouch]
30 | */
31 | abstract class CardStackAdapter(context: Context) : View.OnTouchListener, View.OnClickListener {
32 | companion object {
33 | // Animation constants
34 | const val ANIM_DURATION = 600
35 | const val DECELERATION_FACTOR = 2
36 | const val INVALID_CARD_POSITION = -1
37 | }
38 |
39 | private val mScreenHeight: Int
40 | private val dp30: Int
41 | private val maxDistanceToConsiderAsClick: Float
42 |
43 | // Settings for the adapter from layout
44 | protected var cardGapBottom: Float = 0F
45 | private var mCardGap: Float = 0F
46 | private var mParallaxScale: Int = 0
47 | private var mParallaxEnabled: Boolean = false
48 | private var mShowInitAnimation: Boolean = false
49 | private var mScrollParent: CardStackLayout? = null
50 | private var mFrame: FrameLayout? = null
51 | private var mCardViews: ArrayList = arrayListOf()
52 |
53 | var fullCardHeight: Int = 0
54 | private set
55 |
56 | /**
57 | * Returns true if no animation is in progress currently. Can be used to disable any events
58 | * if they are not allowed during an animation. Returns false if an animation is in progress.
59 | *
60 | * @return - true if animation in progress, false otherwise
61 | */
62 | var isScreenTouchable = false
63 | private set
64 | private var mTouchFirstY = -1f
65 | private var mTouchPrevY = -1f
66 | private var mTouchDistance = 0f
67 | /**
68 | * Returns the position of selected card. If no card
69 | * is selected, returns [.INVALID_CARD_POSITION]
70 | */
71 | var selectedCardPosition = INVALID_CARD_POSITION
72 | private set
73 | private val scaleFactorForElasticEffect: Float
74 | private var mParentPaddingTop = 0
75 | private var mCardPaddingInternal = 0
76 |
77 | /**
78 | * Defines the number of cards that are present in the [CardStackLayout]
79 | *
80 | * @return cardCount - Number of views in the related [CardStackLayout]
81 | */
82 | abstract val count: Int
83 |
84 | protected val scrollOffset: Int
85 | get() = mScrollParent?.scrollY ?: 0
86 |
87 | /**
88 | * Returns false if all the cards are in their initial position i.e. no card is selected
89 | *
90 | *
91 | * Returns true if the [CardStackLayout] has a card selected and all other cards are
92 | * at the bottom of the screen.
93 | *
94 | * @return true if any card is selected, false otherwise
95 | */
96 | val isCardSelected: Boolean
97 | get() = selectedCardPosition != INVALID_CARD_POSITION
98 |
99 | init {
100 | val resources = context.resources
101 |
102 | val dm = Resources.getSystem()
103 | .displayMetrics
104 | mScreenHeight = dm.heightPixels
105 | dp30 = resources.getDimension(R.dimen.dp30)
106 | .toInt()
107 | scaleFactorForElasticEffect = resources.getDimension(R.dimen.dp8)
108 | .toInt()
109 | .toFloat()
110 | maxDistanceToConsiderAsClick = resources.getDimension(R.dimen.dp8)
111 | .toInt()
112 | .toFloat()
113 | }
114 |
115 | /**
116 | * Defines and initializes the view to be shown in the [CardStackLayout]
117 | * Provides two parameters to the sub-class namely -
118 | *
119 | * @param position
120 | * @param container
121 | * @return View corresponding to the position and parent container
122 | */
123 | abstract fun createView(
124 | position: Int,
125 | container: ViewGroup?
126 | ): View
127 |
128 | internal fun addView(position: Int) {
129 | val root = createView(position, mFrame)
130 | root.setOnTouchListener(this)
131 | root.setTag(R.id.cardstack_internal_position_tag, position)
132 | root.setLayerType(View.LAYER_TYPE_HARDWARE, null)
133 | root.isFocusable = true
134 | root.isFocusableInTouchMode = true
135 |
136 | mCardPaddingInternal = root.paddingTop
137 |
138 | val lp = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, fullCardHeight)
139 | root.layoutParams = lp
140 | if (mShowInitAnimation) {
141 | root.y = getCardFinalY(position)
142 | isScreenTouchable = false
143 | } else {
144 | root.y = getCardOriginalY(position) - mParentPaddingTop
145 | isScreenTouchable = true
146 | }
147 |
148 | mCardViews[position] = root
149 |
150 | mFrame?.addView(root)
151 | }
152 |
153 | protected fun getCardFinalY(position: Int): Float {
154 | return mScreenHeight.toFloat() - dp30.toFloat() - (count - position) * cardGapBottom - mCardPaddingInternal.toFloat()
155 | }
156 |
157 | protected fun getCardOriginalY(position: Int): Float {
158 | return mParentPaddingTop + mCardGap * position
159 | }
160 |
161 | /**
162 | * Resets all cards in [CardStackLayout] to their initial positions
163 | *
164 | * @param r Execute r.run() once the reset animation is done
165 | */
166 | @JvmOverloads
167 | fun resetCards(r: Runnable? = null) {
168 | val animations = ArrayList(count)
169 | for (i in 0 until count) {
170 | val child = mCardViews[i]
171 | animations.add(ObjectAnimator.ofFloat(child, View.Y, child.y, getCardOriginalY(i)))
172 | }
173 | startAnimations(animations, r, true)
174 | }
175 |
176 | /**
177 | * Plays together all animations passed in as parameter. Once animation is completed, r.run() is
178 | * executed. If parameter isReset is set to true, [.mSelectedCardPosition] is set to [.INVALID_CARD_POSITION]
179 | *
180 | * @param animations
181 | * @param r
182 | * @param isReset
183 | */
184 | private fun startAnimations(
185 | animations: List,
186 | r: Runnable?,
187 | isReset: Boolean
188 | ) {
189 | val animatorSet = AnimatorSet()
190 | animatorSet.playTogether(animations)
191 | animatorSet.duration = ANIM_DURATION.toLong()
192 | animatorSet.interpolator = DecelerateInterpolator(DECELERATION_FACTOR.toFloat())
193 | animatorSet.addListener(object : AnimatorListenerAdapter() {
194 | override fun onAnimationEnd(animation: Animator) {
195 | r?.run()
196 |
197 | isScreenTouchable = true
198 |
199 | if (isReset) {
200 | selectedCardPosition = INVALID_CARD_POSITION
201 | mScrollParent?.setScrollingEnabled(true)
202 | }
203 | }
204 | })
205 | animatorSet.start()
206 | }
207 |
208 | override fun onTouch(
209 | v: View,
210 | event: MotionEvent
211 | ): Boolean {
212 | if (!isScreenTouchable) {
213 | return false
214 | }
215 |
216 | val y = event.rawY
217 | val positionOfCardToMove = v.getTag(R.id.cardstack_internal_position_tag) as Int
218 |
219 | when (event.action) {
220 | MotionEvent.ACTION_DOWN -> {
221 | if (mTouchFirstY != -1f) {
222 | return false
223 | }
224 | mTouchFirstY = y
225 | mTouchPrevY = mTouchFirstY
226 | mTouchDistance = 0f
227 | }
228 | MotionEvent.ACTION_MOVE -> {
229 | if (selectedCardPosition == INVALID_CARD_POSITION)
230 | moveCards(positionOfCardToMove, y - mTouchFirstY)
231 | mTouchDistance += Math.abs(y - mTouchPrevY)
232 | }
233 | MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
234 | if (mTouchDistance < maxDistanceToConsiderAsClick && Math.abs(y - mTouchFirstY) < maxDistanceToConsiderAsClick) {
235 | if (selectedCardPosition == INVALID_CARD_POSITION) {
236 | onClick(v)
237 | } else {
238 | resetCards()
239 | }
240 | }
241 | mTouchFirstY = -1f
242 | mTouchPrevY = mTouchFirstY
243 | mTouchDistance = 0f
244 | return false
245 | }
246 | }
247 | return true
248 | }
249 |
250 | override fun onClick(v: View) {
251 |
252 | if (!isScreenTouchable) {
253 | return
254 | }
255 | isScreenTouchable = false
256 |
257 | mScrollParent?.setScrollingEnabled(false)
258 | if (selectedCardPosition == INVALID_CARD_POSITION) {
259 | selectedCardPosition = v.getTag(R.id.cardstack_internal_position_tag) as Int
260 |
261 | val animations = ArrayList(count)
262 | for (i in 0 until count) {
263 | val child = mCardViews[i]
264 | animations.add(getAnimatorForView(child, i, selectedCardPosition))
265 | }
266 | startAnimations(animations, Runnable {
267 | isScreenTouchable = true
268 | if (mScrollParent?.onCardSelectedListener != null) {
269 | mScrollParent?.onCardSelectedListener?.onCardSelected(v, selectedCardPosition)
270 | }
271 | }, false)
272 |
273 | }
274 | }
275 |
276 | /**
277 | * This method can be overridden to have different animations for each card when a click event
278 | * happens on any card view. This method will be called for every
279 | *
280 | * @param view The view for which this method needs to return an animator
281 | * @param selectedCardPosition Position of the card that was clicked
282 | * @param currentCardPosition Position of the current card
283 | * @return animator which has to be applied on the current card
284 | */
285 | protected fun getAnimatorForView(
286 | view: View,
287 | currentCardPosition: Int,
288 | selectedCardPosition: Int
289 | ): Animator {
290 | val offsetTop = scrollOffset
291 |
292 | return if (currentCardPosition != selectedCardPosition) {
293 | ObjectAnimator.ofFloat(view, View.Y, view.y, offsetTop + getCardFinalY(currentCardPosition))
294 | } else {
295 | ObjectAnimator.ofFloat(view, View.Y, view.y, offsetTop + getCardOriginalY(0))
296 | }
297 | }
298 |
299 | private fun moveCards(
300 | positionOfCardToMove: Int,
301 | diff: Float
302 | ) {
303 | if (diff < 0 || positionOfCardToMove < 0 || positionOfCardToMove >= count) return
304 | for (i in positionOfCardToMove until count) {
305 | val child = mCardViews[i]
306 | var diffCard = diff / scaleFactorForElasticEffect
307 | diffCard = if (mParallaxEnabled) {
308 | if (mParallaxScale > 0) {
309 | diffCard * (mParallaxScale / 3).toFloat() * (count + 1 - i).toFloat()
310 | } else {
311 | val scale = mParallaxScale * -1
312 | diffCard * (i * (scale / 3) + 1)
313 | }
314 | } else
315 | diffCard * (count * 2 + 1)
316 | child.y = getCardOriginalY(i) + diffCard
317 | }
318 | }
319 |
320 | /**
321 | * Provides an API to [CardStackLayout] to set the parameters provided to it in its XML
322 | *
323 | * @param cardStackLayout Parent of all cards
324 | */
325 | internal fun setAdapterParams(cardStackLayout: CardStackLayout) {
326 | mScrollParent = cardStackLayout
327 | mFrame = cardStackLayout.frame
328 |
329 | cardGapBottom = cardStackLayout.cardGapBottom
330 | mCardGap = cardStackLayout.cardGap
331 | mParallaxScale = cardStackLayout.parallaxScale
332 | mParallaxEnabled = cardStackLayout.isParallaxEnabled
333 | if (mParallaxEnabled && mParallaxScale == 0)
334 | mParallaxEnabled = false
335 | mShowInitAnimation = cardStackLayout.isShowInitAnimation
336 |
337 | mParentPaddingTop = cardStackLayout.paddingTop
338 | fullCardHeight = (mScreenHeight.toFloat() - dp30.toFloat() - count * cardGapBottom).toInt()
339 | }
340 |
341 | /**
342 | * Since there is no view recycling in [CardStackLayout], we maintain an instance of every
343 | * view that is set for every position. This method returns a view at the requested position.
344 | *
345 | * @param position Position of card in [CardStackLayout]
346 | * @return View at requested position
347 | */
348 | fun getCardView(position: Int) = mCardViews[position]
349 | }
--------------------------------------------------------------------------------