diff --git a/LICENSE 2 b/LICENSE 2 new file mode 100644 index 0000000..8dada3e --- /dev/null +++ b/LICENSE 2 @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index 17ca74c..1e410b3 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,113 @@ -# hfradapter -HFRAdapter - Easy as it should be :) +# HFRAdapter - Easy as it should be :) +============== + +Header + Footer + Parallax + Loading + Less Boilerplate code Adapter + + +## I tried to make it easier to deal with RecyclerView Adapter + +Screenshots: +-------- + +// SOON + +## Usage : + + +Java: +``` java + + // The adaoter class looks like this: + public class ParallaxHFRAdapterTest extends ParallaxHFRAdapter { + + public ParallaxHFRAdapterTest(List items) { + super(items); + } + + public ParallaxHFRAdapterTest() {} + + @Override + protected void onBindItemViewHolder(MyViewHolder viewHolder, int position, int type) { + viewHolder.bind(getItem(position)); + } + + @Override + protected MyViewHolder viewHolder(View view, int type) { + return new MyViewHolder(view); + } + + @Override + protected int layoutId(int type) { + return R.layout.item_text; + } + } + + // in the activity + public class MainActivity extends Activity { + private RecyclerView recyclerView; + private ParallaxHFRAdapterTest parallaxHfAdapter; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_hfradapter); + + recyclerView = (RecyclerView) findViewById(R.id.recyclerView); + recyclerView.setLayoutManager(new ALinearLayoutManager(this)); + parallaxHfAdapter = new ParallaxHFRAdapterTest(getItems()); + recyclerView.setAdapter(parallaxHfAdapter); + + parallaxHfAdapter.addHeader(this, R.layout.v_header); + parallaxHfAdapter.addFooter(this, R.layout.v_footer); + parallaxHfAdapter.setLoadingView(this, R.layout.v_loading); + parallaxHfAdapter.setParallaxHeader(true); + parallaxHfAdapter.setParallaxFooter(true); + + } + } +``` + +Install +-------- + +You can install using Gradle: + +```gradle + repositories { + maven { url "https://jitpack.io" } + } + dependencies { + compile 'com.github.iballan:hfradapter:1.0.0' + } +``` + +Contact me: +-------- + +Twitter: [@mbh01t](https://twitter.com/mbh01t) + +Github: [iballan](https://github.com/iballan) + +Website: [www.mbh01.com](http://mbh01.com) + +Credits: +-------- + + + +License +-------- + + Copyright 2017 Mohamad Ballan. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..ec1ce4b --- /dev/null +++ b/build.gradle @@ -0,0 +1,16 @@ +buildscript { + repositories { +// mavenCentral() + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:2.3.1' + } +} + +allprojects { + repositories { +// mavenCentral() + jcenter() + } +} \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..13372ae Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..c12eb4b --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Sun Apr 30 22:22:10 EEST 2017 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..91a7e26 --- /dev/null +++ b/gradlew @@ -0,0 +1,164 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# For Cygwin, ensure paths are in UNIX format before anything is touched. +if $cygwin ; then + [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` +fi + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >&- +APP_HOME="`pwd -P`" +cd "$SAVED" >&- + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..8a0b282 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windowz variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/hfradapter/.gitignore b/hfradapter/.gitignore new file mode 100644 index 0000000..34e5e5d --- /dev/null +++ b/hfradapter/.gitignore @@ -0,0 +1,34 @@ +# built application files +*.apk +*.ap_ + +# files for the dex VM +*.dex + +# Java class files +*.class + +# generated files +bin/ +gen/ + +# Local configuration file (sdk path, etc) +local.properties +gradle.properties + +# Eclipse project files +.classpath +.project + +# Proguard folder generated by Eclipse +proguard/ + +# Intellij project files +*.iml +*.ipr +*.iws +.idea/ + +# OSX files +.DS_Store +.gradle \ No newline at end of file diff --git a/hfradapter/build.gradle b/hfradapter/build.gradle new file mode 100644 index 0000000..261c633 --- /dev/null +++ b/hfradapter/build.gradle @@ -0,0 +1,29 @@ +apply plugin: 'com.android.library' + +dependencies { + compile 'com.android.support:support-annotations:25.3.1' + compile 'com.android.support:recyclerview-v7:25.3.1' +} + +android { + compileSdkVersion 25 + buildToolsVersion "25.0.2" + + defaultConfig { + minSdkVersion 9 + targetSdkVersion 25 + versionCode 1 + versionName "1.0.0" + } + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + buildTypes { + release { + minifyEnabled false + } + } +} \ No newline at end of file diff --git a/hfradapter/src/main/AndroidManifest.xml b/hfradapter/src/main/AndroidManifest.xml new file mode 100644 index 0000000..d69e78d --- /dev/null +++ b/hfradapter/src/main/AndroidManifest.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/hfradapter/src/main/java/com/mbh/hfradapter/AGridLayoutManager.java b/hfradapter/src/main/java/com/mbh/hfradapter/AGridLayoutManager.java new file mode 100644 index 0000000..7b7e1aa --- /dev/null +++ b/hfradapter/src/main/java/com/mbh/hfradapter/AGridLayoutManager.java @@ -0,0 +1,34 @@ +package com.mbh.hfradapter; + +import android.content.Context; +import android.support.v7.widget.GridLayoutManager; +import android.support.v7.widget.RecyclerView; +import android.util.AttributeSet; +import android.util.Log; + +/** + * Createdby MBH on 25/04/2017. + */ + +public class AGridLayoutManager extends GridLayoutManager { + public AGridLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { + super(context, attrs, defStyleAttr, defStyleRes); + } + + public AGridLayoutManager(Context context, int spanCount) { + super(context, spanCount); + } + + public AGridLayoutManager(Context context, int spanCount, int orientation, boolean reverseLayout) { + super(context, spanCount, orientation, reverseLayout); + } + + @Override + public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) { + try { + super.onLayoutChildren(recycler, state); + } catch (IndexOutOfBoundsException e) { + Log.e("HFRAdapter", "GLM - onLayoutChildren"); + } + } +} diff --git a/hfradapter/src/main/java/com/mbh/hfradapter/ALinearLayoutManager.java b/hfradapter/src/main/java/com/mbh/hfradapter/ALinearLayoutManager.java new file mode 100644 index 0000000..e52fa91 --- /dev/null +++ b/hfradapter/src/main/java/com/mbh/hfradapter/ALinearLayoutManager.java @@ -0,0 +1,37 @@ +package com.mbh.hfradapter; + +import android.content.Context; +import android.support.v7.widget.LinearLayoutManager; +import android.support.v7.widget.RecyclerView; +import android.util.AttributeSet; +import android.util.Log; + + +/** + * Createdby MBH on 25/04/2017. + */ + +public class ALinearLayoutManager extends LinearLayoutManager { + + + @Override + public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) { + try { + super.onLayoutChildren(recycler, state); + } catch (IndexOutOfBoundsException e) { + Log.e("HFRAdapter", "LLM - onLayoutChildren"); + } + } + + public ALinearLayoutManager(Context context) { + super(context); + } + + public ALinearLayoutManager(Context context, int orientation, boolean reverseLayout) { + super(context, orientation, reverseLayout); + } + + public ALinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { + super(context, attrs, defStyleAttr, defStyleRes); + } +} diff --git a/hfradapter/src/main/java/com/mbh/hfradapter/ClipContainer.java b/hfradapter/src/main/java/com/mbh/hfradapter/ClipContainer.java new file mode 100644 index 0000000..1fe8a0a --- /dev/null +++ b/hfradapter/src/main/java/com/mbh/hfradapter/ClipContainer.java @@ -0,0 +1,117 @@ +package com.mbh.hfradapter; + +import android.content.Context; +import android.graphics.Canvas; +import android.graphics.Rect; +import android.os.Parcel; +import android.os.Parcelable; +import android.support.annotation.NonNull; +import android.widget.FrameLayout; + + +/** + * Createdby MBH on 02/03/2017. + */ +public class ClipContainer extends FrameLayout { + + private boolean isParallax; + private boolean isFooter; + private int offset; + + public ClipContainer(@NonNull Context context) { + super(context); + this.isParallax = true; + this.isFooter = false; + this.offset = 0; + } + + public ClipContainer(Context context, boolean shouldClick, boolean isFooter) { + super(context); + isParallax = shouldClick; + this.isFooter = isFooter; + } + + @Override + protected void dispatchDraw(@NonNull Canvas canvas) { + if (isParallax) { + int top = isFooter ? -offset : 0; + int bottom = isFooter ? getBottom() : getBottom() + offset; + Rect rect = new Rect(getLeft(), top, getRight(), bottom); + canvas.clipRect(rect); + } + super.dispatchDraw(canvas); + } + + public void setOffset(int offset) { + this.offset = offset; + } + + @Override + protected void onRestoreInstanceState(Parcelable state) { + if (!(state instanceof SavedState)) { + super.onRestoreInstanceState(state); + return; + } + SavedState ss = (SavedState) state; + super.onRestoreInstanceState(ss.getSuperState()); + offset = ss.offset; + isParallax = ss.isParallax; + isFooter = ss.isFooter; + invalidate(); + } + + @Override + protected Parcelable onSaveInstanceState() { + SavedState savedState = new SavedState(super.onSaveInstanceState()); + savedState.offset = offset; + savedState.isParallax = isParallax; + savedState.isFooter = isFooter; + return savedState; + } + + private static class SavedState extends BaseSavedState { + int offset; + boolean isParallax; + boolean isFooter; + + SavedState(Parcelable superState) { + super(superState); + } + + @Override + public String toString() { + return "ClipContainer.SavedState{" + + "offset=" + offset + + "isParallax=" + isParallax + + "isFooter=" + isFooter + + '}'; + } + + @Override + public void writeToParcel(Parcel dest, int flags) { + super.writeToParcel(dest, flags); + dest.writeInt(this.offset); + dest.writeByte(this.isParallax ? (byte) 1 : (byte) 0); + dest.writeByte(this.isFooter ? (byte) 1 : (byte) 0); + } + + SavedState(Parcel in) { + super(in); + this.offset = in.readInt(); + this.isParallax = in.readByte() != 0; + this.isFooter = in.readByte() != 0; + } + + public static final Creator CREATOR = new Creator() { + @Override + public SavedState createFromParcel(Parcel source) { + return new SavedState(source); + } + + @Override + public SavedState[] newArray(int size) { + return new SavedState[size]; + } + }; + } +} diff --git a/hfradapter/src/main/java/com/mbh/hfradapter/HFRAdapter.java b/hfradapter/src/main/java/com/mbh/hfradapter/HFRAdapter.java new file mode 100644 index 0000000..752bfe8 --- /dev/null +++ b/hfradapter/src/main/java/com/mbh/hfradapter/HFRAdapter.java @@ -0,0 +1,637 @@ +package com.mbh.hfradapter; + +import android.content.Context; +import android.os.Bundle; +import android.os.Parcelable; +import android.support.annotation.LayoutRes; +import android.support.v7.widget.GridLayoutManager; +import android.support.v7.widget.LinearLayoutManager; +import android.support.v7.widget.RecyclerView; +import android.support.v7.widget.StaggeredGridLayoutManager; +import android.text.Layout; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.FrameLayout; + +import java.io.Serializable; +import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.List; + +/** + * Createdby MBH on 02/03/2017. + */ + +public abstract class HFRAdapter extends RecyclerView.Adapter { + + static final int TYPE_HEADER = 9876; + static final int TYPE_FOOTER = 9875; + static final int TYPE_LOADING = 9874; + private static final String P_ITEMS = "HFR.items"; + private static final String P_HEADERS = "HFRh"; + private static final String P_FOOTERS = "HFRf"; + private static final String P_LOADING = "HFRl"; + + private OnItemClickedListener mOnItemClickedListener; + private OnLoadMoreListener mOnLoadMoreListener; + + private ArrayList headers = new ArrayList<>(); + private ArrayList footers = new ArrayList<>(); + private View loadingView; + List items = new ArrayList<>(); + + private boolean isLoading = false; + private boolean isAutoLoading = false; + private boolean alwaysScrollToLoading = false; + + private WeakReference wr_recyclerView; + + public HFRAdapter(List items) {this.items = items;} + + public HFRAdapter() {} + + private RecyclerView.LayoutManager manager; + private LayoutInflater inflater; + private GridLayoutManager.SpanSizeLookup spanSizeLookup = new GridLayoutManager.SpanSizeLookup() { + @Override + public int getSpanSize(int position) { + return getGridSpan(position); + } + }; + + public int getRealItemCount() { + return items.size(); + } + + public T getItem(int position) { + return items.get(position); + } + + public void add(final int position, T item) { + items.add(position, item); + tryNotifying(new Runnable() { + @Override + public void run() { + notifyItemInserted(position); + } + }); + final int positionStart = position + getHeadersCount(); + final int itemCount = items.size() - position; + tryNotifying(new Runnable() { + @Override + public void run() { + notifyItemRangeChanged(positionStart, itemCount); + } + }); + } + + public void add(T item) { + items.add(item); + tryNotifying(new Runnable() { + @Override + public void run() { + notifyItemInserted(items.size() - 1 + getHeadersCount()); + } + }); + } + + public void setAll(List items) { + this.items.clear(); + this.items.addAll(items); + notifyDataSetChanged(); + } + public void setItems(List items) { + this.items.clear(); + this.items.addAll(items); + notifyDataSetChanged(); + } + + public void addAll(final List items) { + final int size = this.items.size(); + this.items.addAll(items); + tryNotifying(new Runnable() { + @Override + public void run() { + notifyItemRangeInserted(size + getHeadersCount(), items.size()); + } + }); + } + + public void addAll(final int position, final List items) { + this.items.addAll(position, items); + tryNotifying(new Runnable() { + @Override + public void run() { + notifyItemRangeInserted(position + getHeadersCount(), items.size()); + } + }); + } + + public void set(final int position, T item) { + items.set(position, item); + tryNotifying(new Runnable() { + @Override + public void run() { + notifyItemChanged(position + getHeadersCount()); + } + }); + } + + public void removeChild(final int position) { + items.remove(position); + tryNotifying(new Runnable() { + @Override + public void run() { + notifyItemRemoved(position + getHeadersCount()); + } + }); + final int positionStart = position + getHeadersCount(); + final int itemCount = items.size() - position; + tryNotifying(new Runnable() { + @Override + public void run() { + notifyItemRangeChanged(positionStart, itemCount); + } + }); + } + + public void clear() { + final int size = items.size(); + items.clear(); + tryNotifying(new Runnable() { + @Override + public void run() { + notifyItemRangeRemoved(getHeadersCount(), size); + } + }); + } + + public void notifyChildChanged(final int position) { + tryNotifying(new Runnable() { + @Override + public void run() { + notifyItemChanged(position + getHeadersCount()); + } + }); + } + + public void notifyChildRangeChanged(final int position, final int itemCount) { + tryNotifying(new Runnable() { + @Override + public void run() { + notifyItemRangeChanged(position + getHeadersCount(), itemCount); + } + }); + } + + public void notifyChildRemoved(final int position) { + tryNotifying(new Runnable() { + @Override + public void run() { + notifyItemRemoved(position + getHeadersCount()); + } + }); + } + + public void notifyChildDataSetChanged() { + tryNotifying(new Runnable() { + @Override + public void run() { + notifyItemRangeChanged(getHeadersCount(), items.size()); + } + }); + } + + public void moveChildTo(final int fromPosition, final int toPosition) { + if (toPosition != -1 && toPosition < items.size()) { + final T item = items.remove(fromPosition); + items.add(toPosition, item); + tryNotifying(new Runnable() { + @Override + public void run() { + notifyItemMoved(getHeadersCount() + fromPosition, getHeadersCount() + toPosition); + } + }); + final int positionStart = fromPosition < toPosition ? fromPosition : toPosition; + final int itemCount = Math.abs(fromPosition - toPosition) + 1; + tryNotifying(new Runnable() { + @Override + public void run() { + notifyItemRangeChanged(positionStart + getHeadersCount(), itemCount); + } + }); + } + } + + private void tryNotifying(Runnable runnable) { + try { + runnable.run(); + } catch (Exception ex) { + ex.printStackTrace(); + notifyDataSetChanged(); + } + } + + public VH getViewHolderForItemPosition(RecyclerView rv, int position) { + // Position here is item position + return (VH) rv.findViewHolderForLayoutPosition(position + getHeadersCount()); + } + + public int indexOf(T object) { + return items.indexOf(object); + } + + public List getItems() { + return items; + } + + public void setOnItemClickedListener(OnItemClickedListener onItemClickedListener) { + mOnItemClickedListener = onItemClickedListener; + } + + @Override + public VH onCreateViewHolder(ViewGroup viewGroup, int type) { + //if our position is one of our items (this comes from getItemViewType(int position) below) + if (type != TYPE_HEADER && type != TYPE_FOOTER && type != TYPE_LOADING) { + return onCreateItemViewHolder(viewGroup, type); + //else we have a header/footer/loading + } else if (type == TYPE_LOADING && loadingView != null) { + FrameLayout frameLayout = new FrameLayout(viewGroup.getContext()); + setHeaderFooterLayoutParams(frameLayout); + return (VH) new LoadingViewHolder(frameLayout); + } else { + //create a new framelayout, or inflate from a resource + FrameLayout frameLayout = new FrameLayout(viewGroup.getContext()); + //make sure it fills the space + setHeaderFooterLayoutParams(frameLayout); + return (VH) new HeaderFooterViewHolder(frameLayout); + } + } + + protected void setHeaderFooterLayoutParams(ViewGroup viewGroup) { + ViewGroup.LayoutParams layoutParams; + if (manager instanceof LinearLayoutManager) { + int orientation = ((LinearLayoutManager) manager).getOrientation(); + if (orientation == LinearLayoutManager.VERTICAL) { + layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.WRAP_CONTENT); + } else { + layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, + ViewGroup.LayoutParams.MATCH_PARENT); + } + } else { + layoutParams = new ViewGroup.LayoutParams( + ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); + } + viewGroup.setLayoutParams(layoutParams); + } + + @Override + public final void onBindViewHolder(final RecyclerView.ViewHolder vh, int position) { + //check what type of view our position is + if (isHeader(position)) { + View v = headers.get(position); + //add our view to a header view and display it + prepareHeaderFooter((HeaderFooterViewHolder) vh, v); + } else if (isFooter(position)) { + View v = footers.get(position - getRealItemCount() - getHeadersCount() - getLoadingViewCount()); + //add our view to a footer view and display it + prepareHeaderFooter((HeaderFooterViewHolder) vh, v); + } else if (isLoadingTypeView(position)) { + prepareLoadingViewHolder((LoadingViewHolder) vh, loadingView); + } else { + //it's one of our items, display as required + onBindItemViewHolder((VH) vh, position - headers.size(), getItemType(position)); + if (mOnItemClickedListener != null) { + vh.itemView.setClickable(true); + final int positionFinal = position - headers.size(); + vh.itemView.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + mOnItemClickedListener.onItemClicked(v, positionFinal); + } + }); + } + } + } + + private void prepareHeaderFooter(HeaderFooterViewHolder vh, View view) { + //if it's a staggered grid, span the whole layout + if (manager instanceof StaggeredGridLayoutManager) { + StaggeredGridLayoutManager.LayoutParams layoutParams = new StaggeredGridLayoutManager.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); + layoutParams.setFullSpan(true); + vh.itemView.setLayoutParams(layoutParams); + } + //if the view already belongs to another layout, remove it + if (view.getParent() != null) { + ((ViewGroup) view.getParent()).removeView(view); + } + //empty out our FrameLayout and replace with our header/footer + ((ViewGroup) vh.itemView).removeAllViews(); + ((ViewGroup) vh.itemView).addView(view); + } + + private void prepareLoadingViewHolder(LoadingViewHolder vh, View view) { + //if it's a staggered grid, span the whole layout + if (manager instanceof StaggeredGridLayoutManager) { + StaggeredGridLayoutManager.LayoutParams layoutParams = new StaggeredGridLayoutManager.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); + layoutParams.setFullSpan(true); + vh.itemView.setLayoutParams(layoutParams); + } + //if the view already belongs to another layout, remove it + if (view.getParent() != null) { + ((ViewGroup) view.getParent()).removeView(view); + } + //empty out our FrameLayout and replace with our header/footer + ((ViewGroup) vh.itemView).removeAllViews(); + ((ViewGroup) vh.itemView).addView(view); + } + + private boolean isHeader(int position) { + return (position < headers.size()); + } + + private boolean isLoadingTypeView(int position) { + return isLoading && (position == (headers.size() + items.size())); + } + + private boolean isFooter(int position) { + return footers.size() > 0 && (position >= getHeadersCount() + getRealItemCount() + getLoadingViewCount()); + } + + protected VH onCreateItemViewHolder(ViewGroup parent, int type) { + return viewHolder(inflater.inflate(layoutId(type), null, false), type); + } + + @Override + public int getItemCount() { + return headers.size() + getRealItemCount() + footers.size() + getLoadingViewCount(); + } + + public View getLoadingView() { + return loadingView; + } + + // add loading view to adapter + public void setLoadingView(View view) { + loadingView = view; + } + + public boolean isAlwaysScrollToLoading() { + return alwaysScrollToLoading; + } + + public void setAlwaysScrollToLoading(boolean alwaysScrollToLoading) { + this.alwaysScrollToLoading = alwaysScrollToLoading; + } + + public boolean isLoading() { + return isLoading; + } + + + public void setLoading(boolean status) { + if (loadingView != null) { + if (status != this.isLoading) { + isLoading = status; + tryNotifying(new Runnable() { + @Override + public void run() { + notifyItemChanged(headers.size() + items.size()); + if (isAlwaysScrollToLoading() && isLoading()) { + if (wr_recyclerView != null && wr_recyclerView.get() != null) { + wr_recyclerView.get().smoothScrollToPosition(headers.size() + items.size()); + } + } + } + }); + } + } else { + isLoading = false; + } + } + + public void setAutoLoading(boolean status) { + isAutoLoading = status; + setLoading(isLoading); + } + + @Override + final public int getItemViewType(int position) { + //check what type our position is, based on the assumption that the order is headers > items > footers + if (isHeader(position)) { + return TYPE_HEADER; + } else if (isFooter(position)) { + return TYPE_FOOTER; + } else if (isLoadingTypeView(position)) { + return TYPE_LOADING; + } + int type = getItemType(position); + if (type == TYPE_HEADER || type == TYPE_FOOTER || type == TYPE_LOADING) { + throw new IllegalArgumentException("Item type cannot equal " + TYPE_HEADER + " or " + TYPE_FOOTER + " or " + TYPE_LOADING); + } + return type; + } + + private void setManager(RecyclerView.LayoutManager manager) { + this.manager = manager; + if (this.manager instanceof GridLayoutManager) { + ((GridLayoutManager) this.manager).setSpanSizeLookup(spanSizeLookup); + } else if (this.manager instanceof StaggeredGridLayoutManager) { + ((StaggeredGridLayoutManager) this.manager).setGapStrategy( + StaggeredGridLayoutManager.GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS); + } + } + + protected int getGridSpan(int position) { + if (isHeader(position) || isFooter(position) || isLoadingTypeView(position)) { + return getMaxGridSpan(); + } + position -= headers.size(); +// position -= headers.size(); + if (position < getRealItemCount() && getItem(position) instanceof SpanItemInterface) { + return ((SpanItemInterface) getItem(position)).getGridSpan(); + } + return 1; + } + + protected int getMaxGridSpan() { + if (manager instanceof GridLayoutManager) { + return ((GridLayoutManager) manager).getSpanCount(); + } else if (manager instanceof StaggeredGridLayoutManager) { + return ((StaggeredGridLayoutManager) manager).getSpanCount(); + } + return 1; + } + + //add a header to the adapter + public void addHeader(View header) { + if (!headers.contains(header)) { + headers.add(header); + notifyItemInserted(headers.size() - 1); + } + } + public void addHeader(Context context, @LayoutRes int layoutId) { + addHeader(LayoutInflater.from(context).inflate(layoutId, null)); + } + + @Override + public void onAttachedToRecyclerView(RecyclerView recyclerView) { + super.onAttachedToRecyclerView(recyclerView); + wr_recyclerView = new WeakReference<>(recyclerView); + if (manager == null) { + setManager(recyclerView.getLayoutManager()); + } + if (inflater == null) { + this.inflater = LayoutInflater.from(recyclerView.getContext()); + } + recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { + @Override + public void onScrolled(RecyclerView recyclerView, int dx, int dy) { + super.onScrolled(recyclerView, dx, dy); + + if (loadingView != null) { + LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager(); + int firstVisibleItem = linearLayoutManager.findFirstVisibleItemPosition(); + int visibleItemCount = recyclerView.getChildCount(); + int totalItemCount = linearLayoutManager.getItemCount(); + boolean loading = isLoading(); + + if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + 5)) { + showAutoLoading(); + } + } + } + }); + } + + private void showAutoLoading() { + if (isAutoLoading) { + setLoading(true); + } + if (mOnLoadMoreListener != null) { + mOnLoadMoreListener.onNeedsToLoadMore(); + } + } + + // add loading view to adapter + public void setLoadingView(Context context, @LayoutRes int layoutRes) { + setLoadingView(LayoutInflater.from(context).inflate(layoutRes, null)); + } + + //remove header from adapter + public void removeHeader(View header) { + if (headers.contains(header)) { + //animate + notifyItemRemoved(headers.indexOf(header)); + headers.remove(header); + } + } + + //add a footer to the adapter + public void addFooter(View footer) { + if (!footers.contains(footer)) { + footers.add(footer); + //animate + notifyItemInserted(headers.size() + getItemCount() + footers.size() - 1); + } + } + public void addFooter(Context context, @LayoutRes int layoutRes) { + View footer = LayoutInflater.from(context).inflate(layoutRes, null, false); + addFooter(footer); + } + + //remove footer from adapter + public void removeFooter(View footer) { + if (footers.contains(footer)) { + //animate + notifyItemRemoved(headers.size() + getItemCount() + footers.indexOf(footer)); + footers.remove(footer); + } + } + + public int getHeadersCount() { + return headers.size(); + } + + private int getLoadingViewCount() { + return isLoading ? 1 : 0; + } + + public View getHeader(int location) { + return headers.get(location); + } + + public int getFootersCount() { + return footers.size(); + } + + public View getFooter(int location) { + return footers.get(location); + } + + protected int getItemType(int position) { + return 0; + } + + abstract protected void onBindItemViewHolder(VH viewHolder, int position, int type); + + protected abstract VH viewHolder(View view, int type); + + protected abstract + @LayoutRes + int layoutId(int type); + + public interface SpanItemInterface { + int getGridSpan(); + } + + class LoadingViewHolder extends RecyclerView.ViewHolder { + LoadingViewHolder(View view) { + super(view); + } + } + + //our header/footer RecyclerView.ViewHolder is just a FrameLayout + static class HeaderFooterViewHolder extends RecyclerView.ViewHolder { + HeaderFooterViewHolder(View itemView) { + super(itemView); + } + } + + class EmptyStateViewHolder extends RecyclerView.ViewHolder { + EmptyStateViewHolder(View view) { + super(view); + } + } + + public Parcelable onSaveInstanceState() { + Bundle bundle = new Bundle(); + if (items.size() > 0 && (items.get(0) instanceof Parcelable + || items.get(0) instanceof Serializable)) { + ArrayList arrItems = new ArrayList<>(items); + bundle.putSerializable(P_ITEMS, arrItems); + } + return bundle; + } + + public void onRestoreInstanceState(Parcelable state) { + if (state != null && state instanceof Bundle) { + Bundle bundle = (Bundle) state; + if (bundle.containsKey(P_ITEMS)) { + items = (ArrayList) bundle.getSerializable(P_ITEMS); + } + } + } + + public interface OnItemClickedListener { + void onItemClicked(View view, int position); + } + + public interface OnLoadMoreListener { + void onNeedsToLoadMore(); + } +} diff --git a/hfradapter/src/main/java/com/mbh/hfradapter/ParallaxHFRAdapter.java b/hfradapter/src/main/java/com/mbh/hfradapter/ParallaxHFRAdapter.java new file mode 100644 index 0000000..ad53beb --- /dev/null +++ b/hfradapter/src/main/java/com/mbh/hfradapter/ParallaxHFRAdapter.java @@ -0,0 +1,172 @@ +package com.mbh.hfradapter; + +import android.os.Build; +import android.support.v4.view.ViewCompat; +import android.support.v7.widget.RecyclerView; +import android.view.View; +import android.view.ViewGroup; +import android.view.animation.TranslateAnimation; +import android.widget.FrameLayout; +import android.widget.Toast; + +import java.util.List; + +/** + * Createdby MBH on 02/03/2017. + */ + +public abstract class ParallaxHFRAdapter + extends HFRAdapter { + private static final float SCROLL_MULTIPLIER = 0.5f; + + private ClipContainer header; + private ClipContainer footer; + private OnParallaxScroll parallaxScroll; + private boolean isParallaxHeader = true; + private boolean isParallaxFooter = true; + private boolean isScaleWithParallax = false; + private boolean isFadeWithParallax = false; + + public ParallaxHFRAdapter(List items) { + this.items = items; + } + + public ParallaxHFRAdapter() {} + + //parallax adapter may have only one header + @Override + public void addHeader(View header) { + if (getHeadersCount() == 0) { + super.addHeader(header); + } else { + removeHeader(getHeader(0)); + super.addHeader(header); + } + } + + //parallax adapter may have only one header + @Override + public void addFooter(View footer) { + if (getFootersCount() == 0) { + super.addFooter(footer); + } else { + removeFooter(getFooter(0)); + super.addFooter(footer); + } + } + + private void translateView(float of, ClipContainer view, boolean isFooter) { + float ofCalculated = of * SCROLL_MULTIPLIER; + ofCalculated = isFooter ? -ofCalculated : ofCalculated; + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { + // TODO: Fix this line here + view.setTranslationY(ofCalculated); +// ViewCompat.setTranslationY(view, ofCalculated); + } else { + TranslateAnimation anim = new TranslateAnimation(0, 0, ofCalculated, ofCalculated); + anim.setFillAfter(true); + anim.setDuration(0); + view.startAnimation(anim); + } + view.setOffset(Math.round(ofCalculated)); + + if (isScaleWithParallax) { + float scaleAmount = 1f - ofCalculated * 0.0001f; + ViewCompat.setScaleX(view, scaleAmount); + ViewCompat.setScaleY(view, scaleAmount); + } + + if (isFadeWithParallax) { + float fadeAmount = 1f - ofCalculated * 0.001f; + ViewCompat.setAlpha(view, fadeAmount); + } + + view.invalidate(); + + if (parallaxScroll != null && !isFooter) { + float left = Math.min(1, ((ofCalculated) / (view.getHeight() * SCROLL_MULTIPLIER))); + parallaxScroll.onParallaxScroll(left, of, view); + } + } + + @Override + public final VH onCreateViewHolder(ViewGroup viewGroup, int type) { + //if our position is one of our items (this comes from getItemViewType(int position) below) + if (type != TYPE_HEADER && type != TYPE_FOOTER && type != TYPE_LOADING) { + return (VH) onCreateItemViewHolder(viewGroup, type); + //else if we have a header + } else if (type == TYPE_LOADING && getLoadingView() != null) { + FrameLayout frameLayout = new FrameLayout(viewGroup.getContext()); + setHeaderFooterLayoutParams(frameLayout); + View lView = getLoadingView(); + if (lView.getParent() != null) { + Toast.makeText(lView.getContext(), "Has Parent", Toast.LENGTH_SHORT).show(); + ((ViewGroup) lView.getParent()).removeView(getLoadingView()); + } + frameLayout.addView(getLoadingView()); + return (VH) new LoadingViewHolder(frameLayout); + } else if (type == TYPE_HEADER) { + //create a new ParallaxContainer + header = new ClipContainer(viewGroup.getContext(), isParallaxHeader, false); + //make sure it fills the space + setHeaderFooterLayoutParams(header); + return (VH) new HeaderFooterViewHolder(header); + //else we have a footer + } else { + //create a new ParallaxContainer + footer = new ClipContainer(viewGroup.getContext(), isParallaxFooter, true); + //make sure it fills the space + setHeaderFooterLayoutParams(footer); + return (VH) new HeaderFooterViewHolder(footer); + } + } + + @Override + public void onAttachedToRecyclerView(RecyclerView recyclerView) { + super.onAttachedToRecyclerView(recyclerView); + recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { + @Override + public void onScrolled(RecyclerView recyclerView, int dx, int dy) { + super.onScrolled(recyclerView, dx, dy); + if (header != null && isParallaxHeader) { + translateView(recyclerView.computeVerticalScrollOffset(), header, false); + } + if (footer != null && isParallaxFooter) { + int range = recyclerView.computeVerticalScrollRange(); + int extend = recyclerView.computeVerticalScrollExtent(); + int offset = recyclerView.computeVerticalScrollOffset(); + translateView(range - (extend + offset), footer, true); + } + } + }); + } + + public void setParallaxHeader(boolean isParallaxHeader) { + this.isParallaxHeader = isParallaxHeader; + } + + public void setParallaxFooter(boolean isParallaxFooter) { + this.isParallaxFooter = isParallaxFooter; + } + + public void setParallaxHeaderFooter(boolean isParallaxHeader, boolean isParallaxFooter) { + this.isParallaxHeader = isParallaxHeader; + this.isParallaxFooter = isParallaxFooter; + } + + public void setOnParallaxScroll(OnParallaxScroll parallaxScroll) { + this.parallaxScroll = parallaxScroll; + this.parallaxScroll.onParallaxScroll(0, 0, header); + } + + public interface OnParallaxScroll { + /** + * Event triggered when the parallax is being scrolled. + * + * @param percentage + * @param offset + * @param parallax + */ + void onParallaxScroll(float percentage, float offset, View parallax); + } +} diff --git a/hfradapter/src/main/res/values/strings.xml b/hfradapter/src/main/res/values/strings.xml new file mode 100644 index 0000000..55344e5 --- /dev/null +++ b/hfradapter/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/hfradapter/src/main/res/values/styles.xml b/hfradapter/src/main/res/values/styles.xml new file mode 100644 index 0000000..8542005 --- /dev/null +++ b/hfradapter/src/main/res/values/styles.xml @@ -0,0 +1,2 @@ + + diff --git a/proguard-project.txt b/proguard-project.txt new file mode 100644 index 0000000..f2fe155 --- /dev/null +++ b/proguard-project.txt @@ -0,0 +1,20 @@ +# To enable ProGuard in your project, edit project.properties +# to define the proguard.config property as described in that file. +# +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in ${sdk.dir}/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the ProGuard +# include property in project.properties. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} diff --git a/sample/.gitignore b/sample/.gitignore new file mode 100644 index 0000000..34e5e5d --- /dev/null +++ b/sample/.gitignore @@ -0,0 +1,34 @@ +# built application files +*.apk +*.ap_ + +# files for the dex VM +*.dex + +# Java class files +*.class + +# generated files +bin/ +gen/ + +# Local configuration file (sdk path, etc) +local.properties +gradle.properties + +# Eclipse project files +.classpath +.project + +# Proguard folder generated by Eclipse +proguard/ + +# Intellij project files +*.iml +*.ipr +*.iws +.idea/ + +# OSX files +.DS_Store +.gradle \ No newline at end of file diff --git a/sample/build.gradle b/sample/build.gradle new file mode 100644 index 0000000..ca8393a --- /dev/null +++ b/sample/build.gradle @@ -0,0 +1,29 @@ +apply plugin: 'com.android.application' + +android { + compileSdkVersion 25 + buildToolsVersion "25.0.2" + + defaultConfig { + minSdkVersion 9 + targetSdkVersion 25 + versionCode 1 + versionName "1.0.0" + } + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + buildTypes { + release { + minifyEnabled false + } + } +} + +dependencies { + compile project(':hfradapter') + compile 'com.android.support:appcompat-v7:25.3.1' +} diff --git a/sample/src/main/AndroidManifest.xml b/sample/src/main/AndroidManifest.xml new file mode 100644 index 0000000..76ba59a --- /dev/null +++ b/sample/src/main/AndroidManifest.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/sample/src/main/java/com/mbh/hfadapter/sample/HFRAdapterActivity.java b/sample/src/main/java/com/mbh/hfadapter/sample/HFRAdapterActivity.java new file mode 100644 index 0000000..c64e3df --- /dev/null +++ b/sample/src/main/java/com/mbh/hfadapter/sample/HFRAdapterActivity.java @@ -0,0 +1,67 @@ +package com.mbh.hfadapter.sample; + +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import android.os.Handler; +import android.support.v7.app.AppCompatActivity; +import android.support.v7.widget.RecyclerView; + +import com.mbh.hfadapter.sample.adapters.HFRAdapterTest; +import com.mbh.hfradapter.ALinearLayoutManager; +import com.mbh.hfradapter.sample.R; + +import java.util.Arrays; +import java.util.List; + +public class HFRAdapterActivity extends AppCompatActivity { + + private HFRAdapterTest hfAdapter; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_hfradapter); + + RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView); + // I used ALinearLayoutManager to avoid and ignore bugs in recycler view + recyclerView.setLayoutManager(new ALinearLayoutManager(this)); + prepareAdapter(); + recyclerView.setAdapter(hfAdapter); + + hfAdapter.setLoading(true); + new Handler().postDelayed(new Runnable() { + @Override + public void run() { + hfAdapter.setLoading(false); + hfAdapter.setAll(getItems()); + } + }, 1000); + } + + private void prepareAdapter() { + hfAdapter = new HFRAdapterTest(); +// hfAdapter = new HFRAdapterTest(getItems()); + hfAdapter.addHeader(this, R.layout.v_header); + hfAdapter.addFooter(this, R.layout.v_footer); + hfAdapter.setLoadingView(this, R.layout.v_loading); + } + + + public List getItems() { + return Arrays.asList( + "This", "is", + "test", "for", + "header", "footer", + "only", "for", "testing", "1", + "2", "3", "4", "5", "6", "7", "8", "9", "once", + "more", "1", "2", "3", "4", "5", "6", "7", "8", "9" + ); + } + + + public static void start(Context context) { + Intent starter = new Intent(context, HFRAdapterActivity.class); + context.startActivity(starter); + } +} diff --git a/sample/src/main/java/com/mbh/hfadapter/sample/MainActivity.java b/sample/src/main/java/com/mbh/hfadapter/sample/MainActivity.java new file mode 100644 index 0000000..4e9fa63 --- /dev/null +++ b/sample/src/main/java/com/mbh/hfadapter/sample/MainActivity.java @@ -0,0 +1,32 @@ +package com.mbh.hfadapter.sample; + +import android.os.Bundle; +import android.support.v7.app.AppCompatActivity; +import android.view.Menu; +import android.view.View; + +import com.mbh.hfradapter.sample.R; + + +public class MainActivity extends AppCompatActivity { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_main); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.main, menu); + return true; + } + + public void btn_hfrAdapterClicked(View view) { + HFRAdapterActivity.start(MainActivity.this); + } + + public void btn_phfrAdapterClicked(View view) { + ParallaxHFRAdapterActivity.start(MainActivity.this); + } +} diff --git a/sample/src/main/java/com/mbh/hfadapter/sample/ParallaxHFRAdapterActivity.java b/sample/src/main/java/com/mbh/hfadapter/sample/ParallaxHFRAdapterActivity.java new file mode 100644 index 0000000..1a40a9c --- /dev/null +++ b/sample/src/main/java/com/mbh/hfadapter/sample/ParallaxHFRAdapterActivity.java @@ -0,0 +1,57 @@ +package com.mbh.hfadapter.sample; + +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import android.support.v7.app.AppCompatActivity; +import android.support.v7.widget.RecyclerView; + +import com.mbh.hfadapter.sample.adapters.ParallaxHFRAdapterTest; +import com.mbh.hfradapter.ALinearLayoutManager; +import com.mbh.hfradapter.sample.R; + +import java.util.Arrays; +import java.util.List; + +public class ParallaxHFRAdapterActivity extends AppCompatActivity { + + private ParallaxHFRAdapterTest parallaxHfAdapter; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_hfradapter); + + RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView); + // I used ALinearLayoutManager to avoid and ignore bugs in recycler view + recyclerView.setLayoutManager(new ALinearLayoutManager(this)); + prepareAdapter(); + recyclerView.setAdapter(parallaxHfAdapter); + } + + private void prepareAdapter() { + parallaxHfAdapter = new ParallaxHFRAdapterTest(getItems()); + parallaxHfAdapter.addHeader(this, R.layout.v_header); + parallaxHfAdapter.addFooter(this, R.layout.v_footer); + parallaxHfAdapter.setLoadingView(this, R.layout.v_loading); + parallaxHfAdapter.setParallaxHeader(true); + parallaxHfAdapter.setParallaxFooter(true); + } + + + public List getItems() { + return Arrays.asList( + "This", "is", + "test", "for", + "header", "footer", + "only", "for", "testing", "1", + "1", "2", "3", "4", "5", "6", "7", "8", "9" + ); + } + + + public static void start(Context context) { + Intent starter = new Intent(context, ParallaxHFRAdapterActivity.class); + context.startActivity(starter); + } +} diff --git a/sample/src/main/java/com/mbh/hfadapter/sample/adapters/HFRAdapterTest.java b/sample/src/main/java/com/mbh/hfadapter/sample/adapters/HFRAdapterTest.java new file mode 100644 index 0000000..7bb367b --- /dev/null +++ b/sample/src/main/java/com/mbh/hfadapter/sample/adapters/HFRAdapterTest.java @@ -0,0 +1,36 @@ +package com.mbh.hfadapter.sample.adapters; + +import android.view.View; + +import com.mbh.hfradapter.HFRAdapter; +import com.mbh.hfradapter.sample.R; + +import java.util.List; + +/** + * Createdby MBH on 30/04/2017. + */ + +public class HFRAdapterTest extends HFRAdapter { + + public HFRAdapterTest(List items) { + super(items); + } + + public HFRAdapterTest() {} + + @Override + protected void onBindItemViewHolder(MyViewHolder viewHolder, int position, int type) { + viewHolder.bind(getItem(position)); + } + + @Override + protected MyViewHolder viewHolder(View view, int type) { + return new MyViewHolder(view); + } + + @Override + protected int layoutId(int type) { + return R.layout.item_text; + } +} diff --git a/sample/src/main/java/com/mbh/hfadapter/sample/adapters/MyViewHolder.java b/sample/src/main/java/com/mbh/hfadapter/sample/adapters/MyViewHolder.java new file mode 100644 index 0000000..cdb5ebb --- /dev/null +++ b/sample/src/main/java/com/mbh/hfadapter/sample/adapters/MyViewHolder.java @@ -0,0 +1,25 @@ +package com.mbh.hfadapter.sample.adapters; + +import android.support.v7.widget.RecyclerView; +import android.view.View; +import android.widget.TextView; + +import com.mbh.hfradapter.sample.R; + + +/** + * Createdby MBH on 30/04/2017. + */ + +public class MyViewHolder extends RecyclerView.ViewHolder { + final TextView textView; + + public MyViewHolder(View itemView) { + super(itemView); + textView = (TextView) itemView.findViewById(R.id.tv); + } + + public void bind(String text) { + textView.setText(text); + } +} diff --git a/sample/src/main/java/com/mbh/hfadapter/sample/adapters/ParallaxHFRAdapterTest.java b/sample/src/main/java/com/mbh/hfadapter/sample/adapters/ParallaxHFRAdapterTest.java new file mode 100644 index 0000000..1677b27 --- /dev/null +++ b/sample/src/main/java/com/mbh/hfadapter/sample/adapters/ParallaxHFRAdapterTest.java @@ -0,0 +1,36 @@ +package com.mbh.hfadapter.sample.adapters; + +import android.view.View; + +import com.mbh.hfradapter.ParallaxHFRAdapter; +import com.mbh.hfradapter.sample.R; + +import java.util.List; + +/** + * Createdby MBH on 30/04/2017. + */ + +public class ParallaxHFRAdapterTest extends ParallaxHFRAdapter { + + public ParallaxHFRAdapterTest(List items) { + super(items); + } + + public ParallaxHFRAdapterTest() {} + + @Override + protected void onBindItemViewHolder(MyViewHolder viewHolder, int position, int type) { + viewHolder.bind(getItem(position)); + } + + @Override + protected MyViewHolder viewHolder(View view, int type) { + return new MyViewHolder(view); + } + + @Override + protected int layoutId(int type) { + return R.layout.item_text; + } +} diff --git a/sample/src/main/res/drawable-hdpi/alhamdulillah.jpg b/sample/src/main/res/drawable-hdpi/alhamdulillah.jpg new file mode 100644 index 0000000..3b25184 Binary files /dev/null and b/sample/src/main/res/drawable-hdpi/alhamdulillah.jpg differ diff --git a/sample/src/main/res/drawable-hdpi/ic_launcher.png b/sample/src/main/res/drawable-hdpi/ic_launcher.png new file mode 100644 index 0000000..96a442e Binary files /dev/null and b/sample/src/main/res/drawable-hdpi/ic_launcher.png differ diff --git a/sample/src/main/res/drawable-hdpi/red.jpg b/sample/src/main/res/drawable-hdpi/red.jpg new file mode 100644 index 0000000..5fdad0e Binary files /dev/null and b/sample/src/main/res/drawable-hdpi/red.jpg differ diff --git a/sample/src/main/res/drawable-mdpi/ic_launcher.png b/sample/src/main/res/drawable-mdpi/ic_launcher.png new file mode 100644 index 0000000..359047d Binary files /dev/null and b/sample/src/main/res/drawable-mdpi/ic_launcher.png differ diff --git a/sample/src/main/res/drawable-xhdpi/ic_launcher.png b/sample/src/main/res/drawable-xhdpi/ic_launcher.png new file mode 100644 index 0000000..71c6d76 Binary files /dev/null and b/sample/src/main/res/drawable-xhdpi/ic_launcher.png differ diff --git a/sample/src/main/res/layout/activity_hfradapter.xml b/sample/src/main/res/layout/activity_hfradapter.xml new file mode 100644 index 0000000..8816b02 --- /dev/null +++ b/sample/src/main/res/layout/activity_hfradapter.xml @@ -0,0 +1,15 @@ + + + + + + diff --git a/sample/src/main/res/layout/activity_main.xml b/sample/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..b404785 --- /dev/null +++ b/sample/src/main/res/layout/activity_main.xml @@ -0,0 +1,31 @@ + + + + +