├── .gitignore
├── LICENSE
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── dant
│ │ └── centeringrecyclerview
│ │ └── ExampleInstrumentedTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── assets
│ │ └── demo.gif
│ ├── java
│ │ └── com
│ │ │ └── dant
│ │ │ └── centeringrecyclerview
│ │ │ ├── ExampleDateAdapter.java
│ │ │ ├── ExampleDateEndPaddingItemDecoration.java
│ │ │ ├── ExampleDateReyclerViewHolder.java
│ │ │ └── MainActivity.java
│ └── res
│ │ ├── layout
│ │ ├── activity_main.xml
│ │ └── example_date_viewholder.xml
│ │ ├── mipmap-hdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-mdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxxhdpi
│ │ └── ic_launcher.png
│ │ ├── values-w820dp
│ │ └── dimens.xml
│ │ └── values
│ │ ├── colors.xml
│ │ ├── dimens.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── com
│ └── dant
│ └── centeringrecyclerview
│ └── ExampleUnitTest.java
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── snappy-recyclerview
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
├── androidTest
└── java
│ └── com
│ └── dant
│ └── centersnapreyclerview
│ └── ExampleInstrumentedTest.java
├── main
├── AndroidManifest.xml
├── java
│ └── com
│ │ └── dant
│ │ └── centersnapreyclerview
│ │ ├── CenterLayoutManager.java
│ │ └── SnappingRecyclerView.java
└── res
│ └── values
│ ├── snapping_recyclerview.xml
│ └── strings.xml
└── test
└── java
└── com
└── dant
└── centersnapreyclerview
└── ExampleUnitTest.java
/.gitignore:
--------------------------------------------------------------------------------
1 | # Built application files
2 | *.apk
3 | *.ap_
4 |
5 | # Files for the ART/Dalvik VM
6 | *.dex
7 |
8 | # Java class files
9 | *.class
10 |
11 | # Generated files
12 | bin/
13 | gen/
14 | out/
15 |
16 | # Gradle files
17 | .gradle/
18 | build/
19 |
20 | # Local configuration file (sdk path, etc)
21 | local.properties
22 |
23 | # Proguard folder generated by Eclipse
24 | proguard/
25 |
26 | # Log Files
27 | *.log
28 |
29 | # Android Studio Navigation editor temp files
30 | .navigation/
31 |
32 | # Android Studio captures folder
33 | captures/
34 |
35 | # Intellij
36 | *.iml
37 | .idea/workspace.xml
38 | CenteringRecyclerView/.idea/workspace.xml
39 |
40 | # Keystore files
41 | *.jks
42 |
43 | .idea/*
44 |
45 | # Bintray files
46 | snappy-recyclerview/bintray.gradle
47 | snappy-recyclerview/install.gradle
48 |
49 |
50 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2017 Dan-TD
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://www.bitrise.io/app/5148ffd6da031702)
2 | [](https://android-arsenal.com/details/1/5473)
3 | [](https://opensource.org/licenses/MIT)
4 |
5 | # SnappyRecyclerView
6 |
7 | An extension to RecyclerView which will snap to child Views to the specified anchor, START, CENTER or END.
8 |
9 |
10 |
11 |
12 | ## Setup
13 |
14 | #### Gradle
15 |
16 | `compile 'com.github.dan-td:snappy-recyclerview:1.0.2'`
17 |
18 | #### Maven
19 | ```
20 |
21 | com.github.dan-td
22 | snappy-recyclerview
23 | 1.0.2
24 |
25 | ```
26 |
27 | ## Sample Usage
28 |
29 | ```xml
30 |
35 | ```
36 |
37 | ### XML Attributes
38 |
39 | * **orientation** - the orientation of the recyclerview, VERTICAL or HORIZONTAL
40 | * **anchor** - the snap anchor of the recyclerview, START, CENTER or END
41 | * **scrollSpeed** - the smooth scroll speed
42 | * **flingThreshold** - the threshold above which a fling is will occur
43 |
44 | ## License
45 |
46 | ```
47 | Copyright 2017 Daniel Tanner-Davies
48 |
49 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
50 |
51 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
52 |
53 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
54 | ```
55 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 25
5 | buildToolsVersion "25.0.0"
6 | defaultConfig {
7 | applicationId "com.dant.centeringrecyclerview"
8 | minSdkVersion 19
9 | targetSdkVersion 25
10 | versionCode 1
11 | versionName "1.0"
12 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | compile fileTree(dir: 'libs', include: ['*.jar'])
24 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
25 | exclude group: 'com.android.support', module: 'support-annotations'
26 | })
27 | compile 'com.android.support:appcompat-v7:25.0.1'
28 | compile 'com.android.support:recyclerview-v7:25.0.1'
29 | compile 'com.android.support:cardview-v7:25.0.1'
30 | compile project(':snappy-recyclerview')
31 | testCompile 'junit:junit:4.12'
32 | }
33 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/dant/Library/android-sdk-macosx/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/dant/centeringrecyclerview/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.dant.centeringrecyclerview;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumentation test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() throws Exception {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("com.dant.centeringrecyclerview", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/app/src/main/assets/demo.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Dan-TD/SnappyRecyclerView/3d2f35ea66d48de59027b529153e931aa57683ae/app/src/main/assets/demo.gif
--------------------------------------------------------------------------------
/app/src/main/java/com/dant/centeringrecyclerview/ExampleDateAdapter.java:
--------------------------------------------------------------------------------
1 | package com.dant.centeringrecyclerview;
2 |
3 | import android.support.v7.widget.RecyclerView;
4 | import android.view.ViewGroup;
5 |
6 | import java.text.ParseException;
7 | import java.text.SimpleDateFormat;
8 | import java.util.ArrayList;
9 | import java.util.Calendar;
10 | import java.util.Date;
11 | import java.util.List;
12 |
13 | public class ExampleDateAdapter extends RecyclerView.Adapter {
14 |
15 | private Date startDate;
16 | private Date endDate;
17 |
18 | private List dates;
19 |
20 | public ExampleDateAdapter() {
21 | SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
22 |
23 | try {
24 | startDate = formatter.parse("2017-01-01");
25 | } catch (ParseException ex) {}
26 |
27 | try {
28 | endDate = formatter.parse("2018-12-31");
29 | } catch (ParseException ex) {}
30 |
31 | Calendar start = Calendar.getInstance();
32 | start.setTime(startDate);
33 |
34 | Calendar end = Calendar.getInstance();
35 | end.setTime(endDate);
36 |
37 | dates = new ArrayList<>();
38 | for(Date date = start.getTime(); start.before(end); start.add(Calendar.DATE, 1), date = start.getTime()) {
39 | dates.add(date);
40 | }
41 | }
42 |
43 | @Override
44 | public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
45 | return new ExampleDateReyclerViewHolder(parent);
46 | }
47 |
48 | @Override
49 | public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
50 | ((ExampleDateReyclerViewHolder)holder).setDate(dates.get(position));
51 | }
52 |
53 | @Override
54 | public int getItemCount() {
55 | return dates.size();
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/app/src/main/java/com/dant/centeringrecyclerview/ExampleDateEndPaddingItemDecoration.java:
--------------------------------------------------------------------------------
1 | package com.dant.centeringrecyclerview;
2 |
3 | import android.graphics.Rect;
4 | import android.support.v7.widget.RecyclerView;
5 | import android.view.View;
6 |
7 | import com.dant.centersnapreyclerview.SnappingRecyclerView;
8 |
9 | public class ExampleDateEndPaddingItemDecoration extends RecyclerView.ItemDecoration {
10 |
11 | private @SnappingRecyclerView.OrientationMode int orientation;
12 |
13 | public ExampleDateEndPaddingItemDecoration(@SnappingRecyclerView.OrientationMode int orientation) {
14 | this.orientation = orientation;
15 | }
16 |
17 | @Override
18 | public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
19 | if(parent.getChildAdapterPosition(view) == 0) {
20 | if(orientation == SnappingRecyclerView.VERTICAL) {
21 | outRect.top = (parent.getHeight() / 2) - (view.getHeight() / 2);
22 | } else {
23 | outRect.left = (parent.getWidth() / 2) - (view.getWidth() / 2);
24 | }
25 | } else if (parent.getChildAdapterPosition(view) == parent.getAdapter().getItemCount() - 1) {
26 | if(orientation == SnappingRecyclerView.VERTICAL) {
27 | outRect.bottom = (parent.getHeight() / 2) - (view.getHeight() / 2);
28 | } else {
29 | outRect.right = (parent.getWidth() / 2) - (view.getWidth() / 2);
30 | }
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/app/src/main/java/com/dant/centeringrecyclerview/ExampleDateReyclerViewHolder.java:
--------------------------------------------------------------------------------
1 | package com.dant.centeringrecyclerview;
2 |
3 | import android.support.v7.widget.RecyclerView;
4 | import android.view.LayoutInflater;
5 | import android.view.ViewGroup;
6 | import android.widget.TextView;
7 |
8 | import java.text.SimpleDateFormat;
9 | import java.util.Calendar;
10 | import java.util.Date;
11 |
12 | public class ExampleDateReyclerViewHolder extends RecyclerView.ViewHolder {
13 |
14 | public ExampleDateReyclerViewHolder(ViewGroup parent) {
15 | super(LayoutInflater.from(parent.getContext()).inflate(R.layout.example_date_viewholder, parent, false));
16 | }
17 |
18 | public void setDate(Date date) {
19 | ((TextView)(itemView.findViewById(R.id.date_text))).setText(new SimpleDateFormat("EEE d").format(date));
20 | ((TextView)(itemView.findViewById(R.id.month_text))).setText(new SimpleDateFormat("MMM").format(date));
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/app/src/main/java/com/dant/centeringrecyclerview/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.dant.centeringrecyclerview;
2 |
3 | import android.support.v7.app.AppCompatActivity;
4 | import android.os.Bundle;
5 |
6 | import com.dant.centersnapreyclerview.SnappingRecyclerView;
7 |
8 | public class MainActivity extends AppCompatActivity {
9 |
10 | @Override
11 | protected void onCreate(Bundle savedInstanceState) {
12 | super.onCreate(savedInstanceState);
13 |
14 | setContentView(R.layout.activity_main);
15 |
16 | SnappingRecyclerView recyclerView = (SnappingRecyclerView) findViewById(R.id.recyclerview);
17 | recyclerView.addItemDecoration(new ExampleDateEndPaddingItemDecoration(recyclerView.getOrientation()));
18 | recyclerView.setAdapter(new ExampleDateAdapter());
19 | }
20 | }
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/example_date_viewholder.xml:
--------------------------------------------------------------------------------
1 |
2 |
11 |
12 |
16 |
17 |
22 |
23 |
31 |
32 |
40 |
41 |
42 |
43 |
44 |
45 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Dan-TD/SnappyRecyclerView/3d2f35ea66d48de59027b529153e931aa57683ae/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Dan-TD/SnappyRecyclerView/3d2f35ea66d48de59027b529153e931aa57683ae/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Dan-TD/SnappyRecyclerView/3d2f35ea66d48de59027b529153e931aa57683ae/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Dan-TD/SnappyRecyclerView/3d2f35ea66d48de59027b529153e931aa57683ae/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Dan-TD/SnappyRecyclerView/3d2f35ea66d48de59027b529153e931aa57683ae/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Centering RecyclerView
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/test/java/com/dant/centeringrecyclerview/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.dant.centeringrecyclerview;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() throws Exception {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | jcenter()
6 | }
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:2.2.2'
9 |
10 | // NOTE: Do not place your application dependencies here; they belong
11 | // in the individual module build.gradle files
12 | classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.2'
13 | classpath 'com.github.dcendents:android-maven-gradle-plugin:1.4.1'
14 | }
15 | }
16 |
17 | allprojects {
18 | repositories {
19 | jcenter()
20 | }
21 | }
22 |
23 | task clean(type: Delete) {
24 | delete rootProject.buildDir
25 | }
26 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Dan-TD/SnappyRecyclerView/3d2f35ea66d48de59027b529153e931aa57683ae/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Dec 28 10:00:20 PST 2015
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':snappy-recyclerview'
2 |
--------------------------------------------------------------------------------
/snappy-recyclerview/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/snappy-recyclerview/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | android {
4 | compileSdkVersion 25
5 | buildToolsVersion "25.0.0"
6 |
7 | defaultConfig {
8 | minSdkVersion 16
9 | targetSdkVersion 25
10 | versionCode 1
11 | versionName "1.0.2"
12 |
13 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
14 |
15 | }
16 | buildTypes {
17 | release {
18 | minifyEnabled false
19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
20 | }
21 | }
22 | }
23 |
24 | dependencies {
25 | compile fileTree(dir: 'libs', include: ['*.jar'])
26 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
27 | exclude group: 'com.android.support', module: 'support-annotations'
28 | })
29 | compile 'com.android.support:appcompat-v7:25.0.1'
30 | compile 'com.android.support:recyclerview-v7:25.0.1'
31 | testCompile 'junit:junit:4.12'
32 | }
33 |
34 | // apply from: 'install.gradle'
35 | // apply from: 'bintray.gradle'
36 |
--------------------------------------------------------------------------------
/snappy-recyclerview/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/dant/Library/android-sdk-macosx/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/snappy-recyclerview/src/androidTest/java/com/dant/centersnapreyclerview/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.dant.centersnapreyclerview;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumentation test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() throws Exception {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("com.dant.centersnapreyclerview.test", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/snappy-recyclerview/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/snappy-recyclerview/src/main/java/com/dant/centersnapreyclerview/CenterLayoutManager.java:
--------------------------------------------------------------------------------
1 | package com.dant.centersnapreyclerview;
2 |
3 | import android.content.Context;
4 | import android.graphics.PointF;
5 | import android.support.v7.widget.LinearLayoutManager;
6 | import android.support.v7.widget.LinearSmoothScroller;
7 | import android.support.v7.widget.RecyclerView;
8 | import android.util.DisplayMetrics;
9 |
10 | /**
11 | * This extension to LinearLayoutManager allows the smoothScroll speed to be adjusted, additionally
12 | * it provides a custom implementation of the LinearSmoothScroller. The extension of
13 | * LinearSmoothScroller provides an additional snap preference, CENTER, this aligns the center of
14 | * the child's View with the center of the parent's View.
15 | */
16 | public class CenterLayoutManager extends LinearLayoutManager {
17 |
18 | private SmoothScroller smoothScroller;
19 |
20 | private int anchor;
21 |
22 | public CenterLayoutManager(Context context) {
23 | super(context);
24 |
25 | smoothScroller = new SmoothScroller(context);
26 | }
27 |
28 | public void setAnchor(int anchor) {
29 | this.anchor = anchor;
30 | }
31 |
32 | public void setScrollSpeed(float scrollSpeed) {
33 | smoothScroller.setScrollSpeed(scrollSpeed);
34 | }
35 |
36 | @Override
37 | public void smoothScrollToPosition(RecyclerView recyclerView,
38 | RecyclerView.State state, final int position) {
39 | smoothScroller.setTargetPosition(position);
40 | startSmoothScroll(smoothScroller);
41 | }
42 |
43 | private class SmoothScroller extends LinearSmoothScroller {
44 |
45 | private static final float MILLISECONDS_PER_INCH = 100f;
46 |
47 | /**
48 | * Use in calculating the scroll speed.
49 | * The time (in ms) it takes to scroll an inch.
50 | */
51 | private float milliSecondsPerInch = -1;
52 |
53 | public SmoothScroller(Context context) {
54 | super(context);
55 | }
56 |
57 | public void setScrollSpeed(float scrollSpeed) {
58 | this.milliSecondsPerInch = scrollSpeed;
59 | }
60 |
61 | /**
62 | * Controls the direction in which smoothScroll looks for a list item.
63 | * Use our custom LinearLayoutManager to calculate PointF.
64 | *
65 | * @param targetPosition
66 | *
67 | * @return PointF, a class holding two float coordinates
68 | */
69 | @Override
70 | public PointF computeScrollVectorForPosition(int targetPosition) {
71 | return CenterLayoutManager.this.computeScrollVectorForPosition(targetPosition);
72 | }
73 |
74 | @Override
75 | public int calculateDtToFit(int viewStart, int viewEnd, int boxStart, int boxEnd, int snapPreference) {
76 | switch (anchor) {
77 | case SnappingRecyclerView.START:
78 | return super.calculateDtToFit(viewStart, viewEnd, boxStart, boxEnd, SNAP_TO_START);
79 | case SnappingRecyclerView.END:
80 | return super.calculateDtToFit(viewStart, viewEnd, boxStart, boxEnd, SNAP_TO_END);
81 | case SnappingRecyclerView.CENTER:
82 | default:
83 | return ((boxStart + boxEnd) / 2) - ((viewStart + viewEnd) / 2);
84 | }
85 | }
86 |
87 | protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
88 | return (milliSecondsPerInch > 0 ? milliSecondsPerInch : MILLISECONDS_PER_INCH) / displayMetrics.densityDpi;
89 | }
90 | }
91 |
92 | }
93 |
--------------------------------------------------------------------------------
/snappy-recyclerview/src/main/java/com/dant/centersnapreyclerview/SnappingRecyclerView.java:
--------------------------------------------------------------------------------
1 | package com.dant.centersnapreyclerview;
2 |
3 | import android.content.Context;
4 | import android.content.res.TypedArray;
5 | import android.support.annotation.IntDef;
6 | import android.support.annotation.Nullable;
7 | import android.support.v7.widget.LinearLayoutManager;
8 | import android.support.v7.widget.RecyclerView;
9 | import android.util.AttributeSet;
10 | import android.view.View;
11 |
12 | import java.lang.annotation.Retention;
13 | import java.lang.annotation.RetentionPolicy;
14 | import java.lang.ref.WeakReference;
15 |
16 | /**
17 | * An extension of RecyclerView which provides the ability for an anchor to which views will snap
18 | * too. Once a scroll has been completed the RecyclerView will calculate which of it's Views
19 | * (ViewHolders) is closest to it's anchor and, using the smoothScroll method provided by
20 | * CenterLayoutManager, scroll said View to the correct position on screen.
21 | */
22 | public class SnappingRecyclerView extends RecyclerView {
23 |
24 | @IntDef({HORIZONTAL, VERTICAL})
25 | @Retention(RetentionPolicy.SOURCE)
26 | public @interface OrientationMode {}
27 |
28 | public static final int VERTICAL = 0;
29 | public static final int HORIZONTAL = 1;
30 |
31 | @IntDef({CENTER, START, END})
32 | @Retention(RetentionPolicy.SOURCE)
33 | public @interface AnchorMode {}
34 |
35 | public static final int CENTER = 0;
36 | public static final int START = 1;
37 | public static final int END = 2;
38 |
39 | private static final int DEFAULT_FLING_THRESHOLD = 1000;
40 |
41 | public interface SnappingRecyclerViewListener {
42 | void onPositionChange(int position);
43 | void onScroll(int dx, int dy);
44 | }
45 |
46 | private WeakReference listener;
47 |
48 | private int orientation;
49 |
50 | /**
51 | * The anchor to which a View (ViewHolder) should snap too, the START, CENTER or END
52 | */
53 | private int anchor;
54 |
55 | /**
56 | * The smooth scroll speed, in ms per inch, this is 100 by default in our custom smooth
57 | * scroller
58 | */
59 | private float scrollSpeed;
60 |
61 | /**
62 | * If the velocity of the user's fling is below a set threshold, finish fling and scroll to the
63 | * appropriate View
64 | */
65 | private int flingThreshold;
66 |
67 | private CenterLayoutManager layoutManager;
68 |
69 | public SnappingRecyclerView(Context context) {
70 | super(context);
71 | initialise(context, null);
72 | }
73 |
74 | public SnappingRecyclerView(Context context, @Nullable AttributeSet attrs) {
75 | super(context, attrs);
76 | initialise(context, attrs);
77 | }
78 |
79 | public SnappingRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
80 | super(context, attrs, defStyle);
81 | initialise(context, attrs);
82 | }
83 |
84 | private void initialise(Context context, @Nullable AttributeSet attrs) {
85 | TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.SnappingRecyclerView, 0, 0);
86 | try {
87 | orientation = a.getInt(R.styleable.SnappingRecyclerView_orientation, VERTICAL);
88 | anchor = a.getInt(R.styleable.SnappingRecyclerView_anchor, CENTER);
89 | scrollSpeed = a.getFloat(R.styleable.SnappingRecyclerView_scrollSpeed, -1);
90 | flingThreshold = a.getInt(R.styleable.SnappingRecyclerView_flingThreshold, DEFAULT_FLING_THRESHOLD);
91 | } finally {
92 | a.recycle();
93 | }
94 |
95 | layoutManager = new CenterLayoutManager(getContext());
96 | layoutManager.setOrientation(orientation == VERTICAL ? LinearLayoutManager.VERTICAL : LinearLayoutManager.HORIZONTAL);
97 | layoutManager.setAnchor(anchor);
98 | layoutManager.setScrollSpeed(scrollSpeed);
99 | setLayoutManager(layoutManager);
100 | }
101 |
102 | public SnappingRecyclerViewListener getListener() {
103 | return listener != null ? listener.get() : null;
104 | }
105 |
106 | public void setListener(SnappingRecyclerViewListener listener) {
107 | this.listener = new WeakReference<>(listener);
108 | }
109 |
110 | public void setOrientation(@OrientationMode int orientation) {
111 | if (this.orientation != orientation) {
112 | this.orientation = orientation;
113 |
114 | layoutManager.setOrientation(orientation == VERTICAL ? LinearLayoutManager.VERTICAL : LinearLayoutManager.HORIZONTAL);
115 | requestLayout();
116 | }
117 | }
118 |
119 | @OrientationMode
120 | public int getOrientation() {
121 | return orientation;
122 | }
123 |
124 | public void setAnchor(@AnchorMode int anchor) {
125 | if (this.anchor != anchor) {
126 | this.anchor = anchor;
127 |
128 | layoutManager.setAnchor(anchor);
129 | requestLayout();
130 | }
131 | }
132 |
133 | @AnchorMode
134 | public int getAnchor() {
135 | return anchor;
136 | }
137 |
138 | @Override
139 | public void onScrolled(int dx, int dy) {
140 | super.onScrolled(dx, dy);
141 |
142 | if(getListener() != null) {
143 | getListener().onScroll(dx, dy);
144 | }
145 | }
146 |
147 | @Override
148 | public void scrollToPosition(final int position) {
149 | super.scrollToPosition(position);
150 |
151 | // Use the smoothScroll provided by the CenterLayoutManager
152 | post(new Runnable() {
153 | @Override
154 | public void run() {
155 | smoothScrollToPosition(position);
156 | }
157 | });
158 | }
159 |
160 | @Override
161 | public boolean fling(int velocityX, int velocityY) {
162 | if(Math.abs(orientation == VERTICAL ? velocityY : velocityX) < flingThreshold) {
163 | int centerViewPosition = calculateSnapViewPosition();
164 | smoothScrollToPosition(centerViewPosition);
165 |
166 | if(getListener() != null) {
167 | getListener().onPositionChange(centerViewPosition);
168 | }
169 |
170 | return true;
171 | } else {
172 | return super.fling(velocityX, velocityY);
173 | }
174 | }
175 |
176 | @Override
177 | public void onScrollStateChanged(int state) {
178 | super.onScrollStateChanged(state);
179 |
180 | /* Once a scroll has been completed smooth scroll to the nearest View based on the anchor */
181 | if (state == SCROLL_STATE_IDLE) {
182 | int centerViewPosition = calculateSnapViewPosition();
183 | smoothScrollToPosition(centerViewPosition);
184 |
185 | if(getListener() != null) {
186 | getListener().onPositionChange(centerViewPosition);
187 | }
188 | }
189 | }
190 |
191 | /**
192 | * Provides the anchor of the parent, the RecyclerView, based on the provided orientation and
193 | * anchor mode
194 | *
195 | * @param orientation The orientation of the RecyclerView, VERTICAL or HORIZONTAL
196 | * @param anchor The RecyclerView's anchor mode, START, CENTER or END
197 | *
198 | * @return The anchor of the parent, the RecyclerView
199 | */
200 | private int getParentAnchor(@OrientationMode int orientation, @AnchorMode int anchor) {
201 | switch (anchor) {
202 | case START:
203 | return 0;
204 | case END:
205 | return orientation == VERTICAL ? getHeight() : getWidth();
206 | case CENTER:
207 | default:
208 | return (orientation == VERTICAL ? getHeight() : getWidth()) / 2;
209 | }
210 | }
211 |
212 | /**
213 | * Provides the anchor or the given view relative to the provided orientation and anchor.
214 | * This will be the View's start (top or left), center, or end (bottom or right).
215 | *
216 | * @param view
217 | * @param orientation The orientation of the RecyclerView, VERTICAL or HORIZONTAL
218 | * @param anchor The RecyclerView's anchor mode, START, CENTER or END
219 | *
220 | * @return The anchor of the given View relative to the provided orientation and anchor
221 | */
222 | private int getViewAnchor(View view, @OrientationMode int orientation, @AnchorMode int anchor) {
223 | switch (anchor) {
224 | case START:
225 | return orientation == VERTICAL ? view.getTop() : view.getLeft();
226 | case END:
227 | return orientation == VERTICAL ? view.getBottom() : view.getRight();
228 | case CENTER:
229 | default:
230 | return (orientation == VERTICAL ? view.getTop() + (view.getHeight() / 2) : view.getLeft() + (view.getWidth() / 2));
231 | }
232 | }
233 |
234 | /**
235 | * Calculates the distance between the RecyclerView's anchor, either the start, center or end,
236 | * and the View which is closest to the anchor.
237 | *
238 | * @return The distance between RecyclerView anchor and View closest to anchor
239 | */
240 | private int calculateSnapDistance() {
241 | LinearLayoutManager linearLayoutManager = (LinearLayoutManager) getLayoutManager();
242 |
243 | int parentAnchor = getParentAnchor(orientation, anchor);
244 |
245 | int lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition();
246 | int firstVisibleItemPosition = linearLayoutManager.findFirstVisibleItemPosition();
247 |
248 | View currentViewClosestToAnchor = linearLayoutManager.findViewByPosition(firstVisibleItemPosition);
249 |
250 | int currentViewClosestToAnchorDistance = parentAnchor - getViewAnchor(currentViewClosestToAnchor, orientation, anchor);
251 |
252 | for(int i = firstVisibleItemPosition + 1; i <= lastVisibleItemPosition; i++) {
253 | View view = linearLayoutManager.findViewByPosition(i);
254 | int distanceToAnchor = parentAnchor - getViewAnchor(view, orientation, anchor);
255 |
256 | if (Math.abs(distanceToAnchor) < Math.abs(currentViewClosestToAnchorDistance)) {
257 | currentViewClosestToAnchorDistance = distanceToAnchor;
258 | }
259 | }
260 |
261 | return currentViewClosestToAnchorDistance;
262 | }
263 |
264 | /**
265 | * Finds the position of the View which is closest to the RecyclerView's anchor, either the
266 | * RecyclerView's start, center or end
267 | *
268 | * @return The position of the View closest the to RecyclerView's anchor
269 | */
270 | private int calculateSnapViewPosition() {
271 | LinearLayoutManager linearLayoutManager = (LinearLayoutManager) getLayoutManager();
272 |
273 | int parentAnchor = getParentAnchor(orientation, anchor);
274 |
275 | int lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition();
276 | int firstVisibleItemPosition = linearLayoutManager.findFirstVisibleItemPosition();
277 |
278 | View currentViewClosestToAnchor = linearLayoutManager.findViewByPosition(firstVisibleItemPosition);
279 |
280 | int currentViewClosestToAnchorDistance = parentAnchor - getViewAnchor(currentViewClosestToAnchor, orientation, anchor);
281 |
282 | int currentViewClosestToAnchorPosition = firstVisibleItemPosition;
283 |
284 | for(int i = firstVisibleItemPosition + 1; i <= lastVisibleItemPosition; i++) {
285 | View view = linearLayoutManager.findViewByPosition(i);
286 |
287 | int distanceToCenter = parentAnchor - getViewAnchor(view, orientation, anchor);
288 |
289 | if (Math.abs(distanceToCenter) < Math.abs(currentViewClosestToAnchorDistance)) {
290 | currentViewClosestToAnchorPosition = i;
291 | currentViewClosestToAnchorDistance = distanceToCenter;
292 | }
293 | }
294 |
295 | return currentViewClosestToAnchorPosition;
296 | }
297 | }
298 |
--------------------------------------------------------------------------------
/snappy-recyclerview/src/main/res/values/snapping_recyclerview.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/snappy-recyclerview/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Snappy ReyclerView
3 |
4 |
--------------------------------------------------------------------------------
/snappy-recyclerview/src/test/java/com/dant/centersnapreyclerview/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.dant.centersnapreyclerview;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() throws Exception {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------