Repository: RobertApikyan/SegmentedControl Branch: master Commit: 574281e85338 Files: 48 Total size: 125.7 KB Directory structure: gitextract_p17z464c/ ├── .gitignore ├── .idea/ │ ├── caches/ │ │ ├── build_file_checksums.ser │ │ └── gradle_models.ser │ ├── encodings.xml │ ├── gradle.xml │ ├── misc.xml │ ├── modules.xml │ ├── runConfigurations.xml │ └── vcs.xml ├── LICENSE ├── README.md ├── build.gradle ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat ├── segmentedcontrolmodule/ │ ├── .gitignore │ ├── build.gradle │ ├── proguard-rules.pro │ └── src/ │ └── main/ │ ├── AndroidManifest.xml │ ├── java/ │ │ └── segmented_control/ │ │ └── widget/ │ │ └── custom/ │ │ └── android/ │ │ └── com/ │ │ └── segmentedcontrol/ │ │ ├── Assert.java │ │ ├── Configs.java │ │ ├── Consumer.java │ │ ├── Notifier.java │ │ ├── SegmentConsumer.java │ │ ├── SegmentedControl.java │ │ ├── SegmentedControlControllerComponent.java │ │ ├── SegmentedControlViewComponent.java │ │ ├── custom_segment/ │ │ │ ├── SegmentAdapterImpl.java │ │ │ └── SegmentViewHolderImpl.java │ │ ├── item_row/ │ │ │ ├── SegmentRowAdapter.java │ │ │ └── SegmentRowViewHolder.java │ │ ├── item_row_column/ │ │ │ ├── SegmentAdapter.java │ │ │ ├── SegmentBackgroundType.java │ │ │ ├── SegmentData.java │ │ │ ├── SegmentDecoration.java │ │ │ └── SegmentViewHolder.java │ │ ├── listeners/ │ │ │ ├── OnSegmentClickListener.java │ │ │ ├── OnSegmentSelectRequestListener.java │ │ │ └── OnSegmentSelectedListener.java │ │ └── utils/ │ │ ├── ArgbEvaluator.java │ │ └── Utils.java │ └── res/ │ ├── layout/ │ │ └── item_segment_impl.xml │ └── values/ │ ├── attr.xml │ ├── colors.xml │ └── strings.xml └── settings.gradle ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ *.iml .gradle /local.properties /.idea/workspace.xml /.idea/libraries .DS_Store /build /captures .externalNativeBuild /app ================================================ FILE: .idea/encodings.xml ================================================ ================================================ FILE: .idea/gradle.xml ================================================ ================================================ FILE: .idea/misc.xml ================================================ ================================================ FILE: .idea/modules.xml ================================================ ================================================ FILE: .idea/runConfigurations.xml ================================================ ================================================ FILE: .idea/vcs.xml ================================================ ================================================ FILE: LICENSE ================================================ 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. ================================================ FILE: README.md ================================================ # Android SegmentedControl + multi row support + multi selection ### minSdk API 14+ ![N|Solid](https://raw.githubusercontent.com/RobertApikyan/SegmentedControl/release_v0.1/app/src/main/res/mipmap-hdpi/ic_launcher.png) [Demo App, Play store link](https://play.google.com/store/apps/details?id=segmented_control.widget.custom.android.com.segmentedcontrolexample&hl=en) [Or try demo App online !](https://appetize.io/app/y4e91xhxgp47956bf73da4z4yg) [![](https://jitpack.io/v/RobertApikyan/SegmentedControl.svg)](https://jitpack.io/#RobertApikyan/SegmentedControl) [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) ## Segmented control for Android, with a lot of customization properties ## ScreenShots ## Download ### Gradle Add to project level build.gradle ```groovy allprojects { repositories { ... maven { url 'https://jitpack.io' } } } ``` Add dependency to app module level build.gradle ```groovy dependencies { implementation 'com.github.RobertApikyan:SegmentedControl:1.2.0' } ``` ### Maven ```xml jitpack.io https://jitpack.io ``` Add dependency ```xml com.github.RobertApikyan SegmentedControl 1.1.3 ``` ### Done. ## Simple usage in XML ```xml ``` Attributes ```xml setSupportedSelectionsCount(int) setDistributeEvenly(boolean) setDistributeEvenly(boolean) setColumnCount(int) addSegments(Object[]), addSegments(List) setSelectedStrokeColor(int) setUnSelectedStrokeColor(int) setSelectedBackgroundColor(int) setUnSelectedBackgroundColor(int) setSelectedTextColor(int) setUnSelectedTextColor(int) setTextSize(int) setTextHorizontalPadding(int) setTextVerticalPadding(int) setSegmentVerticalMargin(int) setSegmentHorizontalMargin(int) setRadius(int) setTopLeftRadius(int) setTopRightRadius(int) setBottomRightRadius(int) setBottomLeftRadius(int) setRadiusForEverySegment(boolean) setTypeFace(TypeFace) ``` **Note:** After every configuration change call segmentedControl.notifyConfigIsChanged() method # Example ```java segmentedControl.setStrokeWidth(width.intValue()); segmentedControl.setColumnCount(columnCount); segmentedControl.notifyConfigIsChanged(); ``` > SegmentedControl uses SegmentAdapter and SegmentViewHolder for displaying segments. There are allready exist a default implementations for SegmentAdapter (SegmentAdapterImpl) and SegmentViewHolder (SegmentViewHolderImpl), but if you want to make your custom implementation... well here is the steps 1. Define `segment_item.xml` inside `layouts` folder ```xml ``` 2. Create a `SegmentViewHolder` instance (`AppSegmentViewHolder`) (here I define the segment generic data type as a String) ```java public class AppSegmentViewHolder extends SegmentViewHolder { TextView textView; public AppSegmentViewHolder(@NonNull View sectionView) { super(sectionView); textView = (TextView) sectionView.findViewById(R.id.text_view); } @Override protected void onSegmentBind(String segmentData) { textView.setText(segmentData); } } ``` 3. Create a `SegmentAdapter` instance ```java public class AppSegmentAdapter extends SegmentAdapter { @NonNull @Override protected AppSegmentViewHolder onCreateViewHolder(@NonNull LayoutInflater layoutInflater, ViewGroup viewGroup, int i) { return new AppSegmentViewHolder(layoutInflater.inflate(R.layout.item_segment, null)); } } ``` 4. Pass the adapter to the segmentedControl ```java segmentedControl = (SegmentedControl) findViewById(R.id.segmented_control); segmentedControl.setAdapter(new AppSegmentAdapter()); ``` 5. Finally add segments data. ```java segmentedControl.addSegments(getResources().getStringArray(R.array.segments)); ``` That's it :) For custom implementation use `SegmentedControlUtils` helper class in order to define segment background type and background radius. [![View Robert Apikyan profile on LinkedIn](https://www.linkedin.com/img/webpromo/btn_viewmy_160x33.png)](https://www.linkedin.com/in/robert-apikyan-24b915130/) License ------- Copyright 2017 Robert Apikyan 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. ================================================ FILE: build.gradle ================================================ // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { jcenter() google() } dependencies { classpath 'com.android.tools.build:gradle:3.4.1' classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { jcenter() google() maven { url 'https://jitpack.io' } } } task clean(type: Delete) { delete rootProject.buildDir } ================================================ FILE: gradle/wrapper/gradle-wrapper.properties ================================================ #Fri Apr 19 11:27:29 AMT 2019 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-all.zip ================================================ FILE: gradle.properties ================================================ # Project-wide Gradle settings. # IDE (e.g. Android Studio) users: # Gradle settings configured through the IDE *will override* # any settings specified in this file. # For more details on how to configure your build environment visit # http://www.gradle.org/docs/current/userguide/build_environment.html # Specifies the JVM arguments used for the daemon process. # The setting is particularly useful for tweaking memory settings. org.gradle.jvmargs=-Xmx1536m # When configured, Gradle will run in incubating parallel mode. # This option should only be used with decoupled projects. More details, visit # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects # org.gradle.parallel=true ================================================ FILE: gradlew ================================================ #!/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 # 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\"`/" >/dev/null APP_HOME="`pwd -P`" cd "$SAVED" >/dev/null 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"` JAVACMD=`cygpath --unix "$JAVACMD"` # 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 "$@" ================================================ FILE: gradlew.bat ================================================ @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 ================================================ FILE: segmentedcontrolmodule/.gitignore ================================================ /build ================================================ FILE: segmentedcontrolmodule/build.gradle ================================================ apply plugin: 'com.android.library' android { compileSdkVersion 28 defaultConfig { minSdkVersion 14 targetSdkVersion 28 versionCode 1 versionName "1.2.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:28.0.0' api 'com.github.RobertApikyan:ViewComponent:1.0.3' api 'com.github.RobertApikyan:SecLayout:1.0.3' } task sourcesJar(type: Jar) { from android.sourceSets.main.java.srcDirs classifier = 'sources' } artifacts { archives sourcesJar } ================================================ FILE: segmentedcontrolmodule/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in D:\sdk/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the proguardFiles # directive in build.gradle. # # 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 *; #} # Uncomment this to preserve the line number information for # debugging stack traces. #-keepattributes SourceFile,LineNumberTable # If you keep the line number information, uncomment this to # hide the original source file name. #-renamesourcefileattribute SourceFile ================================================ FILE: segmentedcontrolmodule/src/main/AndroidManifest.xml ================================================ ================================================ FILE: segmentedcontrolmodule/src/main/java/segmented_control/widget/custom/android/com/segmentedcontrol/Assert.java ================================================ package segmented_control.widget.custom.android.com.segmentedcontrol; import section_layout.widget.custom.android.com.sectionlayout.SectionLayout; /** * Created by Robert Apikyan on 9/7/2017. */ class Assert { static void adapter(SectionLayout.Adapter adapter) { throwIf(adapter == null, new IllegalArgumentException("SegmentedControl#setAdapter -> adapter can't be null")); } static void columnCount(int columnCount) { throwIf(columnCount < Configs.DEFAULT_COLUMN_COUNT, new IllegalArgumentException("SegmentedControl#setColumnCount -> columnCounts value is invalid:" + " " + "columnCount = " + columnCount)); } static void outOfBounds(int position, int size, String methodName) { throwIf(position > size, new IndexOutOfBoundsException(methodName + " -> " + "position = " + position + " " + "size = " + size)); } private static void throwIf(boolean willThrow, Exception exception) { if (willThrow) { try { throw exception; } catch (Exception e) { e.printStackTrace(); } } } public static void supportedSelectionsCount(int supportedSelectionsCount) { throwIf(supportedSelectionsCount < Configs.DEFAULT_SUPPORTED_SELECTIONS_COUNT, new IllegalStateException("SegmentedControl#setSupportedSelectionsCount -> supportedSelectionsCount value is invalid: " + " " + "supportedSelectionsCount= "+supportedSelectionsCount)); } } ================================================ FILE: segmentedcontrolmodule/src/main/java/segmented_control/widget/custom/android/com/segmentedcontrol/Configs.java ================================================ package segmented_control.widget.custom.android.com.segmentedcontrol; import segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentDecoration; /** * Created by Robert Apikyan on 9/7/2017. */ class Configs { static final int DEFAULT_COLUMN_COUNT = 2; static final int DEFAULT_SUPPORTED_SELECTIONS_COUNT = 1; boolean willDistributeEvenly; boolean reselectionEnabled; int columnCount; int supportedSelectionsCount; SegmentDecoration segmentDecoration = new SegmentDecoration(); static Configs getDefault() { Configs configs = new Configs(); configs.reselectionEnabled = true; configs.willDistributeEvenly = false; configs.columnCount = DEFAULT_COLUMN_COUNT; configs.supportedSelectionsCount = DEFAULT_SUPPORTED_SELECTIONS_COUNT; return configs; } } ================================================ FILE: segmentedcontrolmodule/src/main/java/segmented_control/widget/custom/android/com/segmentedcontrol/Consumer.java ================================================ package segmented_control.widget.custom.android.com.segmentedcontrol; /** * Created by Robert Apikyan on 9/8/2017. */ interface Consumer { void apply(T t); } ================================================ FILE: segmentedcontrolmodule/src/main/java/segmented_control/widget/custom/android/com/segmentedcontrol/Notifier.java ================================================ package segmented_control.widget.custom.android.com.segmentedcontrol; import java.util.ArrayList; import java.util.List; import segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentViewHolder; import segmented_control.widget.custom.android.com.segmentedcontrol.listeners.OnSegmentClickListener; import segmented_control.widget.custom.android.com.segmentedcontrol.listeners.OnSegmentSelectRequestListener; import segmented_control.widget.custom.android.com.segmentedcontrol.listeners.OnSegmentSelectedListener; import static segmented_control.widget.custom.android.com.segmentedcontrol.utils.Utils.lazy; /** * Created by Robert Apikyan on 9/8/2017. */ class Notifier implements OnSegmentClickListener, OnSegmentSelectedListener, OnSegmentSelectRequestListener { private List> onSegmentClickListeners; private List> onSegmentSelectedListeners; @SuppressWarnings("unchecked") private OnSegmentSelectRequestListener onSegmentSelectRequestListener; @Override public void onSegmentClick(final SegmentViewHolder segmentViewHolder) { onEvent(onSegmentClickListeners, new Consumer>() { @Override public void apply(OnSegmentClickListener onSegmentClickListener) { onSegmentClickListener.onSegmentClick(segmentViewHolder); } }); } @Override public void onSegmentSelected(final SegmentViewHolder segmentViewHolder, final boolean isSelected, final boolean isReselected) { onEvent(onSegmentSelectedListeners, new Consumer>() { @Override public void apply(OnSegmentSelectedListener onSegmentSelectedListener) { onSegmentSelectedListener.onSegmentSelected(segmentViewHolder, isSelected, isReselected); } }); } @Override public boolean onSegmentSelectRequest(final SegmentViewHolder segmentViewHolder) { return onSegmentSelectRequestListener == null || onSegmentSelectRequestListener.onSegmentSelectRequest(segmentViewHolder); } void addOnSegmentClickListener(OnSegmentClickListener onSegmentClickListener) { onSegmentClickListeners = lazy(onSegmentClickListeners, new ArrayList>()); onSegmentClickListeners.add(onSegmentClickListener); } void removeOnSegmentClickListener(OnSegmentClickListener onSegmentClickListener) { onSegmentClickListeners = lazy(onSegmentClickListeners, new ArrayList>()); onSegmentClickListeners.remove(onSegmentClickListener); } void addOnSegmentSelectListener(OnSegmentSelectedListener onSegmentSelectedListener) { onSegmentSelectedListeners = lazy(onSegmentSelectedListeners, new ArrayList>()); onSegmentSelectedListeners.add(onSegmentSelectedListener); } void removeOnSegmentSelectListener(OnSegmentSelectedListener onSegmentSelectedListener) { onSegmentSelectedListeners = lazy(onSegmentSelectedListeners, new ArrayList>()); onSegmentSelectedListeners.remove(onSegmentSelectedListener); } void setOnSegmentSelectRequestListener(OnSegmentSelectRequestListener onSegmentSelectRequestListener) { this.onSegmentSelectRequestListener = onSegmentSelectRequestListener; } private void onEvent(List eventListeners, Consumer listenerConsumer) { if (eventListeners != null && eventListeners.size() != 0) { for (T t : eventListeners) { listenerConsumer.apply(t); } } } } ================================================ FILE: segmentedcontrolmodule/src/main/java/segmented_control/widget/custom/android/com/segmentedcontrol/SegmentConsumer.java ================================================ package segmented_control.widget.custom.android.com.segmentedcontrol; import segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentViewHolder; public interface SegmentConsumer { void apply(SegmentViewHolder segmentViewHolder); } ================================================ FILE: segmentedcontrolmodule/src/main/java/segmented_control/widget/custom/android/com/segmentedcontrol/SegmentedControl.java ================================================ package segmented_control.widget.custom.android.com.segmentedcontrol; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Typeface; import android.support.annotation.NonNull; import android.util.AttributeSet; import android.util.TypedValue; import android.view.LayoutInflater; import java.util.List; import section_layout.widget.custom.android.com.sectionlayout.SectionLayout; import segmented_control.widget.custom.android.com.segmented_control.R; import segmented_control.widget.custom.android.com.segmentedcontrol.custom_segment.SegmentAdapterImpl; import segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentAdapter; import segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentViewHolder; import segmented_control.widget.custom.android.com.segmentedcontrol.listeners.OnSegmentClickListener; import segmented_control.widget.custom.android.com.segmentedcontrol.listeners.OnSegmentSelectRequestListener; import segmented_control.widget.custom.android.com.segmentedcontrol.listeners.OnSegmentSelectedListener; import view_component.lib_android.com.view_component.base_view.layouts.ComponentFrameLayout; import static segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentDecoration.DEFAULT_SELECTION_ANIMATION_DURATION; /** * Created by Robert Apikyan on 8/18/2017. * /* Attributes * {@link #setDistributeEvenly(boolean)} * {@link #setReselectionEnabled(boolean)} * {@link #setColumnCount(int)} * {@link #addSegments(Object[])} {@link #addSegments(List)} * {@link #setSupportedSelectionsCount(int)} * {@link #setSelectedStrokeColor(int)} * {@link #setUnSelectedStrokeColor(int)} * {@link #setStrokeWidth(int)} * {@link #setSelectedBackgroundColor(int)} * {@link #setUnSelectedBackgroundColor(int)} * {@link #setSelectedTextColor(int)} * {@link #setUnSelectedTextColor(int)} * {@link #setTextSize(int)} * {@link #setTextHorizontalPadding(int)} * {@link #setTextVerticalPadding(int)} * {@link #setSegmentVerticalMargin(int)} * {@link #setSegmentHorizontalMargin(int)} * {@link #setRadius(int)} * {@link #setTopLeftRadius(int)} * {@link #setTopRightRadius(int)} * {@link #setBottomRightRadius(int)} * {@link #setBottomLeftRadius(int)} * {@link #setRadiusForEverySegment(boolean)} * * @param */ public class SegmentedControl extends ComponentFrameLayout, SegmentedControlControllerComponent> { public SegmentedControl(Context context) { this(context, null); } public SegmentedControl(Context context, AttributeSet attrs) { this(context, attrs, 0); } public SegmentedControl(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initAttr(attrs, defStyle); } private void initAttr(AttributeSet attrs, int defStyle) { TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.SegmentedControl, defStyle, 0); fetchAccentColor(); try { attrDistributeEvenly(typedArray); attrReselectionEnabled(typedArray); attrColumnCount(typedArray); attrSupportedSelectionsCount(typedArray); attrSelectedStrokeColor(typedArray); attrUnSelectedStrokeColor(typedArray); attrStrokeWidth(typedArray); attrSelectedBackgroundColor(typedArray); attrFocusedBackgroundColor(typedArray); attrSelectionAnimationDuration(typedArray); attrUnSelectedBackgroundColor(typedArray); attrSelectedTextColor(typedArray); attrUnSelectedTextColor(typedArray); attrTextSize(typedArray); attrFontAssetPath(typedArray); attrTextVerticalPadding(typedArray); attrTextHorizontalPadding(typedArray); attrSegmentHorizontalMargin(typedArray); attrSegmentVerticalMargin(typedArray); attrTopLeftRadius(typedArray); attrTopRightRadius(typedArray); attrBottomRightRadius(typedArray); attrBottomLeftRadius(typedArray); attrRadius(typedArray); attrRadiusForEverySegment(typedArray); attrSegments(typedArray); } finally { typedArray.recycle(); } } private void fetchAccentColor() { TypedValue tv = new TypedValue(); TypedArray typedArray = getContext().obtainStyledAttributes(tv.data, new int[]{R.attr.colorAccent}); try { getControllerComponent().setAccentColor(typedArray.getColor(0, 0)); } finally { typedArray.recycle(); } } private void attrSelectedStrokeColor(TypedArray typedArray) { obtainColorAttr(typedArray, R.styleable.SegmentedControl_selectedStrokeColor, new Consumer() { @Override public void apply(Integer color) { getControllerComponent().setSelectedStrokeColor(color); } }); } private void attrUnSelectedStrokeColor(TypedArray typedArray) { obtainColorAttr(typedArray, R.styleable.SegmentedControl_unSelectedStrokeColor, new Consumer() { @Override public void apply(Integer color) { getControllerComponent().setUnSelectedStrokeColor(color); } }); } private void attrStrokeWidth(TypedArray typedArray) { obtainDimensionAttr(typedArray, R.styleable.SegmentedControl_strokeWidth, new Consumer() { @Override public void apply(Integer width) { getControllerComponent().setStrokeWidth(width); } }); } private void attrSelectedBackgroundColor(TypedArray typedArray) { obtainColorAttr(typedArray, R.styleable.SegmentedControl_selectedBackgroundColor, new Consumer() { @Override public void apply(Integer color) { getControllerComponent().setSelectedBackgroundColor(color); } }); } private void attrUnSelectedBackgroundColor(TypedArray typedArray) { obtainColorAttr(typedArray, R.styleable.SegmentedControl_unSelectedBackgroundColor, new Consumer() { @Override public void apply(Integer color) { getControllerComponent().setUnSelectedBackgroundColor(color); } }); } private void attrFocusedBackgroundColor(TypedArray typedArray) { obtainColorAttr(typedArray, R.styleable.SegmentedControl_focusedBackgroundColor, new Consumer() { @Override public void apply(Integer color) { getControllerComponent().setFocusedBackgroundColor(color); } }); } private void attrSelectionAnimationDuration(TypedArray typedArray) { getControllerComponent().setSelectionAnimationDuration( typedArray.getInt(R.styleable.SegmentedControl_selectionAnimationDuration, DEFAULT_SELECTION_ANIMATION_DURATION)); } private void attrSelectedTextColor(TypedArray typedArray) { obtainColorAttr(typedArray, R.styleable.SegmentedControl_selectedTextColor, new Consumer() { @Override public void apply(Integer color) { getControllerComponent().setSelectedTextColor(color); } }); } private void attrUnSelectedTextColor(TypedArray typedArray) { obtainColorAttr(typedArray, R.styleable.SegmentedControl_unSelectedTextColor, new Consumer() { @Override public void apply(Integer color) { getControllerComponent().setUnSelectedTextColor(color); } }); } private void attrTextSize(TypedArray typedArray) { int textSize = typedArray.getDimensionPixelSize(R.styleable.SegmentedControl_textSize, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 14, getResources().getDisplayMetrics())); if (textSize > 0) { getControllerComponent().setTextSize(textSize); } } private void attrFontAssetPath(TypedArray typedArray) { String fontPath = typedArray.getString(R.styleable.SegmentedControl_fontAssetPath); if (fontPath != null && !fontPath.isEmpty()) { getControllerComponent().setTypeFace(Typeface.createFromAsset(getContext().getAssets(), fontPath)); } } private void attrTextVerticalPadding(TypedArray typedArray) { obtainDimensionAttr(typedArray, R.styleable.SegmentedControl_textVerticalPadding, new Consumer() { @Override public void apply(Integer dimen) { getControllerComponent().setTextVerticalPadding(dimen); } }); } private void attrTextHorizontalPadding(TypedArray typedArray) { obtainDimensionAttr(typedArray, R.styleable.SegmentedControl_textHorizontalPadding, new Consumer() { @Override public void apply(Integer dimen) { getControllerComponent().setTextHorizontalPadding(dimen); } }); } private void attrSegmentVerticalMargin(TypedArray typedArray) { obtainDimensionAttr(typedArray, R.styleable.SegmentedControl_segmentVerticalMargin, new Consumer() { @Override public void apply(Integer dimen) { getControllerComponent().setSegmentVerticalMargin(dimen); } }); } private void attrSegmentHorizontalMargin(TypedArray typedArray) { obtainDimensionAttr(typedArray, R.styleable.SegmentedControl_segmentHorizontalMargin, new Consumer() { @Override public void apply(Integer dimen) { getControllerComponent().setSegmentHorizontalMargin(dimen); } }); } private void attrRadius(TypedArray typedArray) { obtainDimensionAttr(typedArray, R.styleable.SegmentedControl_radius, new Consumer() { @Override public void apply(Integer dimen) { getControllerComponent().setRadius(dimen); } }); } private void attrTopLeftRadius(TypedArray typedArray) { obtainDimensionAttr(typedArray, R.styleable.SegmentedControl_topLeftRadius, new Consumer() { @Override public void apply(Integer dimen) { getControllerComponent().setTopLeftRadius(dimen); } }); } private void attrTopRightRadius(TypedArray typedArray) { obtainDimensionAttr(typedArray, R.styleable.SegmentedControl_topRightRadius, new Consumer() { @Override public void apply(Integer dimen) { getControllerComponent().setTopRightRadius(dimen); } }); } private void attrBottomRightRadius(TypedArray typedArray) { obtainDimensionAttr(typedArray, R.styleable.SegmentedControl_bottomRightRadius, new Consumer() { @Override public void apply(Integer dimen) { getControllerComponent().setBottomRightRadius(dimen); } }); } private void attrBottomLeftRadius(TypedArray typedArray) { obtainDimensionAttr(typedArray, R.styleable.SegmentedControl_bottomLeftRadius, new Consumer() { @Override public void apply(Integer dimen) { getControllerComponent().setBottomLeftRadius(dimen); } }); } private void attrRadiusForEverySegment(TypedArray typedArray) { boolean radiusForEverySegment = typedArray.getBoolean(R.styleable.SegmentedControl_radiusForEverySegment, false); getControllerComponent().setRadiusForEverySegment(radiusForEverySegment); } private void attrSegments(TypedArray typedArray) { CharSequence[] items = typedArray.getTextArray(R.styleable.SegmentedControl_segments); useDefaultAdapter(); //noinspection unchecked getControllerComponent().addSegments((D[]) items); } private void attrColumnCount(TypedArray typedArray) { int columnCount = typedArray.getInteger(R.styleable.SegmentedControl_columnCount, Configs.DEFAULT_COLUMN_COUNT); getControllerComponent().setColumnCount(columnCount); notifyConfigIsChanged(); } private void attrSupportedSelectionsCount(TypedArray typedArray) { int supportedSelectionsCount = typedArray.getInteger(R.styleable.SegmentedControl_supportedSelectionsCount, Configs.DEFAULT_SUPPORTED_SELECTIONS_COUNT); if (supportedSelectionsCount > 0) { getControllerComponent().setSupportedSelectionsCount(supportedSelectionsCount); } } private void attrDistributeEvenly(TypedArray typedArray) { boolean willDistribute = typedArray.getBoolean(R.styleable.SegmentedControl_distributeEvenly, false); getControllerComponent().setDistributeEvenly(willDistribute); getControllerComponent().notifyConfigIsChanged(); } private void attrReselectionEnabled(TypedArray typedArray) { boolean reselectionEnabled = typedArray.getBoolean(R.styleable.SegmentedControl_reselectionEnabled, true); getControllerComponent().setReselectionEnabled(reselectionEnabled); } private void obtainColorAttr(TypedArray typedArray, int attr, Consumer colorConsumer) { int color = typedArray.getColor(attr, -2); // -1 is white if (color != -2) { colorConsumer.apply(color); } } private void obtainDimensionAttr(TypedArray typedArray, int attr, Consumer dimensionConsumer) { int dimensionPixelSize = typedArray.getDimensionPixelSize(attr, -1); if (dimensionPixelSize != -1) { dimensionConsumer.apply(dimensionPixelSize); } } @NonNull @Override public SegmentedControlViewComponent createViewComponent(@NonNull LayoutInflater layoutInflater) { addView(new SectionLayout(getContext()), 0); return new SegmentedControlViewComponent<>(this); } @NonNull @Override public SegmentedControlControllerComponent createControllerComponent() { return new SegmentedControlControllerComponent<>(); } /** * Will enabled multy selection, default value is 1, only one item can be selected at the time * @param supportedSelectionsCount specifies the count of selected segments at the same time, * if the selection count is reached the elder selection * will be unselected */ public void setSupportedSelectionsCount(int supportedSelectionsCount) { Assert.supportedSelectionsCount(supportedSelectionsCount); getControllerComponent().setSupportedSelectionsCount(supportedSelectionsCount); } /** * @param columnCount The column count for SegmentedControl */ public void setColumnCount(int columnCount) { Assert.columnCount(columnCount); getControllerComponent().setColumnCount(columnCount); } /** * @param adapter, NonNull adapter (extended from {@link SegmentAdapter}) */ public void setAdapter(@NonNull SegmentAdapter adapter) { Assert.adapter(adapter); getControllerComponent().setAdapter(adapter); } /** * set the adapter {@link SegmentAdapter} with {@link segmented_control.widget.custom.android.com.segmentedcontrol.custom_segment.SegmentViewHolderImpl} view holder * where data D data type is String. use segmentedControl.addSegments(String[] segmentDataArray) or segmentedControl.addSegments(List segmentDataList) methods */ public void useDefaultAdapter() { setAdapter(new SegmentAdapterImpl()); } /** * Add segments to segmentController * * @param segmentData, specified array Data type */ public void addSegments(D[] segmentData) { getControllerComponent().addSegments(segmentData); } /** * Add segments to segmentController * * @param segmentData, specified list Data type */ public void addSegments(List segmentData) { getControllerComponent().addSegments(segmentData); } /** * @param willDistributeEvenly, true each section width with will be equal to each other, * false each section width will be measured depending on its content width; */ public void setDistributeEvenly(boolean willDistributeEvenly) { getControllerComponent().setDistributeEvenly(willDistributeEvenly); } /** * @param isEnabled if true second click to segment will not turn it from selected to unselected state, * if false the second click will turn it from selected to un selected state, * default value is true */ public void setReselectionEnabled(boolean isEnabled) { getControllerComponent().setReselectionEnabled(isEnabled); } /** * @param onSegmentClickListener, every time click event will be notified, * even if the segment is already selected */ public void addOnSegmentClickListener(OnSegmentClickListener onSegmentClickListener) { getControllerComponent().addOnSegmentClickListener(onSegmentClickListener); } /** * @param onSegmentClickListener, every time click event will be notified, * even if the segment is already selected *

* Remove listener */ public void removeOnSegmentClickListener(OnSegmentClickListener onSegmentClickListener) { getControllerComponent().removeOnSegmentClickListener(onSegmentClickListener); } /** * @param onSegmentSelectedListener, event will be notified, when segment is selected and unSelected and reselected, * for more info check out {@link OnSegmentSelectedListener} class */ public void addOnSegmentSelectListener(OnSegmentSelectedListener onSegmentSelectedListener) { getControllerComponent().addOnSegmentSelectListener(onSegmentSelectedListener); } /** * @param onSegmentSelectedListener, event will be notified, when segment is selected and unSelected and reselected, * for more info check out {@link OnSegmentSelectedListener} class *

* Remove listener */ public void removeOnSegmentSelectListener(OnSegmentSelectedListener onSegmentSelectedListener) { getControllerComponent().removeOnSegmentSelectListener(onSegmentSelectedListener); } /** * @param onSegmentSelectRequestListener, event will be triggered after click event and before selection event * for more info click out {@link OnSegmentSelectRequestListener} class */ public void setOnSegmentSelectRequestListener(OnSegmentSelectRequestListener onSegmentSelectRequestListener) { getControllerComponent().setOnSegmentSelectRequestListener(onSegmentSelectRequestListener); } /** * Removes all segments */ public void removeAllSegments() { getControllerComponent().removeAllSegments(); } /** * find the segment view holder with the segment absolute position * * @param position, the segment position * @return SegmentViewHolder instance for specified position */ public SegmentViewHolder findSegmentByAbsolutePosition(int position) { Assert.outOfBounds(position, size(), "SegmentedControl#findSegmentByAbsolutePosition"); return getControllerComponent().findSegmentByAbsolutePosition(position); } /** * find the segment with column number and row position * * @param column, Segment column number * @param row, Segment row position * @return SegmentViewHolder instance for specified column and row numbers */ public SegmentViewHolder findSegmentByColumnAndRow(int column, int row) { Assert.outOfBounds(getControllerComponent().getAbsolutePosition(column, row), size(), "SegmentedControl#setSelectedSegment"); return getControllerComponent().findSegmentByColumnAndRow(column, row); } /** * Select the selected position * * @param position, Segment position */ public void setSelectedSegment(int position) { Assert.outOfBounds(position, size(), "SegmentedControl#setSelectedSegment"); getControllerComponent().setSelectedSegment(position); } /** * Select the segment with specified column number and row position * * @param column, Segment column number * @param row, Segment row position */ public void setSelectedSegment(int column, int row) { Assert.outOfBounds(getControllerComponent().getAbsolutePosition(column, row), size(), "SegmentedControl#setSelectedSegment"); getControllerComponent().setSelectedSegment(column, row); } /** * Iterate on segments, and pass the view holders as an argument for {@link SegmentConsumer} * * @param segmentConsumer, Segment consumer */ public void forEachSegment(SegmentConsumer segmentConsumer) { getControllerComponent().forEachSegment(segmentConsumer); } public void setSelectedStrokeColor(int color) { getControllerComponent().setSelectedStrokeColor(color); } public void setUnSelectedStrokeColor(int color) { getControllerComponent().setUnSelectedStrokeColor(color); } public void setFocusedBackgroundColor(int color) { getControllerComponent().setFocusedBackgroundColor(color); } /** * Set segments selection animation duration value * * @param duration in milliseconds */ public void setSelectionAnimationDuration(int duration) { getControllerComponent().setSelectionAnimationDuration(duration); } public void setStrokeWidth(int width) { getControllerComponent().setStrokeWidth(width); } public void setSelectedBackgroundColor(int color) { getControllerComponent().setSelectedBackgroundColor(color); } public void setUnSelectedBackgroundColor(int color) { getControllerComponent().setUnSelectedBackgroundColor(color); } public void setSelectedTextColor(int color) { getControllerComponent().setSelectedTextColor(color); } public void setUnSelectedTextColor(int color) { getControllerComponent().setUnSelectedTextColor(color); } public void setTextSize(int textSize) { getControllerComponent().setTextSize(textSize); } public void setTypeFace(Typeface typeFace) { getControllerComponent().setTypeFace(typeFace); } public void setTextVerticalPadding(int padding) { getControllerComponent().setTextVerticalPadding(padding); } public void setTextHorizontalPadding(int padding) { getControllerComponent().setTextHorizontalPadding(padding); } public void setSegmentVerticalMargin(int margin) { getControllerComponent().setSegmentVerticalMargin(margin); } public void setSegmentHorizontalMargin(int margin) { getControllerComponent().setSegmentHorizontalMargin(margin); } public void setRadius(int radius) { getControllerComponent().setRadius(radius); } public void setTopLeftRadius(int radius) { getControllerComponent().setTopLeftRadius(radius); } public void setTopRightRadius(int radius) { getControllerComponent().setTopRightRadius(radius); } public void setBottomRightRadius(int radius) { getControllerComponent().setBottomRightRadius(radius); } public void setBottomLeftRadius(int radius) { getControllerComponent().setBottomLeftRadius(radius); } /** * @param radiusForEverySegment, true every segment corners will be rounded, false only top left,top right, bottom right and bottom left corners will be rounded */ public void setRadiusForEverySegment(boolean radiusForEverySegment) { getControllerComponent().setRadiusForEverySegment(radiusForEverySegment); } /** * Removes the last selected segment selection, SegmentViewHolder's onSegmentSelected method will be called * with isSelected = false, isReselected = false */ public void clearSelection() { getControllerComponent().clearSelection(false); } /** * Removes the last selected segment selection, SegmentViewHolder's onSegmentSelected method will be called * with isSelected = false, isReselected = false. * * @param notifySegmentSelectedListener if true SegmentSelectedListeners will be notified. */ public void clearSelection(boolean notifySegmentSelectedListener) { getControllerComponent().clearSelection(notifySegmentSelectedListener); } /** * Call this method after every configuration change * setColumnCount, setRadius et... */ public void notifyConfigIsChanged() { getControllerComponent().notifyConfigIsChanged(); } public int size() { return getControllerComponent().size(); } // public SegmentViewHolder getSelectedViewHolder() { // return getControllerComponent().getSelectedViewHolder(); // } /** * @return int[]{column,row} Section column and row numbers */ public int[] getLastSelectedColumnAndRow() { return getControllerComponent().getLastSelectedColumnAndRow(); } public int getLastSelectedAbsolutePosition() { return getControllerComponent().getLastSelectedAbsolutePosition(); } public boolean hasSelectedSegment() { return getControllerComponent().isSelected(); } } ================================================ FILE: segmentedcontrolmodule/src/main/java/segmented_control/widget/custom/android/com/segmentedcontrol/SegmentedControlControllerComponent.java ================================================ package segmented_control.widget.custom.android.com.segmentedcontrol; import android.graphics.Typeface; import android.support.annotation.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Queue; import section_layout.widget.custom.android.com.sectionlayout.SectionLayout; import section_layout.widget.custom.android.com.sectionlayout.distributive_section_layout.DistributiveSectionLayout; import segmented_control.widget.custom.android.com.segmentedcontrol.item_row.SegmentRowAdapter; import segmented_control.widget.custom.android.com.segmentedcontrol.item_row.SegmentRowViewHolder; import segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentAdapter; import segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentData; import segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentDecoration; import segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentViewHolder; import segmented_control.widget.custom.android.com.segmentedcontrol.listeners.OnSegmentClickListener; import segmented_control.widget.custom.android.com.segmentedcontrol.listeners.OnSegmentSelectRequestListener; import segmented_control.widget.custom.android.com.segmentedcontrol.listeners.OnSegmentSelectedListener; import view_component.lib_android.com.view_component.base_view.ControllerComponent; /** * Created by Robert Apikyan on 9/5/2017. */ class SegmentedControlControllerComponent extends ControllerComponent> { private final Configs configs = Configs.getDefault(); // private SegmentViewHolder lastClickedSegmentViewHolder; private LinkedList> selectedSegments = new LinkedList<>(); private final Notifier notifier = new Notifier<>(); private final List dataList = new ArrayList<>(); // private final OnSegmentClickListener _onSegmentClickListener = new OnSegmentClickListener() { // @Override // public void onSegmentClick(SegmentViewHolder segmentViewHolder) { // notifier.onSegmentClick(segmentViewHolder); // // if (segmentViewHolder.equals(lastClickedSegmentViewHolder)) { // // on section reselected // segmentViewHolder.setSelected(true); // notifier.onSegmentSelected(segmentViewHolder, true, true); // } else if (notifier.onSegmentSelectRequest(segmentViewHolder)) { // // on section selected // // unSelect the last one // if (lastClickedSegmentViewHolder != null) { // lastClickedSegmentViewHolder.setSelected(false); // notifier.onSegmentSelected(lastClickedSegmentViewHolder, false, false); // } // // select the current // lastClickedSegmentViewHolder = segmentViewHolder; // segmentViewHolder.setSelected(true); // notifier.onSegmentSelected(segmentViewHolder, true, false); // } // } // }; private final OnSegmentClickListener onSegmentClickListener = new OnSegmentClickListener() { @Override public void onSegmentClick(SegmentViewHolder segmentViewHolder) { notifier.onSegmentClick(segmentViewHolder); int index = selectedSegments.indexOf(segmentViewHolder); boolean contains = index != -1; if (contains) { // on section reselected SegmentViewHolder viewHolder = selectedSegments.get(index); if (configs.reselectionEnabled){ viewHolder.setSelected(true); notifier.onSegmentSelected(segmentViewHolder, true, true); }else{ selectedSegments.remove(index); viewHolder.setSelected(false); notifier.onSegmentSelected(segmentViewHolder, false, false); } } else if (notifier.onSegmentSelectRequest(segmentViewHolder)) { // on section selected // unSelect the last one SegmentViewHolder lastSelected = addSelectedSegmentViewHolder(segmentViewHolder); if (lastSelected != null) { lastSelected.setSelected(false); notifier.onSegmentSelected(lastSelected, false, false); } // select the current segmentViewHolder.setSelected(true); notifier.onSegmentSelected(segmentViewHolder, true, false); } } }; /** * Watch the supported selections count, if limit is reached the oldest segment will be removed from * selections list and returned back to method caller * * @param segmentViewHolder new selected segment; * @return oldest selection */ @Nullable private SegmentViewHolder addSelectedSegmentViewHolder(SegmentViewHolder segmentViewHolder) { selectedSegments.add(segmentViewHolder); if (selectedSegments.size() > configs.supportedSelectionsCount) { return selectedSegments.remove(0); } return null; } private SegmentViewHolder getLastSelectedViewHolder() { return selectedSegments.size() > 0 ? selectedSegments.getLast() : null; } private void addSegment(D segmentData) { if (getVerticalSectionLayout().size() == 0 || !canAddToLastRow()) { addNewRow(); } addSegmentToLastRow(segmentData); } // removeLastSelected = true // private void removeAllSegments(boolean removeLastSelected) { // for (int row = 0; row < getVerticalSectionLayout().size(); row++) { // getHorizontalSectionLayout(row).removeAllSections(); // } // getVerticalSectionLayout().removeAllSections(); // dataList.clear(); // // if (removeLastSelected) { // lastClickedSegmentViewHolder = null; // } // } private void removeAllSegments(boolean removeLastSelected) { for (int row = 0; row < getVerticalSectionLayout().size(); row++) { getHorizontalSectionLayout(row).removeAllSections(); } getVerticalSectionLayout().removeAllSections(); dataList.clear(); if (removeLastSelected) { selectedSegments.clear(); } } private void addSegmentToLastRow(D segmentData) { DistributiveSectionLayout> horizontalSectionLayout = getHorizontalSectionLayout(getLastRowIndex()); horizontalSectionLayout .addSection(SegmentData.create(segmentData, onSegmentClickListener, getAbsolutePosition(getLastHorizontalSectionLayout().size(), getVerticalSectionLayout().size() - 1), getLastRowIndex(), horizontalSectionLayout.size(), size(), configs.columnCount, configs.segmentDecoration)); horizontalSectionLayout.requestLayout(); } private int[] getRowAndColumnWithAbsolutePosition(int position) { int smallDiff = position % configs.columnCount; int diff = position - smallDiff; int row = (diff / configs.columnCount) + (smallDiff == configs.columnCount ? 1 : 0); int column = position % configs.columnCount; return new int[]{row, column}; } void notifyConfigIsChanged() { recreate(false); } // public void clearSelection(boolean notifySegmentSelectedListener) { // if (lastClickedSegmentViewHolder != null) { // lastClickedSegmentViewHolder.setSelected(false); // // if (notifySegmentSelectedListener) { // notifier.onSegmentSelected(lastClickedSegmentViewHolder, false, false); // } // // lastClickedSegmentViewHolder = null; // } // } public void clearSelection(boolean notifySegmentSelectedListener) { if (!selectedSegments.isEmpty()) { for (SegmentViewHolder selectedSegment : selectedSegments) { selectedSegment.setSelected(false); if (notifySegmentSelectedListener) { notifier.onSegmentSelected(selectedSegment, false, false); } } selectedSegments.clear(); } } // private void recreate(boolean removeLastSelected) { // if (dataList.size() == 0) return; // List itemsData = new ArrayList<>(dataList); // removeAllSegments(removeLastSelected); // addSegments(itemsData); // if (lastClickedSegmentViewHolder != null) { // setSelectedSegment(lastClickedSegmentViewHolder.getAbsolutePosition()); // } // } private void recreate(boolean removeLastSelected) { if (dataList.size() == 0) return; List itemsData = new ArrayList<>(dataList); removeAllSegments(removeLastSelected); addSegments(itemsData); SegmentViewHolder lastSelection = getLastSelectedViewHolder(); if (lastSelection != null) { setSelectedSegment(lastSelection.getAbsolutePosition()); } } private boolean canAddToLastRow() { return getHorizontalSectionLayout(getLastRowIndex()).size() < configs.columnCount; } private void addNewRow() { //noinspection unchecked getVerticalSectionLayout().addSection(configs.willDistributeEvenly); } private SectionLayout getVerticalSectionLayout() { //noinspection ConstantConditions return getViewComponent().verticalSectionLayout; } private DistributiveSectionLayout> getHorizontalSectionLayout(int row) { //noinspection unchecked SegmentRowViewHolder segmentedViewHolder = (SegmentRowViewHolder) getVerticalSectionLayout().getViewHolderForAdapterPosition(row); return segmentedViewHolder.getDistributiveSectionLayout(); } private DistributiveSectionLayout> getLastHorizontalSectionLayout() { return getHorizontalSectionLayout(getLastRowIndex()); } private int getLastRowIndex() { return getVerticalSectionLayout().size() - 1; } SegmentViewHolder findSegmentByAbsolutePosition(int position) { int[] point = getRowAndColumnWithAbsolutePosition(position); return findSegmentByColumnAndRow(point[0], point[1]); } SegmentViewHolder findSegmentByColumnAndRow(int column, int row) { return (SegmentViewHolder) getHorizontalSectionLayout(column).getViewHolderForAdapterPosition(row); } void forEachSegment(SegmentConsumer segmentConsumer) { for (int row = 0; row < getVerticalSectionLayout().size(); row++) { DistributiveSectionLayout> horizontalSectionLayout = getHorizontalSectionLayout(row); for (int column = 0; column < horizontalSectionLayout.size(); column++) { segmentConsumer.apply(findSegmentByColumnAndRow(row, column)); } } } void setAccentColor(int color) { configs.segmentDecoration = SegmentDecoration.createDefault(getContext(), color); } void setSelectedStrokeColor(int color) { configs.segmentDecoration.selectedStrokeColor = color; } void setUnSelectedStrokeColor(int color) { configs.segmentDecoration.unSelectedStrokeColor = color; } void setStrokeWidth(int width) { configs.segmentDecoration.strokeWidth = width; } void setSelectedBackgroundColor(int color) { configs.segmentDecoration.selectBackgroundColor = color; } void setUnSelectedBackgroundColor(int color) { configs.segmentDecoration.unSelectedBackgroundColor = color; } void setFocusedBackgroundColor(int color) { configs.segmentDecoration.focusedBackgroundColor = color; } void setReselectionEnabled(boolean isEnabled){ configs.reselectionEnabled = isEnabled; } void setSelectionAnimationDuration(int duration) { configs.segmentDecoration.selectionAnimationDuration = duration; } void setSelectedTextColor(int color) { configs.segmentDecoration.selectedTextColor = color; } void setUnSelectedTextColor(int color) { configs.segmentDecoration.unSelectedTextColor = color; } void setTextSize(int textSize) { configs.segmentDecoration.textSize = textSize; } void setTypeFace(Typeface typeFace) { configs.segmentDecoration.typeface = typeFace; } void setTextVerticalPadding(int padding) { configs.segmentDecoration.textVerticalPadding = padding; } void setTextHorizontalPadding(int padding) { configs.segmentDecoration.textHorizontalPadding = padding; } void setSegmentVerticalMargin(int margin) { configs.segmentDecoration.segmentVerticalMargin = margin; } void setSegmentHorizontalMargin(int margin) { configs.segmentDecoration.segmentHorizontalMargin = margin; } void setRadius(int radius) { setTopLeftRadius(radius); setTopRightRadius(radius); setBottomRightRadius(radius); setBottomLeftRadius(radius); } void setTopLeftRadius(int radius) { configs.segmentDecoration.topLeftRadius = radius; } void setTopRightRadius(int radius) { configs.segmentDecoration.topRightRadius = radius; } void setBottomRightRadius(int radius) { configs.segmentDecoration.bottomRightRadius = radius; } void setBottomLeftRadius(int radius) { configs.segmentDecoration.bottomLeftRadius = radius; } void setRadiusForEverySegment(boolean radiusForEverySegment) { configs.segmentDecoration.radiusForEverySegment = radiusForEverySegment; } void setAdapter(SegmentAdapter adapter) { //noinspection ConstantConditions, setAdapter will be called from SegmentedControl getViewComponent().verticalSectionLayout.withAdapter(new SegmentRowAdapter(adapter)); } void addSegments(D[] segmentDataArray) { if (segmentDataArray == null || segmentDataArray.length == 0) return; addSegments(new ArrayList<>(Arrays.asList(segmentDataArray))); } void addSegments(List segmentDataList) { if (segmentDataList == null || segmentDataList.size() == 0) return; dataList.addAll(new ArrayList<>(segmentDataList)); for (D segmentData : dataList) { addSegment(segmentData); } } void removeAllSegments() { removeAllSegments(true); } void setDistributeEvenly(boolean willDistributeEvenly) { configs.willDistributeEvenly = willDistributeEvenly; } void setSupportedSelectionsCount(int supportedSelectionsCount) { configs.supportedSelectionsCount = supportedSelectionsCount; } void setColumnCount(int columnCount) { configs.columnCount = columnCount; } void addOnSegmentClickListener(OnSegmentClickListener onSegmentClickListener) { notifier.addOnSegmentClickListener(onSegmentClickListener); } void removeOnSegmentClickListener(OnSegmentClickListener onSegmentClickListener) { notifier.removeOnSegmentClickListener(onSegmentClickListener); } void addOnSegmentSelectListener(OnSegmentSelectedListener onSegmentSelectedListener) { notifier.addOnSegmentSelectListener(onSegmentSelectedListener); } void removeOnSegmentSelectListener(OnSegmentSelectedListener onSegmentSelectedListener) { notifier.removeOnSegmentSelectListener(onSegmentSelectedListener); } void setOnSegmentSelectRequestListener(OnSegmentSelectRequestListener onSegmentSelectRequestListener) { notifier.setOnSegmentSelectRequestListener(onSegmentSelectRequestListener); } void setSelectedSegment(int absolutePosition) { int[] point = getRowAndColumnWithAbsolutePosition(absolutePosition); setSelectedSegment(point[0], point[1]); } void setSelectedSegment(int column, int row) { onSegmentClickListener.onSegmentClick(findSegmentByColumnAndRow(column, row)); } // SegmentViewHolder getSelectedViewHolder() { // return lastClickedSegmentViewHolder; // } List> getSelectedViewHolders() { return selectedSegments; } int[] getLastSelectedColumnAndRow() { SegmentViewHolder lastSelection = getLastSelectedViewHolder(); if (lastSelection != null) { return new int[]{lastSelection.getColumn(), lastSelection.getRow()}; } else { return new int[]{-1, -1}; } } // int getLastSelectedAbsolutePosition() { SegmentViewHolder lastSelection = getLastSelectedViewHolder(); if (lastSelection != null) { return lastSelection.getAbsolutePosition(); } else { return -1; } } // boolean isSelected() { // return lastClickedSegmentViewHolder != null; // } boolean isSelected() { return !selectedSegments.isEmpty(); } int size() { return dataList.size(); } int getAbsolutePosition(int column, int row) { return row * configs.columnCount + column; } } ================================================ FILE: segmentedcontrolmodule/src/main/java/segmented_control/widget/custom/android/com/segmentedcontrol/SegmentedControlViewComponent.java ================================================ package segmented_control.widget.custom.android.com.segmentedcontrol; import android.support.annotation.NonNull; import android.view.View; import android.widget.LinearLayout; import section_layout.widget.custom.android.com.sectionlayout.SectionLayout; import view_component.lib_android.com.view_component.base_view.ViewComponent; /** * Created by Robert Apikyan on 9/5/2017. */ class SegmentedControlViewComponent extends ViewComponent { final SectionLayout verticalSectionLayout; SegmentedControlViewComponent(@NonNull View rootView) { super(rootView); //noinspection unchecked verticalSectionLayout = (SectionLayout) getRootViewGroup().getChildAt(0); verticalSectionLayout.setOrientation(LinearLayout.VERTICAL); } } ================================================ FILE: segmentedcontrolmodule/src/main/java/segmented_control/widget/custom/android/com/segmentedcontrol/custom_segment/SegmentAdapterImpl.java ================================================ package segmented_control.widget.custom.android.com.segmentedcontrol.custom_segment; import android.support.annotation.NonNull; import android.view.LayoutInflater; import android.view.ViewGroup; import segmented_control.widget.custom.android.com.segmented_control.R; import segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentAdapter; /** * Created by Robert Apikyan on 9/8/2017. */ public class SegmentAdapterImpl extends SegmentAdapter { @NonNull @Override protected SegmentViewHolderImpl onCreateViewHolder(@NonNull LayoutInflater layoutInflater, ViewGroup viewGroup, int i) { return new SegmentViewHolderImpl(layoutInflater.inflate(R.layout.item_segment_impl, null)); } } ================================================ FILE: segmentedcontrolmodule/src/main/java/segmented_control/widget/custom/android/com/segmentedcontrol/custom_segment/SegmentViewHolderImpl.java ================================================ package segmented_control.widget.custom.android.com.segmentedcontrol.custom_segment; import android.animation.ValueAnimator; import android.annotation.SuppressLint; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.annotation.NonNull; import android.util.TypedValue; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import segmented_control.widget.custom.android.com.segmented_control.R; import segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentViewHolder; import static segmented_control.widget.custom.android.com.segmentedcontrol.utils.Utils.createBackgroundAnimation; import static segmented_control.widget.custom.android.com.segmentedcontrol.utils.Utils.createRadius; import static segmented_control.widget.custom.android.com.segmentedcontrol.utils.Utils.defineRadiusForPosition; import static segmented_control.widget.custom.android.com.segmentedcontrol.utils.Utils.getBackground; import static segmented_control.widget.custom.android.com.segmentedcontrol.utils.Utils.isInBounds; /** * Created by Robert Apikyan on 9/8/2017. */ public class SegmentViewHolderImpl extends SegmentViewHolder { private TextView itemTV; private float[] radius; private ValueAnimator va; private int[] windowLocation; private final ValueAnimator.AnimatorUpdateListener bgAnimListener = new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { int colorArgb = (int) animation.getAnimatedValue(); Drawable bg = getBackground(getStrokeWidth(), isSelected() ? getSelectedStrokeColor() : getUnSelectedStrokeColor(), colorArgb, radius); setBackground(bg); } }; @SuppressWarnings("FieldCanBeLocal") private final View.OnTouchListener segmentTouchListener = new View.OnTouchListener() { @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouch(View v, MotionEvent event) { if (isSelected()) { return false; } if (event.getAction() == MotionEvent.ACTION_DOWN) { setBackground(getFocusedBackground()); } else if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL || event.getAction() == MotionEvent.ACTION_POINTER_UP || event.getAction() == MotionEvent.ACTION_OUTSIDE) { if (!isInBounds(event.getX(), event.getY(), windowLocation[0], windowLocation[1], getSectionView().getMeasuredWidth(), getSectionView().getMeasuredHeight())) { setBackground(isSelected() ? getSelectedBackground() : getUnSelectedBackground()); } } return false; } }; public SegmentViewHolderImpl(@NonNull View sectionView) { super(sectionView); itemTV = sectionView.findViewById(R.id.item_segment_tv); sectionView.setOnTouchListener(segmentTouchListener); } @Override protected void onSegmentBind(CharSequence segmentData) { initScreenLocation(); itemTV.setText(segmentData); if (isRadiusForEverySegment()) { radius = createRadius(getTopLeftRadius(), getTopRightRadius(), getBottomRightRadius(), getBottomLeftRadius()); } else { radius = defineRadiusForPosition(getAbsolutePosition(), getColumnCount(), getCurrentSize(), getTopLeftRadius(), getTopRightRadius(), getBottomRightRadius(), getBottomLeftRadius()); } setSectionDecorationSelected(false, false); itemTV.setTextSize(TypedValue.COMPLEX_UNIT_PX, getTextSize()); if (getTypeFace() != null) { itemTV.setTypeface(getTypeFace()); } itemTV.setPadding(getTextHorizontalPadding(), getTextVerticalPadding(), getTextHorizontalPadding(), getTextVerticalPadding()); ((ViewGroup.MarginLayoutParams) itemTV.getLayoutParams()).setMargins(getSegmentHorizontalMargin(), getSegmentVerticalMargin(), getSegmentHorizontalMargin(), getSegmentVerticalMargin()); } private void initScreenLocation() { windowLocation = new int[2]; getSectionView().getLocationOnScreen(windowLocation); } @Override public void onSegmentSelected(boolean isSelected, boolean isReselected) { super.onSegmentSelected(isSelected, isReselected); setSectionDecorationSelected(isSelected, isReselected); } private Drawable getSelectedBackground() { return getBackground(getStrokeWidth(), getSelectedStrokeColor(), getSelectBackgroundColor(), radius); } private Drawable getUnSelectedBackground() { return getBackground(getStrokeWidth(), getUnSelectedStrokeColor(), getUnSelectedBackgroundColor(), radius); } private Drawable getFocusedBackground() { return getBackground(getStrokeWidth(), isSelected() ? getSelectedStrokeColor() : getUnSelectedStrokeColor(), getFocusedBackgroundColor(), radius); } private void setSectionDecorationSelected(boolean isSelected, boolean isReselected) { if (isReselected) return; if (hasBackground()) { animateNewBackground(isSelected); } else { setBackground(isSelected ? getSelectedBackground() : getUnSelectedBackground()); } itemTV.setTextColor(isSelected ? getSelectedTextColor() : getUnSelectedTextColor()); } private void animateNewBackground(boolean isSelected) { if (va != null) { va.end(); va.removeUpdateListener(bgAnimListener); } // animate int startColor = isSelected ? getFocusedBackgroundColor() : getSelectBackgroundColor(); int endColor = isSelected ? getSelectBackgroundColor() : getUnSelectedBackgroundColor(); va = createBackgroundAnimation(startColor, endColor); va.addUpdateListener(bgAnimListener); va.setDuration(getSelectionAnimationDuration()); va.start(); } private void setBackground(Drawable drawable) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { itemTV.setBackground(drawable); } else { //noinspection deprecation itemTV.setBackgroundDrawable(drawable); } } private boolean hasBackground() { return itemTV.getBackground() != null; } } ================================================ FILE: segmentedcontrolmodule/src/main/java/segmented_control/widget/custom/android/com/segmentedcontrol/item_row/SegmentRowAdapter.java ================================================ package segmented_control.widget.custom.android.com.segmentedcontrol.item_row; import android.support.annotation.NonNull; import android.view.LayoutInflater; import android.view.ViewGroup; import section_layout.widget.custom.android.com.sectionlayout.SectionLayout; import section_layout.widget.custom.android.com.sectionlayout.distributive_section_layout.DistributiveSectionLayout; import segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentAdapter; import segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentData; /** * Created by Robert Apikyan on 9/7/2017. */ public class SegmentRowAdapter extends SectionLayout.Adapter>> { private final SegmentAdapter segmentAdapter; public SegmentRowAdapter(SegmentAdapter segmentAdapter) { this.segmentAdapter = segmentAdapter; } @NonNull @Override protected SegmentRowViewHolder> onCreateViewHolder(@NonNull LayoutInflater layoutInflater, ViewGroup viewGroup, int i) { return new SegmentRowViewHolder<>(new DistributiveSectionLayout>(layoutInflater.getContext()), segmentAdapter); } } ================================================ FILE: segmentedcontrolmodule/src/main/java/segmented_control/widget/custom/android/com/segmentedcontrol/item_row/SegmentRowViewHolder.java ================================================ package segmented_control.widget.custom.android.com.segmentedcontrol.item_row; import android.support.annotation.NonNull; import android.view.View; import android.widget.LinearLayout; import section_layout.widget.custom.android.com.sectionlayout.SectionLayout; import section_layout.widget.custom.android.com.sectionlayout.distributive_section_layout.DistributiveSectionLayout; import segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentAdapter; import segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentData; /** * Created by Robert Apikyan on 9/7/2017. */ public class SegmentRowViewHolder extends SectionLayout.ViewHolder { private final DistributiveSectionLayout> distributiveSectionLayout; SegmentRowViewHolder(@NonNull View sectionView, SegmentAdapter segmentAdapter) { super(sectionView); //noinspection unchecked distributiveSectionLayout = (DistributiveSectionLayout>) sectionView; distributiveSectionLayout.setOrientation(LinearLayout.HORIZONTAL); distributiveSectionLayout.withAdapter(segmentAdapter); } @Override protected void onBind(Boolean willDistributeEvenly) { distributiveSectionLayout.distributeEvenly(willDistributeEvenly); } public DistributiveSectionLayout> getDistributiveSectionLayout() { return distributiveSectionLayout; } } ================================================ FILE: segmentedcontrolmodule/src/main/java/segmented_control/widget/custom/android/com/segmentedcontrol/item_row_column/SegmentAdapter.java ================================================ package segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column; import section_layout.widget.custom.android.com.sectionlayout.distributive_section_layout.DistributiveSectionLayout; /** * Created by Robert Apikyan on 9/7/2017. */ public abstract class SegmentAdapter> extends DistributiveSectionLayout.Adapter, VH> { } ================================================ FILE: segmentedcontrolmodule/src/main/java/segmented_control/widget/custom/android/com/segmentedcontrol/item_row_column/SegmentBackgroundType.java ================================================ package segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column; import android.support.annotation.IntDef; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import static segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentBackgroundType.BOTTOM_LEFT_BG; import static segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentBackgroundType.BOTTOM_RIGHT_BG; import static segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentBackgroundType.BOTTOM_SINGLE_BG; import static segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentBackgroundType.MIDDLE_BG; import static segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentBackgroundType.SINGLE_BG; import static segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentBackgroundType.TOP_LEFT_BG; import static segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentBackgroundType.TOP_LEFT_SINGLE_BG; import static segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentBackgroundType.TOP_RIGHT_BG; import static segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentBackgroundType.TOP_RIGHT_SINGLE_BG; import static segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentBackgroundType.TOP_SINGLE_BG; /** * Created by Robert Apikyan on 9/12/2017. */ @IntDef(value = {SINGLE_BG, TOP_SINGLE_BG, TOP_LEFT_BG, TOP_LEFT_SINGLE_BG, TOP_RIGHT_SINGLE_BG, TOP_RIGHT_BG, MIDDLE_BG, BOTTOM_SINGLE_BG, BOTTOM_LEFT_BG, BOTTOM_RIGHT_BG}) @Retention(RetentionPolicy.SOURCE) public @interface SegmentBackgroundType { int SINGLE_BG = 0; int TOP_SINGLE_BG = 1; int TOP_LEFT_BG = 2; int TOP_LEFT_SINGLE_BG = 3; int TOP_RIGHT_SINGLE_BG = 4; int TOP_RIGHT_BG = 5; int MIDDLE_BG = 6; int BOTTOM_SINGLE_BG = 7; int BOTTOM_LEFT_BG = 8; int BOTTOM_RIGHT_BG = 9; } ================================================ FILE: segmentedcontrolmodule/src/main/java/segmented_control/widget/custom/android/com/segmentedcontrol/item_row_column/SegmentData.java ================================================ package segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column; import android.graphics.Typeface; import segmented_control.widget.custom.android.com.segmentedcontrol.listeners.OnSegmentClickListener; /** * Created by Robert Apikyan on 9/7/2017. */ public class SegmentData { boolean isSelected; int absolutePosition; private int row; private int column; private D segmentData; private OnSegmentClickListener onSegmentClickListener; private SegmentDecoration segmentDecoration; private int currentSize; private int columnCount; public static SegmentData create(D segmentData, OnSegmentClickListener onSegmentClickListener, int absolutePosition, int row, int column, int currentSize, int columnCount, SegmentDecoration segmentDecoration) { SegmentData sd = new SegmentData<>(); sd.segmentData = segmentData; sd.absolutePosition = absolutePosition; sd.row = row; sd.column = column; sd.currentSize = currentSize; sd.columnCount = columnCount; sd.segmentDecoration = segmentDecoration; sd.onSegmentClickListener = onSegmentClickListener; return sd; } public boolean isSelected() { return isSelected; } public int getAbsolutePosition() { return absolutePosition; } public int getRow() { return row; } public int getColumn() { return column; } public D getSegmentData() { return segmentData; } public OnSegmentClickListener getOnSegmentClickListener() { return onSegmentClickListener; } public int getSelectedStrokeColor() { return segmentDecoration.getSelectedStrokeColor(); } public int getUnSelectedStrokeColor() { return segmentDecoration.getUnSelectedStrokeColor(); } public int getStrokeWidth() { return segmentDecoration.getStrokeWidth(); } public int getSelectBackgroundColor() { return segmentDecoration.getSelectBackgroundColor(); } public int getUnSelectedBackgroundColor() { return segmentDecoration.getUnSelectedBackgroundColor(); } public int getFocusedBackgroundColor(){ return segmentDecoration.getFocusedBackgroundColor(); } public int getSelectionAnimationDuration(){ return segmentDecoration.getSelectionAnimationDuration(); } public int getSelectedTextColor() { return segmentDecoration.getSelectedTextColor(); } public int getUnSelectedTextColor() { return segmentDecoration.getUnSelectedTextColor(); } public int getTextSize() { return segmentDecoration.getTextSize(); } public Typeface getTypeFace(){ return segmentDecoration.getTypeface(); } public int getTextHorizontalPadding() { return segmentDecoration.getTextHorizontalPadding(); } public int getTextVerticalPadding() { return segmentDecoration.getTextVerticalPadding(); } public int getSegmentVerticalMargin() { return segmentDecoration.getSegmentVerticalMargin(); } public int getSegmentHorizontalMargin() { return segmentDecoration.getSegmentHorizontalMargin(); } public int getTopLeftRadius() { return segmentDecoration.getTopLeftRadius(); } public int getTopRightRadius() { return segmentDecoration.getTopRightRadius(); } public int getBottomRightRadius() { return segmentDecoration.getBottomRightRadius(); } public int getBottomLeftRadius() { return segmentDecoration.getBottomLeftRadius(); } public boolean isRadiusForEverySegment() { return segmentDecoration.isRadiusForEverySegment(); } public int getCurrentSize() { return currentSize; } public int getColumnCount() { return columnCount; } } ================================================ FILE: segmentedcontrolmodule/src/main/java/segmented_control/widget/custom/android/com/segmentedcontrol/item_row_column/SegmentDecoration.java ================================================ package segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column; import android.content.Context; import android.graphics.Color; import android.graphics.Typeface; import android.support.annotation.ColorInt; import android.support.v4.content.ContextCompat; /** * Created by Robert Apikyan on 9/11/2017. */ public class SegmentDecoration { public static final int DEFAULT_FOCUSED_BACKGROUND_ALPHA = 36; public static final int DEFAULT_SELECTION_ANIMATION_DURATION = 196; // segment decoration // stroke @ColorInt public int selectedStrokeColor; @ColorInt public int unSelectedStrokeColor; public int strokeWidth; // background @ColorInt public int selectBackgroundColor; @ColorInt public int unSelectedBackgroundColor; // focused segment background public int focusedBackgroundColor; // selection Animation Duration public int selectionAnimationDuration; // text @ColorInt public int selectedTextColor; @ColorInt public int unSelectedTextColor; public int textSize; // text padding public int textHorizontalPadding; public int textVerticalPadding; // segment margins public int segmentVerticalMargin; public int segmentHorizontalMargin; // segment font type public Typeface typeface; // radius public int topLeftRadius; public int topRightRadius; public int bottomRightRadius; public int bottomLeftRadius; public boolean radiusForEverySegment = false; // def. value public static SegmentDecoration createDefault(Context context, int accentColor) { SegmentDecoration sd = new SegmentDecoration(); sd.selectedStrokeColor = accentColor; sd.unSelectedStrokeColor = accentColor; sd.selectBackgroundColor = accentColor; sd.unSelectedBackgroundColor = ContextCompat.getColor(context, android.R.color.transparent); sd.focusedBackgroundColor = Color.argb(DEFAULT_FOCUSED_BACKGROUND_ALPHA, Color.red(accentColor), Color.green(accentColor), Color.blue(accentColor)); sd.selectionAnimationDuration = DEFAULT_SELECTION_ANIMATION_DURATION; sd.selectedTextColor = ContextCompat.getColor(context, android.R.color.white); sd.unSelectedTextColor = accentColor; sd.strokeWidth = 1; sd.typeface = null; return sd; } public int getSelectedStrokeColor() { return selectedStrokeColor; } public int getUnSelectedStrokeColor() { return unSelectedStrokeColor; } public int getStrokeWidth() { return strokeWidth; } public int getSelectBackgroundColor() { return selectBackgroundColor; } public int getUnSelectedBackgroundColor() { return unSelectedBackgroundColor; } public int getFocusedBackgroundColor() { return focusedBackgroundColor; } public int getSelectionAnimationDuration() { return selectionAnimationDuration; } public int getSelectedTextColor() { return selectedTextColor; } public int getUnSelectedTextColor() { return unSelectedTextColor; } public int getTextSize() { return textSize; } public int getTextHorizontalPadding() { return textHorizontalPadding; } public int getTextVerticalPadding() { return textVerticalPadding; } public int getSegmentVerticalMargin() { return segmentVerticalMargin; } public int getSegmentHorizontalMargin() { return segmentHorizontalMargin; } public int getTopLeftRadius() { return topLeftRadius; } public int getTopRightRadius() { return topRightRadius; } public int getBottomRightRadius() { return bottomRightRadius; } public int getBottomLeftRadius() { return bottomLeftRadius; } public boolean isRadiusForEverySegment() { return radiusForEverySegment; } public Typeface getTypeface() { return typeface; } ; } ================================================ FILE: segmentedcontrolmodule/src/main/java/segmented_control/widget/custom/android/com/segmentedcontrol/item_row_column/SegmentViewHolder.java ================================================ package segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column; import android.graphics.Typeface; import android.support.annotation.NonNull; import android.view.View; import section_layout.widget.custom.android.com.sectionlayout.distributive_section_layout.DistributiveSectionLayout; /** * Created by Robert Apikyan on 9/7/2017. */ public abstract class SegmentViewHolder extends DistributiveSectionLayout.ViewHolder> { private SegmentData segmentData; private final View.OnClickListener onSectionViewClickListener = new View.OnClickListener() { @Override public void onClick(View v) { if (segmentData != null) segmentData.getOnSegmentClickListener().onSegmentClick(SegmentViewHolder.this); } }; public SegmentViewHolder(@NonNull View sectionView) { super(sectionView); } @Override protected final void onBind(SegmentData segmentData) { this.segmentData = segmentData; getSectionView().setOnClickListener(onSectionViewClickListener); onSegmentBind(segmentData.getSegmentData()); } public final void setSelected(boolean isSelected) { if (segmentData.isSelected() && isSelected) { segmentData.isSelected = true; onSegmentSelected(true, true); } else if (isSelected) { segmentData.isSelected = true; onSegmentSelected(true, false); } else { segmentData.isSelected = false; onSegmentSelected(false, false); } } /** * Override this method in order to define, performed action, selected, unselected, reselected * * @param isSelected, represent selected state * @param isReselected, represent reselected state */ public void onSegmentSelected(boolean isSelected, boolean isReselected) { } public int getAbsolutePosition() { return segmentData.absolutePosition; } public boolean isSelected() { return segmentData.isSelected; } public int getRow() { return segmentData.getRow(); } public int getColumn() { return segmentData.getColumn(); } public D getSegmentData() { return segmentData.getSegmentData(); } public int getSelectedStrokeColor() { return segmentData.getSelectedStrokeColor(); } public int getUnSelectedStrokeColor() { return segmentData.getUnSelectedStrokeColor(); } public int getStrokeWidth() { return segmentData.getStrokeWidth(); } public int getSelectBackgroundColor() { return segmentData.getSelectBackgroundColor(); } public int getUnSelectedBackgroundColor() { return segmentData.getUnSelectedBackgroundColor(); } public int getFocusedBackgroundColor(){ return segmentData.getFocusedBackgroundColor(); } public int getSelectionAnimationDuration(){ return segmentData.getSelectionAnimationDuration(); } public int getSelectedTextColor() { return segmentData.getSelectedTextColor(); } public int getUnSelectedTextColor() { return segmentData.getUnSelectedTextColor(); } public int getTextSize() { return segmentData.getTextSize(); } public Typeface getTypeFace(){return segmentData.getTypeFace();} public int getCurrentSize() { return segmentData.getCurrentSize(); } public int getColumnCount() { return segmentData.getColumnCount(); } public int getTextHorizontalPadding() { return segmentData.getTextHorizontalPadding(); } public int getTextVerticalPadding() { return segmentData.getTextVerticalPadding(); } public int getSegmentVerticalMargin() { return segmentData.getSegmentVerticalMargin(); } public int getSegmentHorizontalMargin() { return segmentData.getSegmentHorizontalMargin(); } public int getTopLeftRadius() { return segmentData.getTopLeftRadius(); } public int getTopRightRadius() { return segmentData.getTopRightRadius(); } public int getBottomRightRadius() { return segmentData.getBottomRightRadius(); } public int getBottomLeftRadius() { return segmentData.getBottomLeftRadius(); } public boolean isRadiusForEverySegment() { return segmentData.isRadiusForEverySegment(); } protected abstract void onSegmentBind(D segmentData); } ================================================ FILE: segmentedcontrolmodule/src/main/java/segmented_control/widget/custom/android/com/segmentedcontrol/listeners/OnSegmentClickListener.java ================================================ package segmented_control.widget.custom.android.com.segmentedcontrol.listeners; import segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentViewHolder; /** * Created by Robert Apikyan on 9/7/2017. */ public interface OnSegmentClickListener { /** * @param segmentViewHolder, the clicked segment view holder instance */ void onSegmentClick(SegmentViewHolder segmentViewHolder); } ================================================ FILE: segmentedcontrolmodule/src/main/java/segmented_control/widget/custom/android/com/segmentedcontrol/listeners/OnSegmentSelectRequestListener.java ================================================ package segmented_control.widget.custom.android.com.segmentedcontrol.listeners; import segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentViewHolder; /** * Created by Robert Apikyan on 9/12/2017. */ public interface OnSegmentSelectRequestListener { /** * The event will be triggered before perform segment selection,and after segment click event * * @param segmentViewHolder, clicked segment view holder * @return false segment selection will be ignored, true segment selection will be performed */ boolean onSegmentSelectRequest(SegmentViewHolder segmentViewHolder); } ================================================ FILE: segmentedcontrolmodule/src/main/java/segmented_control/widget/custom/android/com/segmentedcontrol/listeners/OnSegmentSelectedListener.java ================================================ package segmented_control.widget.custom.android.com.segmentedcontrol.listeners; import segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentViewHolder; /** * Created by Robert Apikyan on 9/7/2017. */ public interface OnSegmentSelectedListener { /** * The Event will be triggered: if the segment is selected, reselected and unSelected * 1. Segment is selected for first time: isSelected = true ,isReselected = false * 2. Segment is reselected: isSelected = true ,isReselected = true * 3. Segment is unSelected: isSelected = false ,isReselected = false * * @param segmentViewHolder event related segmentViewHolder * @param isSelected, true segment is selected * @param isReselected, true segment is reselected */ void onSegmentSelected(SegmentViewHolder segmentViewHolder, boolean isSelected, boolean isReselected); } ================================================ FILE: segmentedcontrolmodule/src/main/java/segmented_control/widget/custom/android/com/segmentedcontrol/utils/ArgbEvaluator.java ================================================ package segmented_control.widget.custom.android.com.segmentedcontrol.utils; import android.animation.TypeEvaluator; import android.animation.ValueAnimator; public class ArgbEvaluator implements TypeEvaluator { private static final android.animation.ArgbEvaluator sInstance = new android.animation.ArgbEvaluator(); /** * Returns an instance of ArgbEvaluator that may be used in * {@link ValueAnimator#setEvaluator(TypeEvaluator)}. The same instance may * be used in multiple Animators because it holds no state. * @return An instance of ArgbEvalutor. * * @hide */ public static android.animation.ArgbEvaluator getInstance() { return sInstance; } /** * This function returns the calculated in-between value for a color * given integers that represent the start and end values in the four * bytes of the 32-bit int. Each channel is separately linearly interpolated * and the resulting calculated values are recombined into the return value. * * @param fraction The fraction from the starting to the ending values * @param startValue A 32-bit int value representing colors in the * separate bytes of the parameter * @param endValue A 32-bit int value representing colors in the * separate bytes of the parameter * @return A value that is calculated to be the linearly interpolated * result, derived by separating the start and end values into separate * color channels and interpolating each one separately, recombining the * resulting values in the same way. */ public Object evaluate(float fraction, Object startValue, Object endValue) { int startInt = (Integer) startValue; float startA = ((startInt >> 24) & 0xff) / 255.0f; float startR = ((startInt >> 16) & 0xff) / 255.0f; float startG = ((startInt >> 8) & 0xff) / 255.0f; float startB = ( startInt & 0xff) / 255.0f; int endInt = (Integer) endValue; float endA = ((endInt >> 24) & 0xff) / 255.0f; float endR = ((endInt >> 16) & 0xff) / 255.0f; float endG = ((endInt >> 8) & 0xff) / 255.0f; float endB = ( endInt & 0xff) / 255.0f; // convert from sRGB to linear startR = (float) Math.pow(startR, 2.2); startG = (float) Math.pow(startG, 2.2); startB = (float) Math.pow(startB, 2.2); endR = (float) Math.pow(endR, 2.2); endG = (float) Math.pow(endG, 2.2); endB = (float) Math.pow(endB, 2.2); // compute the interpolated color in linear space float a = startA + fraction * (endA - startA); float r = startR + fraction * (endR - startR); float g = startG + fraction * (endG - startG); float b = startB + fraction * (endB - startB); // convert back to sRGB in the [0..255] range a = a * 255.0f; r = (float) Math.pow(r, 1.0 / 2.2) * 255.0f; g = (float) Math.pow(g, 1.0 / 2.2) * 255.0f; b = (float) Math.pow(b, 1.0 / 2.2) * 255.0f; return Math.round(a) << 24 | Math.round(r) << 16 | Math.round(g) << 8 | Math.round(b); } } ================================================ FILE: segmentedcontrolmodule/src/main/java/segmented_control/widget/custom/android/com/segmentedcontrol/utils/Utils.java ================================================ package segmented_control.widget.custom.android.com.segmentedcontrol.utils; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.support.annotation.IntRange; import android.view.View; import segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentBackgroundType; import segmented_control.widget.custom.android.com.segmentedcontrol.item_row_column.SegmentViewHolder; /** * Created by Robert Apikyan on 9/8/2017. */ public class Utils { public static T lazy(T nullable, T nonNull) { if (nullable == null) { nullable = nonNull; } return nullable; } /** * Utility method, use to define segment background type * * @param absolutePosition, Segment absolute position from {@link SegmentViewHolder#getAbsolutePosition()} * @param columnCount, from {@link SegmentViewHolder#getColumnCount()} * @param size, from {@link SegmentViewHolder#getCurrentSize()} * @return {@link SegmentBackgroundType} */ @SegmentBackgroundType public static int defineSegmentBackground(@IntRange(from = 0) int absolutePosition, @IntRange(from = 1) int columnCount, @IntRange(from = 1) int size) { // if only one item if (size == 1) { return SegmentBackgroundType.SINGLE_BG; } // if one column if (columnCount == 1) { // for first if (absolutePosition == 0) { return SegmentBackgroundType.TOP_SINGLE_BG; } // for last if (absolutePosition == size - 1) { return SegmentBackgroundType.BOTTOM_SINGLE_BG; } } // if not one column, but one row if (size <= columnCount) { if (absolutePosition == 0) { return SegmentBackgroundType.TOP_LEFT_SINGLE_BG; } if (absolutePosition == size - 1) { return SegmentBackgroundType.TOP_RIGHT_SINGLE_BG; } } // if not one column and multi row if (absolutePosition == 0) { return SegmentBackgroundType.TOP_LEFT_BG; } if (absolutePosition == columnCount - 1) { return SegmentBackgroundType.TOP_RIGHT_BG; } int notCompletedRowItemsCount = size % columnCount; int completeRowsItemsCount = size - notCompletedRowItemsCount; if (notCompletedRowItemsCount == 1 && absolutePosition == completeRowsItemsCount) { return SegmentBackgroundType.BOTTOM_SINGLE_BG; } if (notCompletedRowItemsCount == 0) { if (absolutePosition == size - columnCount) { return SegmentBackgroundType.BOTTOM_LEFT_BG; } if (absolutePosition == size - 1) { return SegmentBackgroundType.BOTTOM_RIGHT_BG; } } else if (notCompletedRowItemsCount > 0) { if (absolutePosition == size - notCompletedRowItemsCount) { return SegmentBackgroundType.BOTTOM_LEFT_BG; } if (absolutePosition == size - 1) { return SegmentBackgroundType.BOTTOM_RIGHT_BG; } } return SegmentBackgroundType.MIDDLE_BG; } /** * Use to define segment corner radius * * @param absolutePosition, Segment absolute position from {@link SegmentViewHolder#getAbsolutePosition()} * @param columnCount, from {@link SegmentViewHolder#getColumnCount()} * @param size, from {@link SegmentViewHolder#getCurrentSize()} * @param topLeftRadius, from {@link SegmentViewHolder#getTopLeftRadius()} * @param topRightRadius, from {@link SegmentViewHolder#getTopRightRadius()} ()} * @param bottomRightRadius, from {@link SegmentViewHolder#getBottomRightRadius()} * @param bottomLeftRadius, from {@link SegmentViewHolder#getBottomLeftRadius()} * @return, float[] corners radius, */ public static float[] defineRadiusForPosition(@IntRange(from = 0) int absolutePosition, @IntRange(from = 1) int columnCount, @IntRange(from = 1) int size, int topLeftRadius, int topRightRadius, int bottomRightRadius, int bottomLeftRadius) { @SegmentBackgroundType int bgType = defineSegmentBackground(absolutePosition, columnCount, size); switch (bgType) { case SegmentBackgroundType.BOTTOM_LEFT_BG: return createRadius(0, 0, 0, bottomLeftRadius); case SegmentBackgroundType.BOTTOM_RIGHT_BG: return createRadius(0, 0, bottomRightRadius, 0); case SegmentBackgroundType.BOTTOM_SINGLE_BG: return createRadius(0, 0, bottomRightRadius, bottomLeftRadius); case SegmentBackgroundType.MIDDLE_BG: return createRadius(0, 0, 0, 0); case SegmentBackgroundType.SINGLE_BG: return createRadius(topLeftRadius, topRightRadius, bottomRightRadius, bottomLeftRadius); case SegmentBackgroundType.TOP_LEFT_BG: return createRadius(topLeftRadius, 0, 0, 0); case SegmentBackgroundType.TOP_LEFT_SINGLE_BG: return createRadius(topLeftRadius, 0, 0, bottomLeftRadius); case SegmentBackgroundType.TOP_RIGHT_BG: return createRadius(0, topRightRadius, 0, 0); case SegmentBackgroundType.TOP_RIGHT_SINGLE_BG: return createRadius(0, topRightRadius, bottomRightRadius, 0); case SegmentBackgroundType.TOP_SINGLE_BG: return createRadius(topLeftRadius, topRightRadius, 0, 0); default: return createRadius(0, 0, 0, 0); } } public static float[] createRadius(float topLeft, float topRight, float bottomRight, float bottomLeft) { return new float[]{topLeft, topLeft, topRight, topRight, bottomRight, bottomRight, bottomLeft, bottomLeft}; } /** * @param strokeWidth, stroke width * @param strokeColor, stroke color * @param argb, background color * @param radii, use {@link #defineRadiusForPosition(int, int, int, int, int, int, int)} method to define radii * @return background drawable */ public static Drawable getBackground(int strokeWidth, int strokeColor, int argb, float[] radii) { GradientDrawable drawable = new GradientDrawable(); drawable.setShape(GradientDrawable.RECTANGLE); drawable.setStroke(strokeWidth, strokeColor); drawable.setCornerRadii(radii); drawable.setColor(argb); return drawable; } public static ValueAnimator createBackgroundAnimation(int argbStart, int argbEnd) { return ValueAnimator.ofObject(ArgbEvaluator.getInstance(), argbStart, argbEnd); } public static boolean isInBounds(float touchX, float touchY, float viewX, float viewY, float viewW, float viewH) { return touchX >= viewX && touchX <= viewX + viewW && // in x bounds touchY >= viewY && touchY <= viewY + viewH; } } ================================================ FILE: segmentedcontrolmodule/src/main/res/layout/item_segment_impl.xml ================================================ ================================================ FILE: segmentedcontrolmodule/src/main/res/values/attr.xml ================================================ ================================================ FILE: segmentedcontrolmodule/src/main/res/values/colors.xml ================================================ #3F51B5 #303F9F #FF4081 ================================================ FILE: segmentedcontrolmodule/src/main/res/values/strings.xml ================================================ SegmentedControl ================================================ FILE: settings.gradle ================================================ include ':app', ':segmentedcontrolmodule'