├── .gitignore ├── .idea ├── .name ├── codeStyleSettings.xml ├── compiler.xml ├── copyright │ └── profiles_settings.xml ├── encodings.xml ├── findbugs-idea.xml ├── gradle.xml ├── inspectionProfiles │ ├── Project_Default.xml │ └── profiles_settings.xml ├── misc.xml ├── modules.xml ├── runConfigurations.xml └── vcs.xml ├── LICENSE ├── README.md ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── imageseletor ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── io │ │ └── github │ │ └── lijunguan │ │ └── imgselector │ │ └── ApplicationTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── io │ │ │ └── github │ │ │ └── lijunguan │ │ │ └── imgselector │ │ │ ├── AlbumConfig.java │ │ │ ├── ImageSelector.java │ │ │ ├── album │ │ │ ├── AlbumActivity.java │ │ │ ├── AlbumContract.java │ │ │ ├── AlbumFragment.java │ │ │ ├── AlbumPresenter.java │ │ │ ├── adapter │ │ │ │ ├── FolderListAdapter.java │ │ │ │ └── ImageGridAdapter.java │ │ │ ├── previewimage │ │ │ │ ├── ImageContract.java │ │ │ │ ├── ImageDetailFragment.java │ │ │ │ └── ImageDetailPresenter.java │ │ │ └── widget │ │ │ │ ├── GridDividerDecorator.java │ │ │ │ └── HackyViewPager.java │ │ │ ├── base │ │ │ ├── BaseActivity.java │ │ │ ├── BaseFragment.java │ │ │ ├── BasePresenter.java │ │ │ └── BaseView.java │ │ │ ├── cropimage │ │ │ ├── CropActivity.java │ │ │ ├── CropFragment.java │ │ │ └── crop │ │ │ │ ├── CropView.java │ │ │ │ ├── CropViewConfig.java │ │ │ │ └── TouchManager.java │ │ │ ├── model │ │ │ ├── AlbumDataSource.java │ │ │ ├── AlbumRepository.java │ │ │ └── entity │ │ │ │ ├── AlbumFolder.java │ │ │ │ └── ImageInfo.java │ │ │ └── utils │ │ │ ├── ActivityUtils.java │ │ │ ├── CommonUtils.java │ │ │ ├── FileUtils.java │ │ │ ├── KLog.java │ │ │ └── StatusBarUtil.java │ └── res │ │ ├── drawable-v21 │ │ ├── ic_add_a_photo_grey_100_36dp.xml │ │ └── ic_photo_library_white_24dp.xml │ │ ├── drawable │ │ ├── action_btn.xml │ │ ├── button_bg.xml │ │ ├── divider_bg.xml │ │ ├── ic_add_a_photo_grey_100_36dp.xml │ │ ├── ic_photo_library_white_24dp.xml │ │ └── placeholder.png │ │ ├── layout │ │ ├── activity_album.xml │ │ ├── activity_crop.xml │ │ ├── crop_view.xml │ │ ├── fragment_album.xml │ │ ├── fragmetn_image_detail.xml │ │ ├── item_album_folder_list.xml │ │ ├── item_camera.xml │ │ ├── item_image_detail.xml │ │ ├── item_image_grid.xml │ │ ├── layout_album_list.xml │ │ ├── layout_appbar.xml │ │ └── layout_no_image.xml │ │ ├── menu │ │ └── menu_album.xml │ │ ├── mipmap-hdpi │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxxhdpi │ │ └── ic_launcher.png │ │ ├── values-v21 │ │ ├── attrs.xml │ │ └── styles.xml │ │ ├── values-w820dp │ │ └── dimens.xml │ │ └── values │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── io │ └── github │ └── lijunguan │ └── imgselector │ └── ExampleUnitTest.java ├── sample ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── io │ │ └── github │ │ └── lijunguan │ │ └── sample │ │ └── ApplicationTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── io │ │ │ └── github │ │ │ └── lijunguan │ │ │ └── sample │ │ │ ├── App.java │ │ │ ├── GridDividerDecorator.java │ │ │ └── MainActivity.java │ └── res │ │ ├── drawable-v21 │ │ └── ic_send_white_24dp.xml │ │ ├── drawable │ │ ├── bg_rounded_rectangle.xml │ │ ├── divider_background.xml │ │ └── ic_send_white_24dp.xml │ │ ├── layout │ │ ├── activity_main.xml │ │ └── content_main.xml │ │ ├── menu │ │ └── menu_main.xml │ │ ├── mipmap-hdpi │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxxhdpi │ │ └── ic_launcher.png │ │ ├── values-v21 │ │ └── styles.xml │ │ ├── values-w820dp │ │ └── dimens.xml │ │ └── values │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── io │ └── github │ └── lijunguan │ └── sample │ └── ExampleUnitTest.java ├── screenshot ├── ScrennShot1.gif ├── ScrennShot2.gif └── sample-imageselector.apk └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | <<<<<<< HEAD 2 | *.iml 3 | .gradle 4 | /local.properties 5 | /.idea/workspace.xml 6 | /.idea/libraries 7 | .DS_Store 8 | /build 9 | /captures 10 | ======= 11 | # Built application files 12 | *.apk 13 | *.ap_ 14 | 15 | # Files for the Dalvik VM 16 | *.dex 17 | 18 | # Java class files 19 | *.class 20 | 21 | # Generated files 22 | bin/ 23 | gen/ 24 | 25 | # Gradle files 26 | .gradle/ 27 | build/ 28 | 29 | # Local configuration file (sdk path, etc) 30 | local.properties 31 | 32 | # Proguard folder generated by Eclipse 33 | proguard/ 34 | 35 | # Log Files 36 | *.log 37 | 38 | # Android Studio Navigation editor temp files 39 | .navigation/ 40 | 41 | # Android Studio captures folder 42 | captures/ 43 | >>>>>>> 97156da623033c1f6d7a8544e7cd788872411058 44 | -------------------------------------------------------------------------------- /.idea/.name: -------------------------------------------------------------------------------- 1 | AlbumSelector -------------------------------------------------------------------------------- /.idea/codeStyleSettings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 227 | 229 | -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /.idea/copyright/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 25 | 26 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 18 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 12 | 13 | 14 | 26 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 53 | 54 | 55 | 56 | 57 | Android API 21 Platform 58 | 59 | 64 | 65 | 66 | 67 | 68 | 69 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## ImageSelector 2 | 3 | 一个采用MVP架构的图片选择器,可以选择头像,多张图片选择,在很多App上都需要使用这样的功能。 4 | 良好的设计,使用起来非常简单,可根据自己实际需求进行配置。 5 | 6 | 我的博客[追求卓越--成功就会在不经意间追上你](https://lijunguan.github.io) 7 | 8 | ## 特色 9 | 10 | - 根据Google官方的MVP架构最佳实践 设计 11 | - 采用RecyclerView + Toolbar + FloatActionButton 状态栏颜色等Material Design 12 | - 可配置,最大选择数量,Grid列数,是否显示相机,Toolbar颜色等 13 | - 支持Android6.0 运行时权限检查 14 | 15 | ## ScreenShot 16 | 17 | [Apk_Demp DownLoad](https://raw.githubusercontent.com/lijunguan/AlbumSelector/master/screenshot/sample-imagselector.apk) 18 | 19 |
20 | 21 | 22 |
23 | 24 | ## Gradle Dependency Or Maven 25 | 26 | 支持`API >= 11`。 27 | 28 | ```groovy 29 | dependencies { 30 | compile "com.lijunguan:imageseletor:1.0.2" 31 | } 32 | 33 | ``` 34 | 35 | ```groovy 36 | 37 | com.lijunguan 38 | imageseletor 39 | 1.0.2 40 | pom 41 | 42 | ``` 43 | 44 | ## 使用 45 | 46 | ### 使用默认配置 47 | 48 | ```java 49 | public void selectButtonClick(){ 50 | ImageSelector.getInstance() 51 | .startSelect(MainActivity.this); 52 | } 53 | @Override 54 | protected void onActivityResult(int requestCode, int resultCode, Intent data) { 55 | super.onActivityResult(requestCode, resultCode, data); 56 | if (requestCode == ImageSelector.REQUEST_SELECT_IMAGE 57 | && resultCode == RESULT_OK) { 58 | ArrayList imagesPath = data.getStringArrayListExtra(ImageSelector.SELECTED_RESULT); 59 | if(imagesPath != null){ 60 | //TODO do something... 61 | } 62 | } 63 | } 64 | ``` 65 | 66 | ### 配置 67 | 68 | ```java 69 | ImageSelector.getInstance() 70 | .setSelectModel(ImageSelector.MULTI_MODE) 71 | .setMaxCount(6) 72 | .setGridColumns(3) 73 | .setShowCamera(true) 74 | .setToolbarColor(getResources().getColor(R.color.colorPrimary)) 75 | .startSelect(this); 76 | ``` 77 | 78 | #### 配置简介 79 | 80 | - 最大可选数量 81 | 默认:9张 通过setMaxCount(int count)配置 82 | - 图片展示列数 83 | 默认:3列 通过setGridColumns(int columns)配置 84 | - 显示相机Item 85 | 默认:true setShowCamera(boolean shown)配置 86 | - 图片选择模式 87 | 默认:多选模式 可选AvatorModel(头像选择模式) 同 SingleModel(单选模式已废弃) 通过setSelectModel(ImageSelector.AVATOR_MODE)配置 88 | - Toolbar和状态栏颜色 89 | 默认: 蓝色#3F51B5 状态栏颜色需API>19 , 4.4 渐变色,5.0以上为纯色填充 90 | 91 | 92 | ## License 93 | 94 | Copyright 2016 lijunguan 95 | 96 | Licensed under the Apache License, Version 2.0 (the "License"); 97 | you may not use this file except in compliance with the License. 98 | You may obtain a copy of the License at 99 | http://www.apache.org/licenses/LICENSE-2.0 100 | Unless required by applicable law or agreed to in writing, software 101 | distributed under the License is distributed on an "AS IS" BASIS, 102 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 103 | See the License for the specific language governing permissions and 104 | limitations under the License.> 105 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | apply plugin: 'com.jfrog.bintray' 3 | 4 | buildscript { 5 | repositories { 6 | jcenter() 7 | } 8 | dependencies { 9 | classpath 'com.android.tools.build:gradle:2.1.0' 10 | classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3' 11 | classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.6' 12 | // NOTE: Do not place your application dependencies here; they belong 13 | // in the individual module build.gradle files 14 | } 15 | } 16 | 17 | allprojects { 18 | repositories { 19 | jcenter() 20 | maven { url "https://jitpack.io" } 21 | } 22 | } 23 | ext { 24 | configuration = [ 25 | packageName : "io.lijunguan.github.sample", 26 | buildToolsVersion : "23.0.3", 27 | compileVersion : 23, 28 | minSDK : 11, 29 | targetSDK : 23, 30 | version_code : 1, 31 | version_name : "0.01" 32 | ] 33 | libs = [ 34 | supportVersion : "23.2.1", 35 | glide : "3.7.0", 36 | butterknife : "7.0.1" 37 | ] 38 | } 39 | 40 | task clean(type: Delete) { 41 | delete rootProject.buildDir 42 | } 43 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Raynor999/AlbumSelector/e6126a7da077510615f0a2200daa0e94767484c8/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Dec 28 10:00:20 PST 2015 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip 7 | 8 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /imageseletor/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /imageseletor/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'com.github.dcendents.android-maven' 3 | 4 | 5 | def cfg = rootProject.ext.configuration 6 | 7 | android { 8 | 9 | compileSdkVersion cfg.compileVersion 10 | buildToolsVersion cfg.buildToolsVersion 11 | 12 | defaultConfig { 13 | minSdkVersion cfg.minSDK 14 | targetSdkVersion 23 15 | versionCode cfg.version_code 16 | versionName cfg.version_name 17 | } 18 | 19 | buildTypes { 20 | debug { 21 | // 显示Log 22 | buildConfigField "boolean", "LOG_DEBUG", "true" 23 | versionNameSuffix "-debug" 24 | minifyEnabled false 25 | zipAlignEnabled false 26 | shrinkResources false 27 | } 28 | 29 | release { 30 | // 不显示Log 31 | buildConfigField "boolean", "LOG_DEBUG", "false" 32 | 33 | minifyEnabled false 34 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 35 | } 36 | } 37 | packagingOptions { 38 | exclude 'META-INF/services/javax.annotation.processing.Processor' 39 | } 40 | 41 | compileOptions { 42 | sourceCompatibility JavaVersion.VERSION_1_7 43 | targetCompatibility JavaVersion.VERSION_1_7 44 | } 45 | } 46 | 47 | // 注释冲突,annotation.processing.Processor 冲突 48 | 49 | 50 | dependencies { 51 | def libs = rootProject.ext.libs // 库 52 | compile fileTree(dir: 'libs', include: ['*.jar']) 53 | testCompile 'junit:junit:4.12' 54 | compile "com.android.support:appcompat-v7:${libs.supportVersion}" 55 | compile "com.android.support:recyclerview-v7:${libs.supportVersion}" 56 | compile "com.android.support:support-v4:${libs.supportVersion}" 57 | compile "com.android.support:design:${libs.supportVersion}" 58 | compile "com.android.support:percent:${libs.supportVersion}" 59 | compile "com.github.bumptech.glide:glide:${libs.glide}" 60 | compile 'konifar:fab-transformation:1.0.0' 61 | compile 'com.github.chrisbanes:PhotoView:1.2.6' 62 | } 63 | 64 | 65 | 66 | 67 | def siteUrl = 'https://github.com/lijunguan/AlbumSelector' // project homepage 68 | def gitUrl = 'https://github.com/lijunguan/AlbumSelector.git' // project git 69 | 70 | version = "1.0.2" 71 | 72 | group = "com.lijunguan" 73 | 74 | // 75 | Properties properties = new Properties() 76 | properties.load(project.rootProject.file('local.properties').newDataInputStream()) 77 | 78 | bintray { 79 | user = properties.getProperty("bintrayUser") 80 | key = properties.getProperty("bintrayApikey") 81 | 82 | // user = project.hasProperty('bintrayUser') ? project.property('bintrayUser') : System.getenv('BINTRAY_USER') 83 | // key = project.hasProperty('bintrayApiKey') ? project.property('bintrayApiKey') : System.getenv('BINTRAY_API_KEY') 84 | 85 | dryRun = false 86 | publish = true 87 | configurations = ['archives'] 88 | pkg { 89 | repo = "maven" 90 | name = "image-selector" // project name in jcenter 91 | desc = "a image selector module for android " 92 | websiteUrl = siteUrl 93 | vcsUrl = gitUrl 94 | licenses = ["Apache-2.0"] 95 | labels = ['aar', 'android'] 96 | publish = true 97 | } 98 | } 99 | 100 | // 根节点添加 101 | install { 102 | repositories.mavenInstaller { 103 | // This generates POM.xml with proper parameters 104 | pom { 105 | project { 106 | packaging 'aar' 107 | name 'Image Selector For Android' 108 | url siteUrl 109 | licenses { 110 | license { 111 | name 'The Apache Software License, Version 2.0' 112 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt' 113 | } 114 | } 115 | developers { 116 | developer { 117 | id 'lijunguan' 118 | name 'io.github.lijunguan' 119 | email '731212914@qq.com' 120 | } 121 | } 122 | scm { 123 | connection gitUrl 124 | developerConnection gitUrl 125 | url siteUrl 126 | } 127 | } 128 | } 129 | } 130 | } 131 | 132 | 133 | 134 | task sourcesJar(type: Jar) { 135 | from android.sourceSets.main.java.srcDirs 136 | classifier = 'sources' 137 | } 138 | task javadoc(type: Javadoc) { 139 | source = android.sourceSets.main.java.srcDirs 140 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) 141 | } 142 | task javadocJar(type: Jar, dependsOn: javadoc) { 143 | classifier = 'javadoc' 144 | from javadoc.destinationDir 145 | } 146 | artifacts { 147 | archives javadocJar 148 | archives sourcesJar 149 | } 150 | 151 | javadoc { //jav doc采用utf-8编码否则会报“GBK的不可映射字符”错误 152 | options{ 153 | encoding "UTF-8" 154 | charSet 'UTF-8' 155 | } 156 | } 157 | 158 | tasks.withType(JavaCompile) { options.encoding = "UTF-8" } -------------------------------------------------------------------------------- /imageseletor/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in F:\Android_SDK/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /imageseletor/src/androidTest/java/io/github/lijunguan/imgselector/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package io.github.lijunguan.imgselector; 2 | 3 | import android.app.Application; 4 | import android.test.ApplicationTestCase; 5 | 6 | /** 7 | * Testing Fundamentals 8 | */ 9 | public class ApplicationTest extends ApplicationTestCase { 10 | public ApplicationTest() { 11 | super(Application.class); 12 | } 13 | } -------------------------------------------------------------------------------- /imageseletor/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 11 | 17 | 18 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /imageseletor/src/main/java/io/github/lijunguan/imgselector/AlbumConfig.java: -------------------------------------------------------------------------------- 1 | package io.github.lijunguan.imgselector; 2 | 3 | import android.os.Parcel; 4 | import android.os.Parcelable; 5 | import android.support.annotation.ColorInt; 6 | 7 | /** 8 | * Created by lijunguan on 2016/4/21. 9 | * emial: lijunguan199210@gmail.com 10 | * blog: https://lijunguan.github.io 11 | * 12 | * 图片选择器配置 13 | */ 14 | public class AlbumConfig implements Parcelable { 15 | 16 | public static final int DEFAULT_MAX_COUNT = 9; 17 | /** 18 | * 选择模式, SINGLE_MODE = 0 ,MULTI_MODE = 1 19 | */ 20 | private int mSelectModel; 21 | /** 22 | * 图片最大可选择数量 23 | */ 24 | private int mMaxCount; 25 | /** 26 | * 是否显示相机 27 | */ 28 | private boolean mShownCamera; 29 | 30 | /** 31 | * grid 的列数 32 | */ 33 | private int mGridColumns; 34 | 35 | @ColorInt 36 | private int mToolbarColor = -1; 37 | 38 | 39 | public int getSelectModel() { 40 | return mSelectModel; 41 | } 42 | 43 | public void setSelectModel(int mSlecteModel) { 44 | this.mSelectModel = mSlecteModel; 45 | } 46 | 47 | public int getMaxCount() { 48 | return mMaxCount; 49 | } 50 | 51 | public void setMaxCount(int mMaxCount) { 52 | this.mMaxCount = mMaxCount; 53 | } 54 | 55 | public boolean isShownCamera() { 56 | return mShownCamera; 57 | } 58 | 59 | public void setShownCamera(boolean mShownCamera) { 60 | this.mShownCamera = mShownCamera; 61 | } 62 | 63 | public int getGridColumns() { 64 | return mGridColumns; 65 | } 66 | 67 | public void setGridColumns(int mGridColumns) { 68 | this.mGridColumns = mGridColumns; 69 | } 70 | 71 | public int getToolbarColor() { 72 | return mToolbarColor; 73 | } 74 | 75 | public void setToolbarColor(@ColorInt int mToolbarColor) { 76 | this.mToolbarColor = mToolbarColor; 77 | } 78 | 79 | public AlbumConfig() { 80 | mMaxCount = DEFAULT_MAX_COUNT; 81 | mShownCamera = true; 82 | mSelectModel = ImageSelector.MULTI_MODE; 83 | mGridColumns = 3; 84 | } 85 | 86 | 87 | @Override 88 | public int describeContents() { 89 | return 0; 90 | } 91 | 92 | @Override 93 | public void writeToParcel(Parcel dest, int flags) { 94 | dest.writeInt(this.mSelectModel); 95 | dest.writeInt(this.mMaxCount); 96 | dest.writeByte(mShownCamera ? (byte) 1 : (byte) 0); 97 | dest.writeInt(this.mGridColumns); 98 | dest.writeInt(this.mToolbarColor); 99 | } 100 | 101 | protected AlbumConfig(Parcel in) { 102 | this.mSelectModel = in.readInt(); 103 | this.mMaxCount = in.readInt(); 104 | this.mShownCamera = in.readByte() != 0; 105 | this.mGridColumns = in.readInt(); 106 | this.mToolbarColor = in.readInt(); 107 | } 108 | 109 | public static final Creator CREATOR = new Creator() { 110 | @Override 111 | public AlbumConfig createFromParcel(Parcel source) { 112 | return new AlbumConfig(source); 113 | } 114 | 115 | @Override 116 | public AlbumConfig[] newArray(int size) { 117 | return new AlbumConfig[size]; 118 | } 119 | }; 120 | } 121 | 122 | -------------------------------------------------------------------------------- /imageseletor/src/main/java/io/github/lijunguan/imgselector/ImageSelector.java: -------------------------------------------------------------------------------- 1 | package io.github.lijunguan.imgselector; 2 | 3 | import android.app.Activity; 4 | import android.content.Context; 5 | import android.content.Intent; 6 | import android.support.annotation.ColorInt; 7 | import android.support.annotation.NonNull; 8 | 9 | import io.github.lijunguan.imgselector.album.AlbumActivity; 10 | 11 | import static io.github.lijunguan.imgselector.utils.CommonUtils.checkNotNull; 12 | 13 | /** 14 | * Created by lijunguan on 2016/4/21. 15 | * emial: lijunguan199210@gmail.com 16 | * blog: https://lijunguan.github.io 17 | */ 18 | public class ImageSelector { 19 | 20 | 21 | public static final String SELECTED_RESULT = "selected_result"; 22 | 23 | public static final int REQUEST_SELECT_IMAGE = 0x1024; 24 | 25 | public static final int REQUEST_OPEN_CAMERA = 0x2048; 26 | 27 | public static final int REQUEST_CROP_IMAGE = 0x4096; 28 | 29 | public static final String ARG_ALBUM_CONFIG = "albumConfig"; 30 | /** 31 | * 单选模式 32 | */ 33 | @Deprecated 34 | public static final int SINGLE_MODE = 0x0; 35 | 36 | /** 37 | * 头像选择模式 得到裁剪后的正方形图片 38 | */ 39 | public static final int AVATOR_MODE = 0x0; 40 | /** 41 | * 多选模式 42 | */ 43 | public static final int MULTI_MODE = 0x1; 44 | 45 | 46 | 47 | private AlbumConfig mConfig; 48 | 49 | 50 | private static ImageSelector ourInstance = new ImageSelector(); 51 | 52 | public static ImageSelector getInstance() { 53 | return ourInstance; 54 | } 55 | 56 | public AlbumConfig getConfig() { 57 | return mConfig; 58 | } 59 | public void setConfig(AlbumConfig mConfig) { 60 | this.mConfig = mConfig; 61 | } 62 | private ImageSelector() { 63 | mConfig = new AlbumConfig(); 64 | } 65 | 66 | public ImageSelector setMaxCount(int maxCount) { 67 | checkNotNull(maxCount); 68 | mConfig.setMaxCount(maxCount); 69 | return this; 70 | } 71 | 72 | public ImageSelector setSelectModel(int model) { 73 | checkNotNull(model); 74 | mConfig.setSelectModel(model); 75 | return this; 76 | } 77 | 78 | public ImageSelector setShowCamera(boolean shown) { 79 | checkNotNull(shown); 80 | mConfig.setShownCamera(shown); 81 | return this; 82 | } 83 | 84 | public ImageSelector setGridColumns(int columns) { 85 | checkNotNull(columns); 86 | mConfig.setGridColumns(columns); 87 | return this; 88 | } 89 | 90 | public ImageSelector setToolbarColor(@ColorInt int toolbarColor) { 91 | checkNotNull(toolbarColor); 92 | mConfig.setToolbarColor(toolbarColor); 93 | return this; 94 | } 95 | 96 | public void startSelect(@NonNull Activity context) { 97 | Intent intent = new Intent(context, AlbumActivity.class); 98 | intent.putExtra(ImageSelector.ARG_ALBUM_CONFIG, mConfig); 99 | context.startActivityForResult(intent, REQUEST_SELECT_IMAGE); 100 | } 101 | 102 | 103 | public void startSelect(@NonNull Context context) { 104 | if (context instanceof Activity) { 105 | startSelect((Activity) context); 106 | } else { 107 | throw new IllegalArgumentException("Require a Activity.class,but find a Context.class"); 108 | } 109 | } 110 | 111 | } 112 | -------------------------------------------------------------------------------- /imageseletor/src/main/java/io/github/lijunguan/imgselector/album/AlbumActivity.java: -------------------------------------------------------------------------------- 1 | package io.github.lijunguan.imgselector.album; 2 | 3 | import android.content.res.Configuration; 4 | import android.os.Bundle; 5 | import android.support.annotation.Nullable; 6 | import android.view.View; 7 | import android.widget.Button; 8 | 9 | import io.github.lijunguan.imgselector.R; 10 | import io.github.lijunguan.imgselector.album.previewimage.ImageDetailFragment; 11 | import io.github.lijunguan.imgselector.base.BaseActivity; 12 | import io.github.lijunguan.imgselector.model.AlbumRepository; 13 | import io.github.lijunguan.imgselector.utils.ActivityUtils; 14 | import io.github.lijunguan.imgselector.utils.KLog; 15 | 16 | 17 | public class AlbumActivity extends BaseActivity { 18 | 19 | public static final String TAG = AlbumActivity.class.getSimpleName(); 20 | 21 | private AlbumPresenter mAlbumPresenter; 22 | 23 | private Button mSubmitBtn; 24 | 25 | @Override 26 | protected void onCreate(@Nullable Bundle savedInstanceState) { 27 | super.onCreate(savedInstanceState); 28 | setContentView(R.layout.activity_album); 29 | initViews(); 30 | 31 | AlbumFragment albumFragment; 32 | ImageDetailFragment imageDetailFragment; 33 | 34 | if (savedInstanceState != null) { //内存重启时调用 解决 内存重启时可能发生的Fragment重叠异常 35 | imageDetailFragment = 36 | (ImageDetailFragment) getSupportFragmentManager().findFragmentByTag(ImageDetailFragment.TAG); 37 | albumFragment = 38 | (AlbumFragment) getSupportFragmentManager().findFragmentByTag(AlbumFragment.TAG); 39 | 40 | if (imageDetailFragment != null && albumFragment != null) { 41 | getSupportFragmentManager().beginTransaction() 42 | .hide(albumFragment) 43 | .show(imageDetailFragment) 44 | .commit(); 45 | } 46 | } else { 47 | //创建AlbumFragment 48 | 49 | albumFragment = AlbumFragment.newInstance(); 50 | ActivityUtils.addFragmentToActivity( 51 | getSupportFragmentManager(), albumFragment, AlbumFragment.TAG, false); 52 | 53 | } 54 | AlbumRepository albumRepository = AlbumRepository.getInstance(this); 55 | //创建AlbumPresenter 56 | mAlbumPresenter = new AlbumPresenter( 57 | albumRepository, 58 | getSupportLoaderManager(), 59 | albumFragment); 60 | } 61 | 62 | 63 | private void initViews() { 64 | mSubmitBtn = (Button) mToolbar.findViewById(R.id.btn_submit); 65 | mSubmitBtn.setEnabled(false); 66 | mSubmitBtn.setOnClickListener(new View.OnClickListener() { 67 | @Override 68 | public void onClick(View v) { 69 | mAlbumPresenter.returnResult(); 70 | } 71 | }); 72 | } 73 | 74 | 75 | public void setSubmitBtnText(CharSequence text, boolean enabled) { 76 | mSubmitBtn.setText(text); 77 | mSubmitBtn.setEnabled(enabled); 78 | } 79 | 80 | public void setToolbarTitle(CharSequence title) { 81 | mToolbar.setTitle(title); 82 | } 83 | 84 | @Override 85 | public void onBackPressed() { 86 | 87 | AlbumFragment albumFragment = 88 | (AlbumFragment) getSupportFragmentManager().findFragmentByTag(AlbumFragment.TAG); 89 | 90 | if (albumFragment == null) { 91 | super.onBackPressed(); 92 | return; 93 | } 94 | 95 | if (albumFragment.isHidden()) { 96 | getSupportFragmentManager() 97 | .beginTransaction() 98 | .show(albumFragment) 99 | .commit(); 100 | } else if (albumFragment.mFab.getVisibility() != View.VISIBLE) { 101 | albumFragment.hideFolderList(); 102 | return; 103 | } 104 | super.onBackPressed(); 105 | } 106 | 107 | @Override 108 | protected void onDestroy() { 109 | super.onDestroy(); 110 | KLog.d(TAG, "=======onDestroy========"); 111 | mAlbumPresenter.clearCache(); 112 | } 113 | 114 | @Override 115 | public void onConfigurationChanged(Configuration config) { 116 | super.onConfigurationChanged(config); 117 | KLog.d("=========onConfigurationChanged==========="); 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /imageseletor/src/main/java/io/github/lijunguan/imgselector/album/AlbumContract.java: -------------------------------------------------------------------------------- 1 | package io.github.lijunguan.imgselector.album; 2 | 3 | import android.app.Activity; 4 | import android.content.Intent; 5 | import android.support.annotation.NonNull; 6 | import android.support.annotation.Nullable; 7 | 8 | import java.io.File; 9 | import java.util.List; 10 | 11 | import io.github.lijunguan.imgselector.album.previewimage.ImageContract; 12 | import io.github.lijunguan.imgselector.base.BaseView; 13 | import io.github.lijunguan.imgselector.model.entity.AlbumFolder; 14 | import io.github.lijunguan.imgselector.model.entity.ImageInfo; 15 | 16 | /** 17 | * Created by lijunguan on 2016/4/19. 18 | * emial: lijunguan199210@gmail.com 19 | * blog: https://lijunguan.github.io 20 | * 指定 View 和 Presenter之间的关系,统一声明便于查看和管理接口方法 21 | */ 22 | public interface AlbumContract { 23 | 24 | interface View extends BaseView { 25 | 26 | void showEmptyView(@Nullable CharSequence message); 27 | 28 | void showImages(@NonNull List imageInfos); 29 | 30 | void showSystemCamera(); 31 | 32 | void showFolderList(); 33 | 34 | void hideFolderList(); 35 | 36 | void initFolderList(@NonNull List folders); 37 | 38 | void showImageDetailUi(int currentPosition); // 打开ImagedetailFragment 39 | 40 | void showImageCropUi(@NonNull String imagePath);// 启动裁剪图片的Activity 41 | 42 | void showOutOfRange(int position); //提示用户图片选择数量已经达到上限 43 | 44 | void showSelectedCount(int count); 45 | 46 | /** 47 | * 图片选择完成,返回选择数据给等待结果的Activity, 48 | * 根据refreshMedia状态判断是否将相机拍摄或裁剪的图片加入媒体库 49 | * 50 | * @param imagePaths 选择的图片路径集合 51 | * @param refreshMedia 是否刷新系统媒体库 true 将通过相机拍摄的照片加入Media.Store 52 | */ 53 | void selectComplete(List imagePaths, boolean refreshMedia); 54 | 55 | /** 56 | * 同步 ImageDetailFragment 界面Checkbox选中状态 57 | * @param position 58 | */ 59 | void syncCheckboxStatus(int position); 60 | 61 | } 62 | 63 | interface Presenter extends ImageContract.Presenter { 64 | /** 65 | * 切换相册目录,刷新Grid显示 66 | * 67 | * @param folder 选择的相册目录实体 68 | */ 69 | void swtichFloder(@NonNull AlbumFolder folder); 70 | 71 | void previewImage(int position); 72 | 73 | void cropImage(ImageInfo imageInfo); 74 | 75 | /** 76 | * 将用户选择的图片结果返回 77 | */ 78 | void returnResult(); 79 | 80 | void openCamera(); 81 | 82 | /** 83 | * 系统相机Activity 返回结果 * {@link Activity#onActivityResult(int, int, Intent)}. 84 | * 85 | * @param mTmpFile 保存相机拍摄图片的零时文件 86 | */ 87 | void result(int requestCode, int resultCode, Intent data, File mTmpFile); 88 | 89 | void clearCache(); 90 | } 91 | 92 | } 93 | -------------------------------------------------------------------------------- /imageseletor/src/main/java/io/github/lijunguan/imgselector/album/AlbumPresenter.java: -------------------------------------------------------------------------------- 1 | package io.github.lijunguan.imgselector.album; 2 | 3 | import android.app.Activity; 4 | import android.content.Intent; 5 | import android.support.annotation.NonNull; 6 | import android.support.v4.app.LoaderManager; 7 | 8 | import java.io.File; 9 | import java.util.List; 10 | 11 | import io.github.lijunguan.imgselector.ImageSelector; 12 | import io.github.lijunguan.imgselector.cropimage.CropActivity; 13 | import io.github.lijunguan.imgselector.model.AlbumDataSource; 14 | import io.github.lijunguan.imgselector.model.AlbumRepository; 15 | import io.github.lijunguan.imgselector.model.entity.AlbumFolder; 16 | import io.github.lijunguan.imgselector.model.entity.ImageInfo; 17 | 18 | import static io.github.lijunguan.imgselector.utils.CommonUtils.checkNotNull; 19 | 20 | /** 21 | * Created by lijunguan on 2016/4/21. 22 | * emial: lijunguan199210@gmail.com 23 | * blog: https://lijunguan.github.io 24 | */ 25 | public class AlbumPresenter implements AlbumContract.Presenter { 26 | 27 | private AlbumContract.View mAlbumView; 28 | 29 | private AlbumRepository mAlbumRepository; 30 | 31 | private LoaderManager mLoadManager; 32 | 33 | 34 | public AlbumPresenter( 35 | @NonNull AlbumRepository albumRepository, 36 | @NonNull LoaderManager loaderManager, 37 | @NonNull AlbumContract.View albumView) { 38 | mLoadManager = checkNotNull(loaderManager, "loader manager cannot be null"); 39 | mAlbumView = checkNotNull(albumView, "albumView cannot be null"); 40 | mAlbumRepository = checkNotNull(albumRepository, "albumRepository cannot be null"); 41 | //为mAlbumView 设置Presenter 42 | mAlbumView.setPresenter(this); 43 | } 44 | 45 | @Override 46 | public void start() { 47 | loadData(); 48 | } 49 | 50 | private void loadData() { 51 | mAlbumRepository.initImgRepository(mLoadManager, new AlbumDataSource.InitAlbumCallback() { 52 | @Override 53 | public void onInitFinish(List folders) { 54 | List allImages = folders.get(0).getImgInfos(); 55 | mAlbumView.showImages(allImages); 56 | mAlbumView.initFolderList(folders); 57 | } 58 | 59 | @Override 60 | public void onDataNoAvaliable() { 61 | mAlbumView.showEmptyView(null); 62 | } 63 | }); 64 | } 65 | 66 | @Override 67 | public void result(int requestCode, int resultCode, Intent data, File mTmpFile) { 68 | 69 | switch (requestCode) { 70 | case ImageSelector.REQUEST_OPEN_CAMERA: 71 | if (resultCode == Activity.RESULT_OK) { 72 | if (ImageSelector.getInstance().getConfig().getSelectModel() == ImageSelector.AVATOR_MODE) { 73 | mAlbumView.showImageCropUi(mTmpFile.getPath()); 74 | return; 75 | } 76 | mAlbumRepository.addSelect(mTmpFile.getPath()); 77 | mAlbumView.selectComplete(mAlbumRepository.getSelectedResult(), true); 78 | } else if (mTmpFile != null && mTmpFile.exists()) { 79 | //出错时,删除零时文件, 80 | mTmpFile.delete(); 81 | } 82 | break; 83 | case ImageSelector.REQUEST_CROP_IMAGE: 84 | if (resultCode == Activity.RESULT_OK) { 85 | String path = data.getStringExtra(CropActivity.CROP_RESULT); 86 | mAlbumRepository.addSelect(path); 87 | mAlbumView.selectComplete(mAlbumRepository.getSelectedResult(), false); 88 | } 89 | break; 90 | } 91 | 92 | } 93 | 94 | @Override 95 | public void swtichFloder(@NonNull AlbumFolder floder) { 96 | checkNotNull(floder); 97 | mAlbumView.showImages(floder.getImgInfos()); 98 | mAlbumView.hideFolderList(); 99 | } 100 | 101 | 102 | @Override 103 | public void selectImage(@NonNull ImageInfo imageInfo, int maxCount, int position) { 104 | checkNotNull(imageInfo, "ImageInfo cannot be null"); 105 | if (mAlbumRepository.getSelectedResult().size() >= maxCount) { 106 | mAlbumView.showOutOfRange(position); 107 | return; 108 | } 109 | imageInfo.setSelected(true); 110 | mAlbumRepository.addSelect(imageInfo.getPath()); 111 | mAlbumView.showSelectedCount(mAlbumRepository.getSelectedCount()); 112 | } 113 | 114 | @Override 115 | public void unSelectImage(@NonNull ImageInfo imageInfo,int positon) { 116 | checkNotNull(imageInfo, "ImageInfo cannot be null"); 117 | imageInfo.setSelected(false); 118 | mAlbumRepository.removeSelect(imageInfo.getPath()); 119 | mAlbumView.showSelectedCount(mAlbumRepository.getSelectedCount()); 120 | } 121 | 122 | @Override 123 | public void previewImage(int position) { 124 | mAlbumView.showImageDetailUi(position); 125 | } 126 | 127 | @Override 128 | public void cropImage(ImageInfo imageInfo) { 129 | checkNotNull(imageInfo); 130 | mAlbumView.showImageCropUi(imageInfo.getPath()); 131 | } 132 | 133 | @Override 134 | public void returnResult() { 135 | List selectedResult = mAlbumRepository.getSelectedResult(); 136 | mAlbumView.selectComplete(selectedResult, false); 137 | } 138 | 139 | @Override 140 | public void openCamera() { 141 | mAlbumView.showSystemCamera(); 142 | } 143 | 144 | public void clearCache() { 145 | mAlbumRepository.clearCacheAndSelect(); 146 | } 147 | 148 | } 149 | -------------------------------------------------------------------------------- /imageseletor/src/main/java/io/github/lijunguan/imgselector/album/adapter/FolderListAdapter.java: -------------------------------------------------------------------------------- 1 | package io.github.lijunguan.imgselector.album.adapter; 2 | 3 | import android.support.annotation.NonNull; 4 | import android.support.v4.content.ContextCompat; 5 | import android.support.v7.widget.RecyclerView; 6 | import android.view.LayoutInflater; 7 | import android.view.View; 8 | import android.view.ViewGroup; 9 | import android.widget.ImageView; 10 | import android.widget.TextView; 11 | 12 | import com.bumptech.glide.RequestManager; 13 | 14 | import java.util.ArrayList; 15 | import java.util.List; 16 | 17 | import io.github.lijunguan.imgselector.R; 18 | import io.github.lijunguan.imgselector.album.AlbumFragment; 19 | import io.github.lijunguan.imgselector.model.entity.AlbumFolder; 20 | 21 | import static io.github.lijunguan.imgselector.utils.CommonUtils.checkNotNull; 22 | 23 | /** 24 | * Created by lijunguan on 2016/4/13 25 | * email: lijunguan199210@gmail.com 26 | * blog : https://lijunguan.github.io 27 | */ 28 | public class FolderListAdapter extends RecyclerView.Adapter { 29 | 30 | private List mData; 31 | 32 | private int mSelectedIndex = 0; 33 | 34 | private final RequestManager mRequestManager; 35 | 36 | private AlbumFragment.FolderItemListener mListener; 37 | 38 | public FolderListAdapter(RequestManager requestManager, AlbumFragment.FolderItemListener listener) { 39 | mRequestManager = checkNotNull(requestManager); 40 | mListener = listener; 41 | mData = new ArrayList<>(); 42 | } 43 | 44 | 45 | @Override 46 | public FolderListAdapter.FolderViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 47 | View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_album_folder_list, parent, false); 48 | return new FolderViewHolder(view); 49 | } 50 | 51 | @Override 52 | public void onBindViewHolder(final FolderListAdapter.FolderViewHolder holder, int position) { 53 | 54 | final AlbumFolder floder = mData.get(position); 55 | 56 | mRequestManager 57 | .load(floder.getCover().getPath()) 58 | .asBitmap() 59 | .into(holder.mCoverView); 60 | holder.mFolderName.setText(floder.getFloderName()); 61 | holder.mFolderSize.setText(holder.itemView.getContext() 62 | .getString(R.string.folder_size, floder.getImgInfos().size())); 63 | 64 | holder.itemView.setOnClickListener(new View.OnClickListener() { 65 | @Override 66 | public void onClick(View v) { 67 | mListener.onFloderItemClick(floder); 68 | holder.itemView.setBackgroundColor(holder.mSelectedColor); 69 | mSelectedIndex = holder.getAdapterPosition(); 70 | notifyDataSetChanged(); 71 | } 72 | }); 73 | 74 | if (mSelectedIndex == position) { 75 | holder.itemView.setBackgroundColor(holder.mSelectedColor); 76 | } else { 77 | holder.itemView.setBackgroundColor(holder.mNormalColor); 78 | } 79 | } 80 | 81 | @Override 82 | public int getItemCount() { 83 | return mData.size(); 84 | } 85 | 86 | public void setData(@NonNull List data) { 87 | mData = checkNotNull(data); 88 | notifyDataSetChanged(); 89 | } 90 | 91 | static class FolderViewHolder extends RecyclerView.ViewHolder { 92 | ImageView mCoverView; 93 | TextView mFolderName; 94 | TextView mFolderSize; 95 | int mNormalColor; 96 | int mSelectedColor; 97 | 98 | public FolderViewHolder(View itemView) { 99 | super(itemView); 100 | mCoverView = (ImageView) itemView.findViewById(R.id.iv_cover); 101 | mFolderName = (TextView) itemView.findViewById(R.id.tv_floder_name); 102 | mFolderSize = (TextView) itemView.findViewById(R.id.tv_folder_size); 103 | mNormalColor = ContextCompat.getColor(itemView.getContext(), R.color.background); 104 | mSelectedColor = ContextCompat.getColor(itemView.getContext(), R.color.primary_light); 105 | } 106 | } 107 | 108 | } 109 | -------------------------------------------------------------------------------- /imageseletor/src/main/java/io/github/lijunguan/imgselector/album/adapter/ImageGridAdapter.java: -------------------------------------------------------------------------------- 1 | package io.github.lijunguan.imgselector.album.adapter; 2 | 3 | import android.support.v7.widget.RecyclerView; 4 | import android.view.LayoutInflater; 5 | import android.view.View; 6 | import android.view.ViewGroup; 7 | import android.widget.CheckBox; 8 | import android.widget.ImageView; 9 | 10 | import com.bumptech.glide.RequestManager; 11 | 12 | import java.util.Collections; 13 | import java.util.List; 14 | 15 | import io.github.lijunguan.imgselector.AlbumConfig; 16 | import io.github.lijunguan.imgselector.ImageSelector; 17 | import io.github.lijunguan.imgselector.R; 18 | import io.github.lijunguan.imgselector.album.AlbumFragment; 19 | import io.github.lijunguan.imgselector.model.entity.ImageInfo; 20 | 21 | import static io.github.lijunguan.imgselector.utils.CommonUtils.checkNotNull; 22 | 23 | 24 | /** 25 | * Created by lijunguan on 2016/4/11 26 | * email: lijunguan199210@gmail.com 27 | * blog : https://lijunguan.github.io 28 | */ 29 | public class ImageGridAdapter extends RecyclerView.Adapter { 30 | 31 | public static final int NORMAL_ITEM = 0; 32 | public static final int CAMERA_ITEM = 1; 33 | 34 | private List mData = Collections.emptyList(); 35 | 36 | private final RequestManager mRequestManager; 37 | 38 | private AlbumConfig mAlbumConfig; 39 | 40 | private AlbumFragment.ImageItemListener mListener; 41 | 42 | public ImageGridAdapter(RequestManager requestManager, AlbumConfig albumConfig, AlbumFragment.ImageItemListener listener) { 43 | mRequestManager = checkNotNull(requestManager); 44 | mAlbumConfig = checkNotNull(albumConfig); 45 | mListener = listener; 46 | } 47 | 48 | 49 | public void replaceData(List data) { 50 | mData = checkNotNull(data); 51 | notifyDataSetChanged(); 52 | } 53 | 54 | 55 | @SuppressWarnings("SuspiciousNameCombination") 56 | @Override 57 | public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 58 | 59 | int itemWidth = parent.getWidth() / mAlbumConfig.getGridColumns(); 60 | 61 | View rootView; 62 | if (viewType == NORMAL_ITEM) { 63 | rootView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_image_grid, parent, false); 64 | rootView.getLayoutParams().height = itemWidth; //构建正方形Item布局 65 | return new ImageViewHolder(rootView); 66 | } else { 67 | //inflate 拍照 item 68 | rootView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_camera, parent, false); 69 | rootView.getLayoutParams().height = itemWidth; 70 | rootView.setOnClickListener(new View.OnClickListener() { 71 | @Override 72 | public void onClick(View v) { 73 | //调用系统相机,拍照 74 | mListener.onCameraItemClick(); 75 | } 76 | }); 77 | return new RecyclerView.ViewHolder(rootView) { 78 | }; 79 | } 80 | } 81 | 82 | @Override 83 | public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) { 84 | if (isNormalItem(position)) { 85 | final ImageViewHolder imgHolder = (ImageViewHolder) holder; 86 | final ImageInfo imageInfo = getItem(position); 87 | 88 | if (mAlbumConfig.getSelectModel() == ImageSelector.MULTI_MODE) { 89 | //这里使用CheckBox的OnClickListener监听,而不是OnCheckedChangeListener ,当调用CheckBox的CheckBox.setChecked() 90 | //方法时又会触发OnCheckedChangeListener监听,加上VieHolder缓存服用, 问题简直不能更多!!! 用OnClickListener巧妙解决 91 | imgHolder.mCheckBox.setOnClickListener(new View.OnClickListener() { 92 | @Override 93 | public void onClick(View v) { 94 | if (!imageInfo.isSelected()) { 95 | mListener.onSelectedImageClick(imageInfo, mAlbumConfig.getMaxCount(), imgHolder.getAdapterPosition()); 96 | imgHolder.mMaskView.setVisibility(View.VISIBLE); 97 | } else { 98 | mListener.onUnSelectedImageClick(imageInfo, imgHolder.getAdapterPosition()); 99 | imgHolder.mMaskView.setVisibility(View.GONE); 100 | } 101 | } 102 | }); 103 | imgHolder.mCheckBox.setChecked(imageInfo.isSelected()); 104 | imgHolder.mMaskView.setVisibility(imageInfo.isSelected() ? View.VISIBLE : View.GONE); 105 | 106 | } else if (mAlbumConfig.getSelectModel() == ImageSelector.AVATOR_MODE) { 107 | imgHolder.mCheckBox.setVisibility(View.GONE); 108 | } 109 | 110 | imgHolder.itemView.setOnClickListener(new View.OnClickListener() { 111 | @Override 112 | public void onClick(View v) { 113 | 114 | int realPositon = holder.getAdapterPosition(); 115 | //得到图片在集合中真正的 position 116 | if (mAlbumConfig.isShownCamera()) { 117 | realPositon--; 118 | } 119 | mListener.onImageClick(realPositon, imageInfo, mAlbumConfig.getSelectModel()); 120 | } 121 | }); 122 | 123 | mRequestManager 124 | .load(imageInfo.getPath()) 125 | .asBitmap() 126 | .placeholder(R.drawable.placeholder) 127 | .into(imgHolder.mImageView); 128 | 129 | 130 | } 131 | 132 | } 133 | 134 | private boolean isNormalItem(int position) { 135 | return !mAlbumConfig.isShownCamera() || position > 0; 136 | } 137 | 138 | @Override 139 | public int getItemCount() { 140 | return mAlbumConfig.isShownCamera() ? mData.size() + 1 : mData.size(); 141 | } 142 | 143 | public ImageInfo getItem(int position) { 144 | return mAlbumConfig.isShownCamera() ? mData.get(position - 1) : mData.get(position); 145 | } 146 | 147 | @Override 148 | public int getItemViewType(int position) { 149 | if (mAlbumConfig.isShownCamera()) { 150 | if (position == 0) 151 | return CAMERA_ITEM; 152 | return NORMAL_ITEM; 153 | } else { 154 | return NORMAL_ITEM; 155 | } 156 | } 157 | 158 | static class ImageViewHolder extends RecyclerView.ViewHolder { 159 | ImageView mImageView; 160 | View mMaskView; 161 | CheckBox mCheckBox; 162 | 163 | public ImageViewHolder(View itemView) { 164 | super(itemView); 165 | mImageView = (ImageView) itemView.findViewById(R.id.iv_image); 166 | mMaskView = itemView.findViewById(R.id.mask); 167 | mCheckBox = (CheckBox) itemView.findViewById(R.id.cb_checkbox); 168 | } 169 | } 170 | 171 | 172 | } 173 | -------------------------------------------------------------------------------- /imageseletor/src/main/java/io/github/lijunguan/imgselector/album/previewimage/ImageContract.java: -------------------------------------------------------------------------------- 1 | package io.github.lijunguan.imgselector.album.previewimage; 2 | 3 | import android.support.annotation.NonNull; 4 | 5 | import io.github.lijunguan.imgselector.base.BasePresenter; 6 | import io.github.lijunguan.imgselector.base.BaseView; 7 | import io.github.lijunguan.imgselector.model.entity.ImageInfo; 8 | 9 | /** 10 | * Created by lijunguan on 2016/4/24. 11 | * emial: lijunguan199210@gmail.com 12 | * blog: https://lijunguan.github.io 13 | */ 14 | public interface ImageContract { 15 | 16 | interface View extends BaseView { 17 | 18 | void updateIndicator(); 19 | 20 | void showOutOfRange(int position); 21 | 22 | void showSelectedCount(int count); 23 | } 24 | 25 | interface Presenter extends BasePresenter { 26 | 27 | void selectImage(@NonNull ImageInfo imageInfo, int maxCount, int position); 28 | 29 | void unSelectImage(@NonNull ImageInfo imageInfo, int position); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /imageseletor/src/main/java/io/github/lijunguan/imgselector/album/previewimage/ImageDetailFragment.java: -------------------------------------------------------------------------------- 1 | package io.github.lijunguan.imgselector.album.previewimage; 2 | 3 | import android.os.Bundle; 4 | import android.support.annotation.Nullable; 5 | import android.support.design.widget.Snackbar; 6 | import android.support.v4.view.PagerAdapter; 7 | import android.support.v4.view.ViewPager; 8 | import android.view.LayoutInflater; 9 | import android.view.View; 10 | import android.view.ViewGroup; 11 | import android.widget.CheckBox; 12 | 13 | import com.bumptech.glide.Glide; 14 | import com.bumptech.glide.RequestManager; 15 | 16 | import java.util.ArrayList; 17 | import java.util.List; 18 | 19 | import io.github.lijunguan.imgselector.AlbumConfig; 20 | import io.github.lijunguan.imgselector.ImageSelector; 21 | import io.github.lijunguan.imgselector.R; 22 | import io.github.lijunguan.imgselector.base.BaseFragment; 23 | import io.github.lijunguan.imgselector.model.entity.ImageInfo; 24 | import uk.co.senab.photoview.PhotoView; 25 | 26 | import static io.github.lijunguan.imgselector.utils.CommonUtils.checkNotNull; 27 | 28 | /** 29 | * Created by lijunguan on 2016/4/22. 30 | * emial: lijunguan199210@gmail.com 31 | * blog: https://lijunguan.github.io 32 | */ 33 | public class ImageDetailFragment extends BaseFragment 34 | implements ImageContract.View { 35 | public static final String TAG = ImageDetailFragment.class.getSimpleName(); 36 | 37 | public static final String ARG_IMAGE_LIST = "imageInfos"; 38 | 39 | public static final String ARG_CURRENT_POSITION = "currentPosition"; 40 | 41 | private ViewPager mViewPager; 42 | 43 | private CheckBox mCheckBox; 44 | 45 | private List mImageInfos; 46 | 47 | private int mCurrentPosition; 48 | 49 | private ImageContract.Presenter mPresenter; 50 | 51 | private AlbumConfig mAlbumConfig; 52 | 53 | private ImageDetailAdapter mPagerAdapter; 54 | 55 | public static ImageDetailFragment newInstance(ArrayList imageInfos, int currentPosition) { 56 | ImageDetailFragment fragment = new ImageDetailFragment(); 57 | Bundle args = new Bundle(); 58 | args.putParcelableArrayList(ARG_IMAGE_LIST, imageInfos); 59 | args.putInt(ARG_CURRENT_POSITION, currentPosition); 60 | fragment.setArguments(args); 61 | return fragment; 62 | } 63 | 64 | @Override 65 | public void onCreate(@Nullable Bundle savedInstanceState) { 66 | super.onCreate(savedInstanceState); 67 | if (getArguments() != null) { 68 | mImageInfos = getArguments().getParcelableArrayList(ARG_IMAGE_LIST); 69 | mCurrentPosition = getArguments().getInt(ARG_CURRENT_POSITION); 70 | } 71 | if (savedInstanceState != null) { 72 | //当Application被kill,复原Fragment时,得到原本配置信息 73 | mAlbumConfig = savedInstanceState.getParcelable(ImageSelector.ARG_ALBUM_CONFIG); 74 | ImageSelector.getInstance().setConfig(mAlbumConfig); 75 | } else { 76 | mAlbumConfig = ImageSelector.getInstance().getConfig(); 77 | } 78 | 79 | } 80 | 81 | @Override 82 | public void onSaveInstanceState(Bundle outState) { 83 | //保存配置参数,防止Application被kill后,恢复Fragment时,配置参数发送异常 84 | outState.putParcelable(ImageSelector.ARG_ALBUM_CONFIG, mAlbumConfig); 85 | } 86 | 87 | @Nullable 88 | @Override 89 | public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 90 | View rootView = inflater.inflate(R.layout.fragmetn_image_detail, container, false); 91 | mViewPager = (ViewPager) rootView.findViewById(R.id.view_pager); 92 | mCheckBox = (CheckBox) rootView.findViewById(R.id.cb_checkbox); 93 | mCheckBox.setOnClickListener(new View.OnClickListener() { 94 | @Override 95 | public void onClick(View v) { 96 | int position = mViewPager.getCurrentItem(); 97 | ImageInfo currentItem = mPagerAdapter.getItem(position); 98 | if (!currentItem.isSelected()) { 99 | mPresenter.selectImage(currentItem, mAlbumConfig.getMaxCount(), position); 100 | } else { 101 | mPresenter.unSelectImage(currentItem, position); 102 | } 103 | } 104 | }); 105 | mPagerAdapter = new ImageDetailAdapter(Glide.with(mContext), mImageInfos); 106 | mViewPager.setAdapter(mPagerAdapter); 107 | mViewPager.setCurrentItem(mCurrentPosition); 108 | mViewPager.addOnPageChangeListener(onPageChangeListener); 109 | mCheckBox.setChecked(mImageInfos.get(mCurrentPosition).isSelected()); 110 | updateIndicator(); 111 | return rootView; 112 | } 113 | 114 | private ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.SimpleOnPageChangeListener() { 115 | @Override 116 | public void onPageSelected(int position) { 117 | ImageInfo item = mPagerAdapter.getItem(position); 118 | mCheckBox.setChecked(item.isSelected()); 119 | updateIndicator(); 120 | } 121 | }; 122 | 123 | @Override 124 | public void updateIndicator() { 125 | String text = String.format("(%1$d/%2$d)", mViewPager.getCurrentItem() + 1, mPagerAdapter.getCount()); 126 | mContext.setToolbarTitle(text); 127 | } 128 | 129 | 130 | @Override 131 | public void setPresenter(ImageContract.Presenter presenter) { 132 | mPresenter = checkNotNull(presenter); 133 | } 134 | 135 | @Override 136 | public void showOutOfRange(int position) { 137 | String warningMSg = getString(R.string.out_of_limit, mAlbumConfig.getMaxCount()); 138 | showToast(warningMSg); 139 | mCheckBox.setChecked(false); 140 | } 141 | 142 | @Override 143 | public void showSelectedCount(int count) { 144 | String text; 145 | if (count > 0) { 146 | text = getString(R.string.update_count, count, mAlbumConfig.getMaxCount()); 147 | mContext.setSubmitBtnText(text, true); 148 | } else { 149 | text = getString(R.string.btn_submit_text); 150 | mContext.setSubmitBtnText(text, false); 151 | } 152 | } 153 | 154 | @Override 155 | public void showToast(CharSequence message) { 156 | Snackbar.make(getView(), message, Snackbar.LENGTH_SHORT).show(); 157 | } 158 | 159 | 160 | static class ImageDetailAdapter extends PagerAdapter { 161 | 162 | private List mData = new ArrayList<>(); 163 | 164 | private final RequestManager mRequestManager; 165 | 166 | 167 | public ImageDetailAdapter(RequestManager requestManager, List data) { 168 | mData = checkNotNull(data); 169 | mRequestManager = checkNotNull(requestManager); 170 | } 171 | 172 | @Override 173 | public int getCount() { 174 | return mData.size(); 175 | } 176 | 177 | @Override 178 | public boolean isViewFromObject(View view, Object object) { 179 | return view == object; 180 | } 181 | 182 | @Override 183 | public Object instantiateItem(ViewGroup container, int position) { 184 | PhotoView photoView = (PhotoView) LayoutInflater.from(container.getContext()) 185 | .inflate(R.layout.item_image_detail, container, false); 186 | mRequestManager 187 | .load(mData.get(position).getPath()) 188 | .asBitmap() 189 | .fitCenter() 190 | .thumbnail(0.2f) 191 | .into(photoView); 192 | container.addView(photoView); 193 | return photoView; 194 | } 195 | 196 | @Override 197 | public void destroyItem(ViewGroup container, int position, Object object) { 198 | container.removeView((View) object); 199 | } 200 | 201 | public ImageInfo getItem(int position) { 202 | return mData.get(position); 203 | } 204 | } 205 | } 206 | -------------------------------------------------------------------------------- /imageseletor/src/main/java/io/github/lijunguan/imgselector/album/previewimage/ImageDetailPresenter.java: -------------------------------------------------------------------------------- 1 | package io.github.lijunguan.imgselector.album.previewimage; 2 | 3 | import android.support.annotation.NonNull; 4 | 5 | import io.github.lijunguan.imgselector.album.AlbumContract; 6 | import io.github.lijunguan.imgselector.model.AlbumRepository; 7 | import io.github.lijunguan.imgselector.model.entity.ImageInfo; 8 | 9 | import static io.github.lijunguan.imgselector.utils.CommonUtils.checkNotNull; 10 | 11 | /** 12 | * Created by lijunguan on 2016/4/24. 13 | */ 14 | public class ImageDetailPresenter implements ImageContract.Presenter { 15 | private AlbumRepository mAlbumRepository; 16 | 17 | private ImageContract.View mImageDetailView; 18 | 19 | private AlbumContract.View mAlbumView; 20 | 21 | public ImageDetailPresenter( 22 | @NonNull AlbumRepository albumRepository, 23 | @NonNull ImageContract.View imageDetailView, 24 | @NonNull AlbumContract.View albumView) { 25 | 26 | mImageDetailView = checkNotNull(imageDetailView, "ImageContract.View cannt be null"); 27 | mAlbumRepository = checkNotNull(albumRepository, "AlbumRepository cannt be null"); 28 | mAlbumView = checkNotNull(albumView,"AlbumContract.View cannt be null"); 29 | mImageDetailView.setPresenter(this); 30 | } 31 | 32 | public void start() { 33 | // AlbumFolder folder = mAlbumRepository.getFolderByImage(mImageInfo); 34 | // int index = folder.getImgInfos().indexOf(mImageInfo); 35 | // mImageDetailView.showImageDetail(index, folder.getImgInfos()); 36 | } 37 | 38 | 39 | @Override 40 | public void selectImage(@NonNull ImageInfo imageInfo, int maxCount, int position) { 41 | checkNotNull(imageInfo, "ImageInfo cannot be null"); 42 | if (mAlbumRepository.getSelectedResult().size() >= maxCount) { 43 | mImageDetailView.showOutOfRange(0); 44 | return; 45 | } 46 | imageInfo.setSelected(true); 47 | mAlbumRepository.addSelect(imageInfo.getPath()); 48 | mImageDetailView.showSelectedCount(mAlbumRepository.getSelectedCount()); 49 | mAlbumView.syncCheckboxStatus(position); 50 | } 51 | 52 | @Override 53 | public void unSelectImage(@NonNull ImageInfo imageInfo,int position) { 54 | checkNotNull(imageInfo, "ImageInfo cannot be null"); 55 | imageInfo.setSelected(false); 56 | mAlbumRepository.removeSelect(imageInfo.getPath()); 57 | mImageDetailView.showSelectedCount(mAlbumRepository.getSelectedCount()); 58 | mAlbumView.syncCheckboxStatus(position); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /imageseletor/src/main/java/io/github/lijunguan/imgselector/album/widget/GridDividerDecorator.java: -------------------------------------------------------------------------------- 1 | package io.github.lijunguan.imgselector.album.widget; 2 | 3 | import android.content.Context; 4 | import android.content.res.TypedArray; 5 | import android.graphics.Canvas; 6 | import android.graphics.Rect; 7 | import android.graphics.drawable.Drawable; 8 | import android.support.v4.view.ViewCompat; 9 | import android.support.v7.widget.GridLayoutManager; 10 | import android.support.v7.widget.RecyclerView; 11 | import android.view.View; 12 | 13 | /** 14 | * Created by lijunguan on 2016/4/11 15 | * email: lijunguan199210@gmail.com 16 | * blog : https://lijunguan.github.io 17 | */ 18 | public class GridDividerDecorator extends RecyclerView.ItemDecoration { 19 | private static final int[] ATTRS = new int[]{android.R.attr.listDivider}; 20 | private Drawable mDivider; 21 | private int mDividerSize; 22 | 23 | public GridDividerDecorator(Context context) { 24 | final TypedArray a = context.obtainStyledAttributes(ATTRS); 25 | mDivider = a.getDrawable(0); 26 | mDividerSize = mDivider.getIntrinsicHeight(); 27 | a.recycle(); 28 | } 29 | 30 | @Override 31 | public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) { 32 | drawRightDivider(c, parent); 33 | drawBottomDivider(c, parent); 34 | } 35 | 36 | private void drawRightDivider(Canvas c, RecyclerView parent) { 37 | final int childCount = parent.getChildCount(); 38 | for (int i = 0; i < childCount; i++) { 39 | 40 | final View child = parent.getChildAt(i); 41 | final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child 42 | .getLayoutParams(); 43 | final int left = child.getRight() + params.rightMargin; 44 | final int right = left + mDividerSize; 45 | final int top = child.getTop() - params.topMargin; 46 | final int bottom = child.getBottom() + params.bottomMargin; 47 | mDivider.setBounds(left, top, right, bottom); 48 | mDivider.draw(c); 49 | } 50 | } 51 | 52 | private void drawBottomDivider(Canvas c, RecyclerView parent) { 53 | final int childCount = parent.getChildCount(); 54 | for (int i = 0; i < childCount; i++) { 55 | 56 | final View child = parent.getChildAt(i); 57 | final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child 58 | .getLayoutParams(); 59 | final int left = child.getLeft() - params.leftMargin; 60 | final int right = child.getRight() - params.rightMargin + mDividerSize; 61 | final int top = child.getBottom() + params.bottomMargin + 62 | Math.round(ViewCompat.getTranslationY(child)); 63 | final int bottom = top + mDividerSize; 64 | mDivider.setBounds(left, top, right, bottom); 65 | mDivider.draw(c); 66 | } 67 | } 68 | 69 | //过时方法 70 | // @Override 71 | // public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) { 72 | // int spanCount = getSpanCount(parent); 73 | // if (spanCount == -1) 74 | // throw new ClassCastException("Can not cast" + parent.getLayoutManager() + "to GridLayoutManager"); 75 | // if (isLastCloum(itemPosition, spanCount)) { 76 | // //如果是最后一列则不绘制右边的Divider 77 | // outRect.set(0, 0, 0, mDividerSize); 78 | // } else { 79 | // outRect.set(0, 0, mDividerSize, mDividerSize); 80 | // } 81 | // } 82 | // 83 | @Override 84 | public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { 85 | int position = parent.getChildAdapterPosition(view); 86 | int spanCount = getSpanCount(parent); 87 | if (spanCount == -1) 88 | throw new ClassCastException("Can not cast" + parent.getLayoutManager() + "to GridLayoutManager"); 89 | if (isLastCloum(position, spanCount)) { 90 | //如果是最后一列则不绘制右边的Divider 91 | outRect.set(0, 0, 0, mDividerSize); 92 | } else { 93 | outRect.set(0, 0, mDividerSize, mDividerSize); 94 | } 95 | } 96 | 97 | private boolean isLastCloum(int itemPosition, int spanCount) { 98 | return (itemPosition + 1) % spanCount == 0; 99 | 100 | } 101 | 102 | 103 | private int getSpanCount(RecyclerView parent) { 104 | RecyclerView.LayoutManager layoutManager = parent.getLayoutManager(); 105 | if (layoutManager instanceof GridLayoutManager) { 106 | return ((GridLayoutManager) layoutManager).getSpanCount(); 107 | } else { 108 | return -1; 109 | } 110 | } 111 | } -------------------------------------------------------------------------------- /imageseletor/src/main/java/io/github/lijunguan/imgselector/album/widget/HackyViewPager.java: -------------------------------------------------------------------------------- 1 | package io.github.lijunguan.imgselector.album.widget; 2 | 3 | import android.content.Context; 4 | import android.support.v4.view.ViewPager; 5 | import android.util.AttributeSet; 6 | import android.view.MotionEvent; 7 | 8 | /** 9 | * Found at http://stackoverflow.com/questions/7814017/is-it-possible-to-disable-scrolling-on-a-viewpager. 10 | * Convenient way to temporarily disable ViewPager navigation while interacting with ImageView. 11 | * 12 | * Julia Zudikova 13 | */ 14 | 15 | /** 16 | * Hacky fix for Issue #4 and 17 | * http://code.google.com/p/android/issues/detail?id=18990 18 | * 19 | * ScaleGestureDetector seems to mess up the touch events, which means that 20 | * ViewGroups which make use of onInterceptTouchEvent throw a lot of 21 | * IllegalArgumentException: pointerIndex out of range. 22 | * 23 | * There's not much I can do in my code for now, but we can mask the result by 24 | * just catching the problem and ignoring it. 25 | * 26 | * @author Chris Banes 27 | */ 28 | public class HackyViewPager extends ViewPager { 29 | 30 | private boolean isLocked; 31 | 32 | public HackyViewPager(Context context) { 33 | super(context); 34 | isLocked = false; 35 | } 36 | 37 | public HackyViewPager(Context context, AttributeSet attrs) { 38 | super(context, attrs); 39 | isLocked = false; 40 | } 41 | 42 | @Override 43 | public boolean onInterceptTouchEvent(MotionEvent ev) { 44 | if (!isLocked) { 45 | try { 46 | return super.onInterceptTouchEvent(ev); 47 | } catch (IllegalArgumentException e) { 48 | e.printStackTrace(); 49 | return false; 50 | } 51 | } 52 | return false; 53 | } 54 | 55 | @Override 56 | public boolean onTouchEvent(MotionEvent event) { 57 | return !isLocked && super.onTouchEvent(event); 58 | } 59 | 60 | 61 | } 62 | -------------------------------------------------------------------------------- /imageseletor/src/main/java/io/github/lijunguan/imgselector/base/BaseActivity.java: -------------------------------------------------------------------------------- 1 | package io.github.lijunguan.imgselector.base; 2 | 3 | import android.content.DialogInterface; 4 | import android.support.annotation.LayoutRes; 5 | import android.support.annotation.NonNull; 6 | import android.support.annotation.Nullable; 7 | import android.support.v4.app.ActivityCompat; 8 | import android.support.v4.content.ContextCompat; 9 | import android.support.v7.app.ActionBar; 10 | import android.support.v7.app.AlertDialog; 11 | import android.support.v7.app.AppCompatActivity; 12 | import android.support.v7.widget.Toolbar; 13 | import android.view.MenuItem; 14 | 15 | import io.github.lijunguan.imgselector.ImageSelector; 16 | import io.github.lijunguan.imgselector.R; 17 | import io.github.lijunguan.imgselector.utils.StatusBarUtil; 18 | 19 | /** 20 | * Created by lijunguan on 2016/4/8 21 | * email: lijunguan199210@gmail.com 22 | * blog : https://lijunguan.github.io 23 | */ 24 | 25 | public class BaseActivity extends AppCompatActivity { 26 | 27 | 28 | 29 | protected Toolbar mToolbar; 30 | 31 | private AlertDialog mAlertDialog; 32 | 33 | @Override 34 | public void setContentView(@LayoutRes int layoutResID) { 35 | super.setContentView(layoutResID); 36 | trySetToolBar(); 37 | setStatusBar(); 38 | } 39 | 40 | private void trySetToolBar() { 41 | mToolbar = (Toolbar) findViewById(R.id.toolbar); 42 | if (mToolbar != null) { 43 | setSupportActionBar(mToolbar); 44 | ActionBar ab = getSupportActionBar(); 45 | ab.setDisplayHomeAsUpEnabled(true); 46 | } 47 | } 48 | 49 | /** 50 | * 设置状态栏颜色,支持 API14 以上 51 | */ 52 | protected void setStatusBar() { 53 | int toolBarColor = ImageSelector.getInstance().getConfig().getToolbarColor(); 54 | if (toolBarColor != -1) { 55 | StatusBarUtil.setColor(this, toolBarColor); 56 | if (mToolbar != null) 57 | mToolbar.setBackgroundColor(toolBarColor); 58 | } else { 59 | StatusBarUtil.setColor(this, ContextCompat.getColor(this, R.color.primary)); 60 | 61 | } 62 | } 63 | 64 | /** 65 | * Android6.0 动态申请权限,如果这个permission已经被用户拒绝过, 66 | * 则弹出一个对话框,显示rationale内容(解释为什么要申请该权限), 否则 立即申请权限 67 | * @param permission 要申请的权限 68 | * @param rationale 申请权限原因描述 69 | * @param requestCode 70 | */ 71 | public void requestPermission(final String permission, String rationale, final int requestCode) { 72 | if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) { 73 | showAlertDialog(getString(R.string.permission_title_rationale), rationale, 74 | new DialogInterface.OnClickListener() { 75 | @Override 76 | public void onClick(DialogInterface dialog, int which) { 77 | ActivityCompat.requestPermissions(BaseActivity.this, new String[]{permission}, requestCode); 78 | } 79 | }, getString(R.string.label_ok), null, getString(R.string.label_cancel)); 80 | } else { 81 | ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode); 82 | } 83 | } 84 | 85 | 86 | 87 | protected void showAlertDialog(@Nullable String title, @Nullable String message, 88 | @Nullable DialogInterface.OnClickListener onPositiveButtonClickListener, 89 | @NonNull String positiveText, 90 | @Nullable DialogInterface.OnClickListener onNegativeButtonClickListener, 91 | @NonNull String negativeText) { 92 | AlertDialog.Builder builder = new AlertDialog.Builder(this); 93 | builder.setTitle(title); 94 | builder.setMessage(message); 95 | builder.setPositiveButton(positiveText, onPositiveButtonClickListener); 96 | builder.setNegativeButton(negativeText, onNegativeButtonClickListener); 97 | mAlertDialog = builder.show(); 98 | } 99 | 100 | @Override 101 | public boolean onOptionsItemSelected(MenuItem item) { 102 | switch (item.getItemId()) { 103 | case android.R.id.home: 104 | onBackPressed(); 105 | return true; 106 | default: 107 | return super.onOptionsItemSelected(item); 108 | } 109 | } 110 | 111 | @Override 112 | protected void onStop() { 113 | super.onStop(); 114 | if (mAlertDialog != null && mAlertDialog.isShowing()) { 115 | mAlertDialog.dismiss(); 116 | } 117 | } 118 | 119 | } 120 | -------------------------------------------------------------------------------- /imageseletor/src/main/java/io/github/lijunguan/imgselector/base/BaseFragment.java: -------------------------------------------------------------------------------- 1 | package io.github.lijunguan.imgselector.base; 2 | 3 | import android.content.Context; 4 | import android.support.v4.app.Fragment; 5 | 6 | import java.lang.ref.WeakReference; 7 | 8 | import io.github.lijunguan.imgselector.album.AlbumActivity; 9 | 10 | /** 11 | * Created by lijunguan on 2016/4/8 12 | * email: lijunguan199210@gmail.com 13 | * blog : https://lijunguan.github.io 14 | */ 15 | public class BaseFragment extends Fragment { 16 | protected AlbumActivity mContext; 17 | 18 | @Override 19 | public void onAttach(Context context) { 20 | super.onAttach(context); 21 | //在Fragment中用 弱引用的方式持有一份Activity 引用,方便在Fragment中使用Context 22 | if (context instanceof AlbumActivity) { 23 | WeakReference mActivityRef = new WeakReference<>((AlbumActivity) getActivity()); 24 | mContext = mActivityRef.get(); 25 | } else { 26 | throw new IllegalArgumentException("unexcepted context "); 27 | } 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /imageseletor/src/main/java/io/github/lijunguan/imgselector/base/BasePresenter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016, The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.github.lijunguan.imgselector.base; 18 | 19 | public interface BasePresenter { 20 | /** 21 | * 一般在onResume()方法中调用,执行一些数据初始化工作 22 | */ 23 | void start(); 24 | 25 | } 26 | -------------------------------------------------------------------------------- /imageseletor/src/main/java/io/github/lijunguan/imgselector/base/BaseView.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016, The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.github.lijunguan.imgselector.base; 18 | 19 | public interface BaseView { 20 | /** 21 | * 给View(Fragment,Activity 视图UI)设置Presenter 22 | * 23 | * @param presenter 24 | */ 25 | void setPresenter(T presenter); 26 | /** 27 | * 用来显示提示信息,用Snackbar实现 28 | * 29 | * @param message 提示的消息内容 30 | */ 31 | void showToast(CharSequence message); 32 | } 33 | -------------------------------------------------------------------------------- /imageseletor/src/main/java/io/github/lijunguan/imgselector/cropimage/CropActivity.java: -------------------------------------------------------------------------------- 1 | package io.github.lijunguan.imgselector.cropimage; 2 | 3 | import android.content.Intent; 4 | import android.os.Bundle; 5 | import android.support.annotation.Nullable; 6 | import android.view.View; 7 | 8 | import io.github.lijunguan.imgselector.R; 9 | import io.github.lijunguan.imgselector.base.BaseActivity; 10 | import io.github.lijunguan.imgselector.utils.ActivityUtils; 11 | 12 | /** 13 | * Created by lijunguan on 2016/4/26. 14 | * emial: lijunguan199210@gmail.com 15 | * blog: https://lijunguan.github.io 16 | */ 17 | public class CropActivity extends BaseActivity implements CropFragment.CropImageListener { 18 | 19 | private CropFragment mCropFragment; 20 | 21 | public static final String CROP_RESULT = "cropResult"; 22 | 23 | @Override 24 | protected void onCreate(@Nullable Bundle savedInstanceState) { 25 | super.onCreate(savedInstanceState); 26 | setContentView(R.layout.activity_crop); 27 | if (savedInstanceState == null) { 28 | String iamgePath = getIntent().getStringExtra(CropFragment.ARG_IMAGE_PATH); 29 | mCropFragment = CropFragment.newInstance(iamgePath); 30 | ActivityUtils.addFragmentToActivity( 31 | getSupportFragmentManager(), 32 | mCropFragment, 33 | CropFragment.TAG, 34 | false 35 | ); 36 | } 37 | 38 | findViewById(R.id.btn_submit).setOnClickListener(new View.OnClickListener() { 39 | @Override 40 | public void onClick(View v) { 41 | if (mCropFragment != null) 42 | mCropFragment.cropImage(); 43 | } 44 | }); 45 | } 46 | 47 | 48 | 49 | @Override 50 | public void onCropCompleted(String path) { 51 | Intent intent = new Intent(); 52 | intent.putExtra(CROP_RESULT, path); 53 | setResult(RESULT_OK, intent); 54 | finish(); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /imageseletor/src/main/java/io/github/lijunguan/imgselector/cropimage/CropFragment.java: -------------------------------------------------------------------------------- 1 | package io.github.lijunguan.imgselector.cropimage; 2 | 3 | import android.app.Activity; 4 | import android.content.Context; 5 | import android.graphics.Bitmap; 6 | import android.graphics.Rect; 7 | import android.os.Bundle; 8 | import android.support.annotation.Nullable; 9 | import android.support.v4.app.Fragment; 10 | import android.view.LayoutInflater; 11 | import android.view.View; 12 | import android.view.ViewGroup; 13 | import android.view.ViewTreeObserver; 14 | 15 | import com.bumptech.glide.Glide; 16 | import com.bumptech.glide.load.engine.DiskCacheStrategy; 17 | import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool; 18 | import com.bumptech.glide.load.resource.bitmap.BitmapTransformation; 19 | 20 | import java.io.File; 21 | import java.io.IOException; 22 | 23 | import io.github.lijunguan.imgselector.BuildConfig; 24 | import io.github.lijunguan.imgselector.R; 25 | import io.github.lijunguan.imgselector.cropimage.crop.CropView; 26 | import io.github.lijunguan.imgselector.utils.FileUtils; 27 | import io.github.lijunguan.imgselector.utils.KLog; 28 | 29 | import static io.github.lijunguan.imgselector.utils.CommonUtils.checkNotNull; 30 | 31 | /** 32 | * Created by lijunguan on 2016/4/26. 33 | * emial: lijunguan199210@gmail.com 34 | * blog: https://lijunguan.github.io 35 | */ 36 | public class CropFragment extends Fragment { 37 | 38 | private Activity mContext; 39 | 40 | public static final String TAG = CropFragment.class.getSimpleName(); 41 | 42 | public static final String ARG_IMAGE_PATH = "imageInfo"; 43 | 44 | private String mImagePath; 45 | 46 | private CropView mCropView; 47 | 48 | private CropImageListener mListener; 49 | 50 | public static CropFragment newInstance(String imagePath) { 51 | checkNotNull(imagePath); 52 | CropFragment fragment = new CropFragment(); 53 | Bundle args = new Bundle(); 54 | args.putString(ARG_IMAGE_PATH, imagePath); 55 | fragment.setArguments(args); 56 | return fragment; 57 | } 58 | 59 | @Override 60 | public void onAttach(Context context) { 61 | super.onAttach(context); 62 | mContext = (Activity) context; 63 | if (context instanceof CropImageListener) { 64 | mListener = (CropImageListener) context; 65 | } else { 66 | throw new RuntimeException(context.toString() 67 | + " must implement CropImageListener"); 68 | } 69 | } 70 | 71 | @Override 72 | public void onDestroy() { 73 | super.onDestroy(); 74 | mListener = null; 75 | } 76 | 77 | @Override 78 | public void onCreate(@Nullable Bundle savedInstanceState) { 79 | super.onCreate(savedInstanceState); 80 | if (getArguments() != null) { 81 | mImagePath = getArguments().getString(ARG_IMAGE_PATH); 82 | } 83 | } 84 | 85 | @Nullable 86 | @Override 87 | public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 88 | View rootView = getLayoutInflater(savedInstanceState).inflate(R.layout.crop_view, container, false); 89 | mCropView = (CropView) rootView; 90 | performLoad(); //加载图片 91 | return rootView; 92 | } 93 | 94 | void performLoad() { 95 | //得到图片尺寸,合适的缩放图片大小 96 | if (mCropView.getWidth() == 0 && mCropView.getHeight() == 0) { 97 | if (!mCropView.getViewTreeObserver().isAlive()) { 98 | return; 99 | } 100 | mCropView.getViewTreeObserver().addOnGlobalLayoutListener( 101 | new ViewTreeObserver.OnGlobalLayoutListener() { 102 | @SuppressWarnings("deprecation") 103 | @Override 104 | public void onGlobalLayout() { 105 | if (mCropView.getViewTreeObserver().isAlive()) { 106 | mCropView.getViewTreeObserver().removeGlobalOnLayoutListener(this); 107 | } 108 | loadImage(); 109 | } 110 | } 111 | ); 112 | return; 113 | } 114 | loadImage(); 115 | } 116 | 117 | private void loadImage() { 118 | Glide.with(mContext) 119 | .load(mImagePath) 120 | .asBitmap() 121 | .skipMemoryCache(true) 122 | .diskCacheStrategy(DiskCacheStrategy.SOURCE) 123 | .transform(new FillViewportTransformation( 124 | Glide.get(mContext).getBitmapPool(), 125 | mCropView.getViewportWidth(), 126 | mCropView.getViewportHeight())) 127 | .into(mCropView); 128 | } 129 | 130 | public void cropImage() { 131 | 132 | final File avatorFile = new File(FileUtils.getCacheDirectory(mContext), System.currentTimeMillis() + "avator.jpg"); 133 | 134 | try { 135 | new CropView.CropRequest(mCropView) 136 | .quality(80) 137 | .format(Bitmap.CompressFormat.JPEG) 138 | .into(avatorFile); 139 | if (mListener != null) { 140 | //通知Activity裁剪完成 141 | mListener.onCropCompleted(avatorFile.getPath()); 142 | } 143 | } catch (IOException e) { 144 | e.printStackTrace(); 145 | if (BuildConfig.LOG_DEBUG) { 146 | KLog.e("Error save cropImage file"); 147 | } 148 | } 149 | } 150 | 151 | interface CropImageListener { 152 | void onCropCompleted(String path); 153 | } 154 | 155 | static class FillViewportTransformation extends BitmapTransformation { 156 | 157 | private final int viewportWidth; 158 | private final int viewportHeight; 159 | 160 | public FillViewportTransformation(BitmapPool bitmapPool, int viewportWidth, int viewportHeight) { 161 | super(bitmapPool); 162 | this.viewportWidth = viewportWidth; 163 | this.viewportHeight = viewportHeight; 164 | } 165 | 166 | @Override 167 | protected Bitmap transform(BitmapPool bitmapPool, Bitmap source, int outWidth, int outHeight) { 168 | int sourceWidth = source.getWidth(); 169 | int sourceHeight = source.getHeight(); 170 | 171 | Rect target = computeTargetSize(sourceWidth, sourceHeight, viewportWidth, viewportHeight); 172 | 173 | int targetWidth = target.width(); 174 | int targetHeight = target.height(); 175 | 176 | return Bitmap.createScaledBitmap( 177 | source, 178 | targetWidth, 179 | targetHeight, 180 | true); 181 | } 182 | 183 | @Override 184 | public String getId() { 185 | return getClass().getName(); 186 | } 187 | 188 | Rect computeTargetSize(int sourceWidth, int sourceHeight, int viewportWidth, int viewportHeight) { 189 | 190 | if (sourceWidth == viewportWidth && sourceHeight == viewportHeight) { 191 | return new Rect(0, 0, viewportWidth, viewportHeight); // Fail fast for when source matches exactly on viewport 192 | } 193 | 194 | float scale; 195 | if (sourceWidth * viewportHeight > viewportWidth * sourceHeight) { 196 | scale = (float) viewportHeight / (float) sourceHeight; 197 | } else { 198 | scale = (float) viewportWidth / (float) sourceWidth; 199 | } 200 | final int recommendedWidth = (int) ((sourceWidth * scale) + 0.5f); 201 | final int recommendedHeight = (int) ((sourceHeight * scale) + 0.5f); 202 | return new Rect(0, 0, recommendedWidth, recommendedHeight); 203 | } 204 | 205 | } 206 | } 207 | -------------------------------------------------------------------------------- /imageseletor/src/main/java/io/github/lijunguan/imgselector/cropimage/crop/CropView.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 Lyft, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.lijunguan.imgselector.cropimage.crop; 17 | 18 | import android.content.Context; 19 | import android.graphics.Bitmap; 20 | import android.graphics.BitmapFactory; 21 | import android.graphics.Canvas; 22 | import android.graphics.Matrix; 23 | import android.graphics.Paint; 24 | import android.graphics.Rect; 25 | import android.graphics.drawable.BitmapDrawable; 26 | import android.graphics.drawable.Drawable; 27 | import android.support.annotation.DrawableRes; 28 | import android.support.annotation.NonNull; 29 | import android.support.annotation.Nullable; 30 | import android.util.AttributeSet; 31 | import android.view.MotionEvent; 32 | import android.widget.ImageView; 33 | 34 | import java.io.File; 35 | import java.io.FileOutputStream; 36 | import java.io.IOException; 37 | import java.io.OutputStream; 38 | 39 | import static io.github.lijunguan.imgselector.utils.CommonUtils.checkArgument; 40 | import static io.github.lijunguan.imgselector.utils.CommonUtils.checkNotNull; 41 | 42 | /** 43 | 44 | */ 45 | public class CropView extends ImageView { 46 | 47 | public static final String TAG = "CropView"; 48 | 49 | private static final int MAX_TOUCH_POINTS = 2; 50 | private TouchManager touchManager; 51 | 52 | private Paint viewportPaint = new Paint(); 53 | private Paint bitmapPaint = new Paint(); 54 | 55 | private Bitmap bitmap; 56 | private Matrix transform = new Matrix(); 57 | 58 | 59 | public CropView(Context context) { 60 | super(context); 61 | initCropView(context, null); 62 | } 63 | 64 | public CropView(Context context, AttributeSet attrs) { 65 | super(context, attrs); 66 | 67 | initCropView(context, attrs); 68 | } 69 | 70 | void initCropView(Context context, AttributeSet attrs) { 71 | CropViewConfig config = CropViewConfig.from(context, attrs); 72 | 73 | touchManager = new TouchManager(MAX_TOUCH_POINTS, config); 74 | 75 | bitmapPaint.setFilterBitmap(true); 76 | viewportPaint.setColor(config.getViewportOverlayColor()); 77 | } 78 | 79 | @Override 80 | protected void onDraw(Canvas canvas) { 81 | super.onDraw(canvas); 82 | 83 | if (bitmap == null) { 84 | return; 85 | } 86 | 87 | drawBitmap(canvas); 88 | drawOverlay(canvas); 89 | } 90 | 91 | private void drawBitmap(Canvas canvas) { 92 | transform.reset(); 93 | touchManager.applyPositioningAndScale(transform); 94 | 95 | canvas.drawBitmap(bitmap, transform, bitmapPaint); 96 | } 97 | 98 | private void drawOverlay(Canvas canvas) { 99 | final int viewportWidth = touchManager.getViewportWidth(); 100 | final int viewportHeight = touchManager.getViewportHeight(); 101 | final int left = (getWidth() - viewportWidth) / 2; 102 | final int top = (getHeight() - viewportHeight) / 2; 103 | 104 | canvas.drawRect(0, top, left, getHeight() - top, viewportPaint); 105 | canvas.drawRect(0, 0, getWidth(), top, viewportPaint); 106 | canvas.drawRect(getWidth() - left, top, getWidth(), getHeight() - top, viewportPaint); 107 | canvas.drawRect(0, getHeight() - top, getWidth(), getHeight(), viewportPaint); 108 | } 109 | 110 | @Override 111 | protected void onSizeChanged(int w, int h, int oldw, int oldh) { 112 | super.onSizeChanged(w, h, oldw, oldh); 113 | resetTouchManager(); 114 | } 115 | 116 | @Override 117 | public void setImageResource(@DrawableRes int resId) { 118 | final Bitmap bitmap = resId > 0 119 | ? BitmapFactory.decodeResource(getResources(), resId) 120 | : null; 121 | setImageBitmap(bitmap); 122 | } 123 | 124 | @Override 125 | public void setImageDrawable(@Nullable Drawable drawable) { 126 | final Bitmap bitmap; 127 | if (drawable instanceof BitmapDrawable) { 128 | BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; 129 | bitmap = bitmapDrawable.getBitmap(); 130 | } else if (drawable != null) { 131 | bitmap = asBitmap(drawable, getWidth(), getHeight()); 132 | } else { 133 | bitmap = null; 134 | } 135 | 136 | setImageBitmap(bitmap); 137 | } 138 | 139 | public Bitmap asBitmap(Drawable drawable, int minWidth, int minHeight) { 140 | final Rect tmpRect = new Rect(); 141 | drawable.copyBounds(tmpRect); 142 | if (tmpRect.isEmpty()) { 143 | tmpRect.set(0, 0, Math.max(minWidth, drawable.getIntrinsicWidth()), Math.max(minHeight, drawable.getIntrinsicHeight())); 144 | drawable.setBounds(tmpRect); 145 | } 146 | Bitmap bitmap = Bitmap.createBitmap(tmpRect.width(), tmpRect.height(), Bitmap.Config.ARGB_8888); 147 | drawable.draw(new Canvas(bitmap)); 148 | return bitmap; 149 | } 150 | 151 | @Override 152 | public void setImageBitmap(@Nullable Bitmap bitmap) { 153 | this.bitmap = bitmap; 154 | resetTouchManager(); 155 | invalidate(); 156 | } 157 | 158 | private void resetTouchManager() { 159 | final boolean invalidBitmap = bitmap == null; 160 | final int bitmapWidth = invalidBitmap ? 0 : bitmap.getWidth(); 161 | final int bitmapHeight = invalidBitmap ? 0 : bitmap.getHeight(); 162 | touchManager.resetFor(bitmapWidth, bitmapHeight, getWidth(), getHeight()); 163 | } 164 | 165 | @Override 166 | public boolean dispatchTouchEvent(MotionEvent event) { 167 | super.dispatchTouchEvent(event); 168 | 169 | touchManager.onEvent(event); 170 | invalidate(); 171 | return true; 172 | } 173 | 174 | /** 175 | * Performs synchronous image cropping based on configuration. 176 | * 177 | * @return A {@link Bitmap} cropped based on viewport and user panning and zooming or null if no {@link Bitmap} has been 178 | * provided. 179 | */ 180 | @Nullable 181 | public Bitmap crop() { 182 | if (bitmap == null) { 183 | return null; 184 | } 185 | 186 | final Bitmap src = bitmap; 187 | final Bitmap.Config srcConfig = src.getConfig(); 188 | final Bitmap.Config config = srcConfig == null ? Bitmap.Config.ARGB_8888 : srcConfig; 189 | final int viewportHeight = touchManager.getViewportHeight(); 190 | final int viewportWidth = touchManager.getViewportWidth(); 191 | 192 | final Bitmap dst = Bitmap.createBitmap(viewportWidth, viewportHeight, config); 193 | 194 | Canvas canvas = new Canvas(dst); 195 | final int left = (getRight() - viewportWidth) / 2; 196 | final int top = (getBottom() - viewportHeight) / 2; 197 | canvas.translate(-left, -top); 198 | 199 | drawBitmap(canvas); 200 | 201 | return dst; 202 | } 203 | 204 | /** 205 | * Obtain current viewport width. 206 | * 207 | * @return Current viewport width. 208 | *

Note: It might be 0 if layout pass has not been completed.

209 | */ 210 | public int getViewportWidth() { 211 | return touchManager.getViewportWidth(); 212 | } 213 | 214 | /** 215 | * Obtain current viewport height. 216 | * 217 | * @return Current viewport height. 218 | *

Note: It might be 0 if layout pass has not been completed.

219 | */ 220 | public int getViewportHeight() { 221 | return touchManager.getViewportHeight(); 222 | } 223 | 224 | 225 | public static class CropRequest { 226 | 227 | private final CropView cropView; 228 | private Bitmap.CompressFormat format = Bitmap.CompressFormat.JPEG; 229 | private int quality = CropViewConfig.DEFAULT_IMAGE_QUALITY; 230 | 231 | public CropRequest(@NonNull CropView cropView) { 232 | checkNotNull(cropView, "cropView == null"); 233 | this.cropView = cropView; 234 | } 235 | 236 | /** 237 | * Compression format to use, defaults to {@link Bitmap.CompressFormat#JPEG}. 238 | * 239 | * @return current request for chaining. 240 | */ 241 | public CropRequest format(@NonNull Bitmap.CompressFormat format) { 242 | checkNotNull(format, "format == null"); 243 | this.format = format; 244 | return this; 245 | } 246 | 247 | /** 248 | * Compression quality to use (must be 0..100), defaults to {@value CropViewConfig#DEFAULT_IMAGE_QUALITY}. 249 | * 250 | * @return current request for chaining. 251 | */ 252 | public CropRequest quality(int quality) { 253 | checkArgument(quality >= 0 && quality <= 100, "quality must be 0..100"); 254 | this.quality = quality; 255 | return this; 256 | } 257 | 258 | 259 | //TODO 有必要的话 采用Callable + Future (将此方法在非主线程中执行) 260 | 261 | /** 262 | * 同步地将裁剪后的bitmap 写入到提供的file中, 如果需要会创建父目录 263 | * 264 | * @param file Must have permissions to write, will be created if doesn't exist or overwrite if it does. 265 | */ 266 | public void into(@NonNull File file) throws IOException { 267 | final Bitmap croppedBitmap = cropView.crop(); 268 | flushToFile(croppedBitmap, format, quality, file); 269 | } 270 | 271 | private void flushToFile(final Bitmap bitmap, 272 | final Bitmap.CompressFormat format, 273 | final int quality, 274 | final File file) throws IOException { 275 | 276 | OutputStream outputStream = null; 277 | try { 278 | file.getParentFile().mkdirs(); 279 | outputStream = new FileOutputStream(file); 280 | bitmap.compress(format, quality, outputStream); 281 | outputStream.flush(); 282 | } finally { 283 | try { 284 | if (outputStream != null) { 285 | outputStream.close(); 286 | } 287 | } catch (IOException e) { 288 | e.printStackTrace(); 289 | } 290 | } 291 | 292 | } 293 | } 294 | 295 | } 296 | -------------------------------------------------------------------------------- /imageseletor/src/main/java/io/github/lijunguan/imgselector/cropimage/crop/CropViewConfig.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 Lyft, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.lijunguan.imgselector.cropimage.crop; 17 | 18 | import android.content.Context; 19 | import android.content.res.TypedArray; 20 | import android.util.AttributeSet; 21 | 22 | import io.github.lijunguan.imgselector.R; 23 | 24 | class CropViewConfig { 25 | 26 | public static final float DEFAULT_VIEWPORT_RATIO = 0f; 27 | public static final float DEFAULT_MAXIMUM_SCALE = 10f; 28 | public static final float DEFAULT_MINIMUM_SCALE = 0f; 29 | public static final int DEFAULT_IMAGE_QUALITY = 100; 30 | public static final int DEFAULT_VIEWPORT_OVERLAY_PADDING = 0; 31 | public static final int DEFAULT_VIEWPORT_OVERLAY_COLOR = 0xC8000000; // Black with 200 alpha 32 | 33 | private float viewportRatio = DEFAULT_VIEWPORT_RATIO; 34 | private float maxScale = DEFAULT_MAXIMUM_SCALE; 35 | private float minScale = DEFAULT_MINIMUM_SCALE; 36 | private int viewportOverlayPadding = DEFAULT_VIEWPORT_OVERLAY_PADDING; 37 | private int viewportOverlayColor = DEFAULT_VIEWPORT_OVERLAY_COLOR; 38 | 39 | public int getViewportOverlayColor() { 40 | return viewportOverlayColor; 41 | } 42 | 43 | void setViewportOverlayColor(int viewportOverlayColor) { 44 | this.viewportOverlayColor = viewportOverlayColor; 45 | } 46 | 47 | public int getViewportOverlayPadding() { 48 | return viewportOverlayPadding; 49 | } 50 | 51 | void setViewportOverlayPadding(int viewportOverlayPadding) { 52 | this.viewportOverlayPadding = viewportOverlayPadding; 53 | } 54 | 55 | public float getViewportRatio() { 56 | return viewportRatio; 57 | } 58 | 59 | void setViewportRatio(float viewportRatio) { 60 | this.viewportRatio = viewportRatio <= 0 ? DEFAULT_VIEWPORT_RATIO : viewportRatio; 61 | } 62 | 63 | public float getMaxScale() { 64 | return maxScale; 65 | } 66 | 67 | void setMaxScale(float maxScale) { 68 | this.maxScale = maxScale <= 0 ? DEFAULT_MAXIMUM_SCALE : maxScale; 69 | } 70 | 71 | public float getMinScale() { 72 | return minScale; 73 | } 74 | 75 | void setMinScale(float minScale) { 76 | this.minScale = minScale <= 0 ? DEFAULT_MINIMUM_SCALE : minScale; 77 | } 78 | 79 | public static CropViewConfig from(Context context, AttributeSet attrs) { 80 | final CropViewConfig cropViewConfig = new CropViewConfig(); 81 | 82 | if (attrs == null) { 83 | return cropViewConfig; 84 | } 85 | 86 | TypedArray attributes = context.obtainStyledAttributes( 87 | attrs, 88 | R.styleable.CropView); 89 | 90 | cropViewConfig.setViewportRatio( 91 | attributes.getFloat(R.styleable.CropView_ViewportRatio, 92 | CropViewConfig.DEFAULT_VIEWPORT_RATIO)); 93 | 94 | cropViewConfig.setMaxScale( 95 | attributes.getFloat(R.styleable.CropView_MaxScale, 96 | CropViewConfig.DEFAULT_MAXIMUM_SCALE)); 97 | 98 | cropViewConfig.setMinScale( 99 | attributes.getFloat(R.styleable.CropView_MinScale, 100 | CropViewConfig.DEFAULT_MINIMUM_SCALE)); 101 | 102 | cropViewConfig.setViewportOverlayColor( 103 | attributes.getColor(R.styleable.CropView_ViewportOverlayColor, 104 | CropViewConfig.DEFAULT_VIEWPORT_OVERLAY_COLOR)); 105 | 106 | cropViewConfig.setViewportOverlayPadding( 107 | attributes.getDimensionPixelSize(R.styleable.CropView_ViewportOverlayPadding, 108 | CropViewConfig.DEFAULT_VIEWPORT_OVERLAY_PADDING)); 109 | 110 | attributes.recycle(); 111 | 112 | return cropViewConfig; 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /imageseletor/src/main/java/io/github/lijunguan/imgselector/model/AlbumDataSource.java: -------------------------------------------------------------------------------- 1 | package io.github.lijunguan.imgselector.model; 2 | 3 | import android.support.annotation.NonNull; 4 | import android.support.annotation.Nullable; 5 | import android.support.v4.app.LoaderManager; 6 | 7 | import java.util.List; 8 | 9 | import io.github.lijunguan.imgselector.model.entity.AlbumFolder; 10 | 11 | 12 | /** 13 | * Created by lijunguan on 2016/4/8 14 | * email: lijunguan199210@gmail.com 15 | * blog : https://lijunguan.github.io 16 | *

17 | * Model 层接口 18 | */ 19 | public interface AlbumDataSource { 20 | 21 | 22 | void initImgRepository(@NonNull LoaderManager loaderManager, @NonNull InitAlbumCallback mCallback); 23 | 24 | @Nullable 25 | List getSelectedResult(); 26 | 27 | void addSelect(@NonNull String path); 28 | 29 | void removeSelect(@NonNull String path); 30 | 31 | void clearCacheAndSelect(); 32 | 33 | int getSelectedCount(); 34 | 35 | 36 | interface InitAlbumCallback { 37 | 38 | void onInitFinish(List folders); 39 | 40 | void onDataNoAvaliable(); 41 | } 42 | 43 | } 44 | 45 | -------------------------------------------------------------------------------- /imageseletor/src/main/java/io/github/lijunguan/imgselector/model/AlbumRepository.java: -------------------------------------------------------------------------------- 1 | package io.github.lijunguan.imgselector.model; 2 | 3 | import android.content.Context; 4 | import android.database.Cursor; 5 | import android.os.Bundle; 6 | import android.provider.MediaStore; 7 | import android.support.annotation.NonNull; 8 | import android.support.v4.app.LoaderManager; 9 | import android.support.v4.content.CursorLoader; 10 | import android.support.v4.content.Loader; 11 | import android.text.TextUtils; 12 | 13 | import java.io.File; 14 | import java.util.ArrayList; 15 | import java.util.LinkedHashMap; 16 | import java.util.List; 17 | import java.util.Map; 18 | 19 | import io.github.lijunguan.imgselector.R; 20 | import io.github.lijunguan.imgselector.model.entity.AlbumFolder; 21 | import io.github.lijunguan.imgselector.model.entity.ImageInfo; 22 | import io.github.lijunguan.imgselector.utils.KLog; 23 | 24 | import static io.github.lijunguan.imgselector.utils.CommonUtils.checkNotNull; 25 | 26 | 27 | /** 28 | * Created by lijunguan on 2016/4/8 29 | * email: lijunguan199210@gmail.com 30 | * blog : https://lijunguan.github.io 31 | */ 32 | public class AlbumRepository implements AlbumDataSource { 33 | 34 | public static final String TAG = AlbumRepository.class.getSimpleName(); 35 | 36 | private static volatile AlbumRepository mInstance; 37 | /** 38 | * Loader的唯一ID号 39 | */ 40 | private final static int IMAGE_LOADER_ID = 1000; 41 | 42 | Map mCachedFolders; 43 | /** 44 | * 用户选择的图片路径集合 45 | */ 46 | private List mSelectedResult = new ArrayList<>(); 47 | 48 | /** 49 | * 包涵所有图片的相册名 综合的相册名 50 | */ 51 | private String mGeneralFolderName; 52 | 53 | private CursorLoader mLoader; 54 | 55 | public static AlbumRepository getInstance(Context context) { 56 | if (mInstance == null) { 57 | synchronized (AlbumRepository.class) { 58 | if (mInstance == null) { 59 | mInstance = new AlbumRepository(context.getApplicationContext()); 60 | return mInstance; 61 | } 62 | } 63 | } 64 | return mInstance; 65 | } 66 | 67 | public AlbumRepository(Context context) { 68 | 69 | String[] IMAGE_PROJECTION = { 70 | MediaStore.Images.Media.DATA, 71 | MediaStore.Images.Media.DISPLAY_NAME, 72 | MediaStore.Images.Media.DATE_ADDED, 73 | MediaStore.Images.Media.MIME_TYPE, 74 | MediaStore.Images.Media.SIZE, 75 | MediaStore.Images.Media._ID}; 76 | mGeneralFolderName = context.getString(R.string.label_general_folder_name); 77 | mLoader = new CursorLoader(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 78 | IMAGE_PROJECTION, null, 79 | null, IMAGE_PROJECTION[2] + " DESC"); 80 | } 81 | 82 | //非空注解,参数都不能为空 83 | @Override 84 | public void initImgRepository(@NonNull LoaderManager loaderManager, 85 | @NonNull final InitAlbumCallback callback) { 86 | checkNotNull(loaderManager); 87 | checkNotNull(callback); 88 | if (mCachedFolders != null) { //如果缓存可用,则立即响应 89 | callback.onInitFinish(getCachedAlbumFolder()); 90 | return; 91 | } 92 | 93 | loaderManager.initLoader(IMAGE_LOADER_ID, null, new LoaderManager.LoaderCallbacks() { 94 | @Override 95 | public Loader onCreateLoader(int id, Bundle args) { 96 | return mLoader; 97 | } 98 | 99 | @Override 100 | public void onLoadFinished(Loader loader, Cursor data) { 101 | List albumFolders = new ArrayList<>(); 102 | if (data == null) return; 103 | if (data.getCount() <= 0) { 104 | callback.onDataNoAvaliable(); 105 | return; 106 | } 107 | //创建包涵所有图片的相册目录 108 | AlbumFolder generalAlbumFolder = new AlbumFolder(); 109 | ArrayList imgList = new ArrayList<>(); 110 | generalAlbumFolder.setImgInfos(imgList); 111 | generalAlbumFolder.setFloderName(mGeneralFolderName); 112 | albumFolders.add(generalAlbumFolder); 113 | 114 | while (data.moveToNext()) { 115 | ImageInfo imageInfo = createImageInfo(data); 116 | generalAlbumFolder.getImgInfos().add(imageInfo); //每一张图片都加入到allAlbumFolder 目录中 117 | 118 | File folderFile = new File(imageInfo.getPath()).getParentFile(); //得到当前图片的目录 119 | String path = folderFile.getAbsolutePath(); 120 | AlbumFolder albumFloder = getFloderByPath(path, albumFolders); 121 | if (albumFloder == null) { 122 | //相册集合中不存在,则创建该相册目录,并添加到集合中 123 | albumFloder = new AlbumFolder(); 124 | albumFloder.setCover(imageInfo); 125 | albumFloder.setFloderName(folderFile.getName()); 126 | albumFloder.setPath(path); 127 | ArrayList imageInfos = new ArrayList<>(); 128 | imageInfos.add(imageInfo); 129 | albumFloder.setImgInfos(imageInfos); 130 | albumFolders.add(albumFloder); 131 | } else { 132 | albumFloder.getImgInfos().add(imageInfo); 133 | } 134 | } 135 | KLog.i(TAG, "========nLoadFinished :" + albumFolders.size()); 136 | 137 | generalAlbumFolder.setCover(generalAlbumFolder.getImgInfos().get(0)); 138 | callback.onInitFinish(albumFolders); 139 | processLoadedAlbumFolder(albumFolders); 140 | } 141 | 142 | 143 | @Override 144 | public void onLoaderReset(Loader loader) { 145 | 146 | } 147 | }); 148 | } 149 | 150 | private void processLoadedAlbumFolder(List folders) { 151 | if (folders == null) { 152 | mCachedFolders = null; 153 | return; 154 | } 155 | if (mCachedFolders == null) { 156 | mCachedFolders = new LinkedHashMap<>(); 157 | } 158 | mCachedFolders.clear(); 159 | for (AlbumFolder task : folders) { 160 | mCachedFolders.put(task.getPath(), task); 161 | } 162 | } 163 | 164 | public List getCachedAlbumFolder() { 165 | return mCachedFolders == null ? null : new ArrayList<>(mCachedFolders.values()); 166 | } 167 | 168 | /** 169 | * 根据传入的路径得到AlbumFloder对象 170 | * 171 | * @param path 文件路径 172 | * @return 如果mAlbumFloders集合中存在 改path路径的albumFolder则返回AlbumFloder ,否则返回null 173 | */ 174 | private AlbumFolder getFloderByPath(String path, List albumFolders) { 175 | AlbumFolder folder = null; 176 | if (albumFolders != null) { 177 | for (AlbumFolder floder : albumFolders) { 178 | if (TextUtils.equals(floder.getPath(), path)) { 179 | return floder; 180 | } 181 | } 182 | } 183 | return folder; 184 | } 185 | 186 | 187 | private ImageInfo createImageInfo(Cursor data) { 188 | String imgPath = data.getString(data.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)); 189 | String displayName = data.getString(data.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME)); 190 | long addedTime = data.getLong(data.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_ADDED)); 191 | long imageSize = data.getLong(data.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE)); 192 | return new ImageInfo(imgPath, displayName, addedTime, imageSize); 193 | } 194 | 195 | @Override 196 | public List getSelectedResult() { 197 | return mSelectedResult; 198 | } 199 | 200 | @Override 201 | public void addSelect(@NonNull String path) { 202 | mSelectedResult.add(checkNotNull(path)); 203 | } 204 | 205 | @Override 206 | public void removeSelect(@NonNull String path) { 207 | mSelectedResult.remove(checkNotNull(path)); 208 | } 209 | 210 | @Override 211 | public int getSelectedCount() { 212 | return mSelectedResult.size(); 213 | } 214 | 215 | public void clearCacheAndSelect() { 216 | mSelectedResult.clear(); 217 | mCachedFolders = null; 218 | } 219 | } 220 | -------------------------------------------------------------------------------- /imageseletor/src/main/java/io/github/lijunguan/imgselector/model/entity/AlbumFolder.java: -------------------------------------------------------------------------------- 1 | package io.github.lijunguan.imgselector.model.entity; 2 | 3 | import android.os.Parcel; 4 | import android.os.Parcelable; 5 | 6 | import java.util.List; 7 | 8 | /** 9 | * Created by lijunguan on 2016/4/8 10 | * email: lijunguan199210@gmail.com 11 | * blog : https://lijunguan.github.io 12 | */ 13 | public class AlbumFolder implements Parcelable { 14 | /** 15 | * 相册目录的路径 16 | */ 17 | private String mPath; 18 | /** 19 | * 相册目录名 20 | */ 21 | private String mFloderName; 22 | /** 23 | * 目录下的所有图片集合 24 | */ 25 | private List mImgInfos; 26 | /** 27 | * 目录封面 28 | */ 29 | private ImageInfo mCover; 30 | 31 | public String getPath() { 32 | return mPath; 33 | } 34 | 35 | public void setPath(String mPath) { 36 | this.mPath = mPath; 37 | } 38 | 39 | public String getFloderName() { 40 | return mFloderName; 41 | } 42 | 43 | public void setFloderName(String mFloderName) { 44 | this.mFloderName = mFloderName; 45 | } 46 | 47 | public List getImgInfos() { 48 | return mImgInfos; 49 | } 50 | 51 | public void setImgInfos(List mImgInfos) { 52 | this.mImgInfos = mImgInfos; 53 | } 54 | 55 | public ImageInfo getCover() { 56 | return mCover; 57 | } 58 | 59 | public void setCover(ImageInfo mCover) { 60 | this.mCover = mCover; 61 | } 62 | 63 | public AlbumFolder() { 64 | } 65 | 66 | 67 | @Override 68 | public int describeContents() { 69 | return 0; 70 | } 71 | 72 | @Override 73 | public void writeToParcel(Parcel dest, int flags) { 74 | dest.writeString(this.mPath); 75 | dest.writeString(this.mFloderName); 76 | dest.writeTypedList(mImgInfos); 77 | dest.writeParcelable(this.mCover, flags); 78 | } 79 | 80 | protected AlbumFolder(Parcel in) { 81 | this.mPath = in.readString(); 82 | this.mFloderName = in.readString(); 83 | this.mImgInfos = in.createTypedArrayList(ImageInfo.CREATOR); 84 | this.mCover = in.readParcelable(ImageInfo.class.getClassLoader()); 85 | } 86 | 87 | public static final Creator CREATOR = new Creator() { 88 | @Override 89 | public AlbumFolder createFromParcel(Parcel source) { 90 | return new AlbumFolder(source); 91 | } 92 | 93 | @Override 94 | public AlbumFolder[] newArray(int size) { 95 | return new AlbumFolder[size]; 96 | } 97 | }; 98 | } 99 | -------------------------------------------------------------------------------- /imageseletor/src/main/java/io/github/lijunguan/imgselector/model/entity/ImageInfo.java: -------------------------------------------------------------------------------- 1 | package io.github.lijunguan.imgselector.model.entity; 2 | 3 | import android.os.Parcel; 4 | import android.os.Parcelable; 5 | 6 | /** 7 | * Created by lijunguan on 2016/4/8 8 | * email: lijunguan199210@gmail.com 9 | * blog : https://lijunguan.github.io 10 | */ 11 | public class ImageInfo implements Parcelable { 12 | /** 13 | * 图片文件的名字 14 | */ 15 | private String mDisplayName; 16 | /** 17 | * 文件被添加到 media provider的时间 ,单位是 从1970年开始的毫秒数 18 | */ 19 | private long mAddedTime; 20 | /** 21 | * 文件存储路径 22 | */ 23 | private String mPath; 24 | /** 25 | * 图片大小 26 | */ 27 | private long mSize; 28 | /** 29 | * 选择状态 30 | */ 31 | private boolean isSelected; 32 | 33 | public ImageInfo(String mPath, String mDisplayName, long mAddedTime, long mSize) { 34 | this.mDisplayName = mDisplayName; 35 | this.mAddedTime = mAddedTime; 36 | this.mPath = mPath; 37 | this.mSize = mSize; 38 | } 39 | 40 | public long getSize() { 41 | return mSize; 42 | } 43 | 44 | public void setSize(long mSize) { 45 | this.mSize = mSize; 46 | } 47 | 48 | public String getDisplayName() { 49 | return mDisplayName; 50 | } 51 | 52 | public void setDisplayName(String mDisplayName) { 53 | this.mDisplayName = mDisplayName; 54 | } 55 | 56 | public long getAddedTime() { 57 | return mAddedTime; 58 | } 59 | 60 | public void setAddedTime(long mAddedTime) { 61 | this.mAddedTime = mAddedTime; 62 | } 63 | 64 | public String getPath() { 65 | return mPath; 66 | } 67 | 68 | public void setPath(String mPath) { 69 | this.mPath = mPath; 70 | } 71 | 72 | public boolean isSelected() { 73 | return isSelected; 74 | } 75 | 76 | public void setSelected(boolean selected) { 77 | isSelected = selected; 78 | } 79 | 80 | public ImageInfo() { 81 | } 82 | 83 | @Override 84 | public int describeContents() { 85 | return 0; 86 | } 87 | 88 | @Override 89 | public void writeToParcel(Parcel dest, int flags) { 90 | dest.writeString(this.mDisplayName); 91 | dest.writeLong(this.mAddedTime); 92 | dest.writeString(this.mPath); 93 | dest.writeLong(this.mSize); 94 | dest.writeByte(isSelected ? (byte) 1 : (byte) 0); 95 | } 96 | 97 | protected ImageInfo(Parcel in) { 98 | this.mDisplayName = in.readString(); 99 | this.mAddedTime = in.readLong(); 100 | this.mPath = in.readString(); 101 | this.mSize = in.readLong(); 102 | this.isSelected = in.readByte() != 0; 103 | } 104 | 105 | public static final Creator CREATOR = new Creator() { 106 | @Override 107 | public ImageInfo createFromParcel(Parcel source) { 108 | return new ImageInfo(source); 109 | } 110 | 111 | @Override 112 | public ImageInfo[] newArray(int size) { 113 | return new ImageInfo[size]; 114 | } 115 | }; 116 | } 117 | -------------------------------------------------------------------------------- /imageseletor/src/main/java/io/github/lijunguan/imgselector/utils/ActivityUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016, The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.github.lijunguan.imgselector.utils; 18 | 19 | import android.support.annotation.NonNull; 20 | import android.support.v4.app.Fragment; 21 | import android.support.v4.app.FragmentManager; 22 | import android.support.v4.app.FragmentTransaction; 23 | 24 | import io.github.lijunguan.imgselector.R; 25 | 26 | import static io.github.lijunguan.imgselector.utils.CommonUtils.checkNotNull; 27 | 28 | 29 | /** 30 | * Created by lijunguan on 2016/4/21. 31 | * emial: lijunguan199210@gmail.com 32 | * blog: https://lijunguan.github.io 33 | * 提供方法帮助Activity加载它的UI 34 | */ 35 | public class ActivityUtils { 36 | 37 | /** 38 | * 添加这个{@code fragment} 到container View中并指定 id {@code frameId}。 39 | * 这个操作将会被{@code fragmentManager} 执行 40 | */ 41 | public static void addFragmentToActivity(@NonNull FragmentManager fragmentManager, 42 | @NonNull Fragment fragment, String tag, boolean addToBackStack) { 43 | checkNotNull(fragmentManager); 44 | checkNotNull(fragment); 45 | FragmentTransaction transaction = fragmentManager.beginTransaction(); 46 | transaction.add(R.id.fragment_container, fragment, tag); 47 | if (addToBackStack) { 48 | transaction.addToBackStack(null); 49 | } 50 | transaction.commit(); 51 | } 52 | 53 | 54 | } 55 | -------------------------------------------------------------------------------- /imageseletor/src/main/java/io/github/lijunguan/imgselector/utils/CommonUtils.java: -------------------------------------------------------------------------------- 1 | package io.github.lijunguan.imgselector.utils; 2 | 3 | import android.support.annotation.Nullable; 4 | 5 | /** 6 | * Created by lijunguan on 2016/4/21. 7 | * emial: lijunguan199210@gmail.com 8 | * blog: https://lijunguan.github.io 9 | */ 10 | public class CommonUtils { 11 | 12 | /** 13 | * Ensures the truth of an expression involving one or more parameters to the calling method. 14 | * 15 | * @param expression a boolean expression 16 | * @param errorMessage the exception message to use if the check fails; will be converted to a 17 | * string using {@link String#valueOf(Object)} 18 | * @throws IllegalArgumentException if {@code expression} is false 19 | */ 20 | public static void checkArgument(boolean expression, @Nullable Object errorMessage) { 21 | if (!expression) { 22 | throw new IllegalArgumentException(String.valueOf(errorMessage)); 23 | } 24 | } 25 | 26 | /** 27 | *确保作为方法参数的对象引用非空 28 | * @param reference an object reference 29 | * @return the non-null reference that was validated 30 | * @throws NullPointerException if {@code reference} is null 31 | */ 32 | public static T checkNotNull(T reference) { 33 | if (reference == null) { 34 | throw new NullPointerException(); 35 | } 36 | return reference; 37 | } 38 | 39 | /** 40 | * 确保作为方法参数的对象引用非空 41 | * @param reference an object reference 42 | * @param errorMessage the exception message to use if the check fails; will be converted to a 43 | * string using {@link String#valueOf(Object)} 44 | * @return the non-null reference that was validated 45 | * @throws NullPointerException if {@code reference} is null 46 | */ 47 | public static T checkNotNull(T reference, @Nullable Object errorMessage) { 48 | if (reference == null) { 49 | throw new NullPointerException(String.valueOf(errorMessage)); 50 | } 51 | return reference; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /imageseletor/src/main/java/io/github/lijunguan/imgselector/utils/FileUtils.java: -------------------------------------------------------------------------------- 1 | package io.github.lijunguan.imgselector.utils; 2 | 3 | import android.content.Context; 4 | import android.content.pm.PackageManager; 5 | import android.os.Environment; 6 | import android.text.TextUtils; 7 | 8 | import java.io.File; 9 | import java.io.IOException; 10 | 11 | import static android.os.Environment.MEDIA_MOUNTED; 12 | 13 | /** 14 | * 文件操作类 15 | */ 16 | public class FileUtils { 17 | 18 | private static final String JPEG_FILE_PREFIX = "IMG_"; 19 | private static final String JPEG_FILE_SUFFIX = ".jpg"; 20 | 21 | 22 | public static File createTmpFile(Context context) throws IOException { 23 | File dir; 24 | if (TextUtils.equals(Environment.getExternalStorageState(), Environment.MEDIA_MOUNTED)) { 25 | dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM); 26 | if (!dir.exists()) { 27 | dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM + "/Camera"); 28 | if (!dir.exists()) { 29 | dir = getCacheDirectory(context, true); 30 | } 31 | } 32 | } else { 33 | dir = getCacheDirectory(context, true); 34 | } 35 | return File.createTempFile(JPEG_FILE_PREFIX, JPEG_FILE_SUFFIX, dir); 36 | } 37 | 38 | 39 | private static final String EXTERNAL_STORAGE_PERMISSION = "android.permission.WRITE_EXTERNAL_STORAGE"; 40 | 41 | /** 42 | * Returns application cache directory. Cache directory will be created on SD card 43 | * ("/Android/data/[app_package_name]/cache") if card is mounted and app has appropriate permission. Else - 44 | * Android defines cache directory on device's file system. 45 | * 46 | * @param context Application context 47 | * @return Cache {@link File directory}. 48 | * NOTE: Can be null in some unpredictable cases (if SD card is unmounted and 49 | * {@link android.content.Context#getCacheDir() Context.getCacheDir()} returns null). 50 | */ 51 | public static File getCacheDirectory(Context context) { 52 | return getCacheDirectory(context, true); 53 | } 54 | 55 | /** 56 | * Returns application cache directory. Cache directory will be created on SD card 57 | * ("/Android/data/[app_package_name]/cache") (if card is mounted and app has appropriate permission) or 58 | * on device's file system depending incoming parameters. 59 | * 60 | * @param context Application context 61 | * @param preferExternal Whether prefer external location for cache 62 | * @return Cache {@link File directory}. 63 | * NOTE: Can be null in some unpredictable cases (if SD card is unmounted and 64 | * {@link android.content.Context#getCacheDir() Context.getCacheDir()} returns null). 65 | */ 66 | public static File getCacheDirectory(Context context, boolean preferExternal) { 67 | File appCacheDir = null; 68 | String externalStorageState; 69 | try { 70 | externalStorageState = Environment.getExternalStorageState(); 71 | } catch (NullPointerException | IncompatibleClassChangeError e) { // (sh)it happens (Issue #660) 72 | externalStorageState = ""; 73 | } 74 | if (preferExternal && MEDIA_MOUNTED.equals(externalStorageState) && hasExternalStoragePermission(context)) { 75 | appCacheDir = getExternalCacheDir(context); 76 | } 77 | if (appCacheDir == null) { 78 | appCacheDir = context.getCacheDir(); 79 | } 80 | if (appCacheDir == null) { 81 | String cacheDirPath = "/data/data/" + context.getPackageName() + "/cache/"; 82 | appCacheDir = new File(cacheDirPath); 83 | } 84 | return appCacheDir; 85 | } 86 | 87 | private static File getExternalCacheDir(Context context) { 88 | File dataDir = new File(new File(Environment.getExternalStorageDirectory(), "Android"), "data"); 89 | File appCacheDir = new File(new File(dataDir, context.getPackageName()), "cache"); 90 | if (!appCacheDir.exists()) { 91 | if (!appCacheDir.mkdirs()) { 92 | return null; 93 | } 94 | try { 95 | new File(appCacheDir, ".nomedia").createNewFile(); 96 | } catch (IOException e) { 97 | } 98 | } 99 | return appCacheDir; 100 | } 101 | 102 | private static boolean hasExternalStoragePermission(Context context) { 103 | int perm = context.checkCallingOrSelfPermission(EXTERNAL_STORAGE_PERMISSION); 104 | return perm == PackageManager.PERMISSION_GRANTED; 105 | } 106 | 107 | } 108 | -------------------------------------------------------------------------------- /imageseletor/src/main/java/io/github/lijunguan/imgselector/utils/KLog.java: -------------------------------------------------------------------------------- 1 | package io.github.lijunguan.imgselector.utils; 2 | 3 | import android.util.Log; 4 | 5 | 6 | public class KLog { 7 | 8 | public static final String DEFAULT_MESSAGE = "execute"; 9 | public static final String NULL_TIPS = "Log with null object"; 10 | public static final String PARAM = "Param"; 11 | public static final String NULL = "null"; 12 | 13 | 14 | public static final int V = 0x1; 15 | public static final int D = 0x2; 16 | public static final int I = 0x3; 17 | public static final int W = 0x4; 18 | public static final int E = 0x5; 19 | public static final int A = 0x6; 20 | 21 | private static boolean IS_SHOW_LOG = true; 22 | 23 | public static void init(boolean isShowLog) { 24 | IS_SHOW_LOG = isShowLog; 25 | } 26 | 27 | public static void v() { 28 | printLog(V, null, DEFAULT_MESSAGE); 29 | } 30 | 31 | public static void v(Object msg) { 32 | printLog(V, null, msg); 33 | } 34 | 35 | public static void v(String tag, Object... objects) { 36 | printLog(V, tag, objects); 37 | } 38 | 39 | public static void d() { 40 | printLog(D, null, DEFAULT_MESSAGE); 41 | } 42 | 43 | public static void d(Object msg) { 44 | printLog(D, null, msg); 45 | } 46 | 47 | public static void d(String tag, Object... objects) { 48 | printLog(D, tag, objects); 49 | } 50 | 51 | public static void i() { 52 | printLog(I, null, DEFAULT_MESSAGE); 53 | } 54 | 55 | public static void i(Object msg) { 56 | printLog(I, null, msg); 57 | } 58 | 59 | public static void i(String tag, Object... objects) { 60 | printLog(I, tag, objects); 61 | } 62 | 63 | public static void w() { 64 | printLog(W, null, DEFAULT_MESSAGE); 65 | } 66 | 67 | public static void w(Object msg) { 68 | printLog(W, null, msg); 69 | } 70 | 71 | public static void w(String tag, Object... objects) { 72 | printLog(W, tag, objects); 73 | } 74 | 75 | public static void e() { 76 | printLog(E, null, DEFAULT_MESSAGE); 77 | } 78 | 79 | public static void e(Object msg) { 80 | printLog(E, null, msg); 81 | } 82 | 83 | public static void e(String tag, Object... objects) { 84 | printLog(E, tag, objects); 85 | } 86 | 87 | public static void a() { 88 | printLog(A, null, DEFAULT_MESSAGE); 89 | } 90 | 91 | public static void a(Object msg) { 92 | printLog(A, null, msg); 93 | } 94 | 95 | public static void a(String tag, Object... objects) { 96 | printLog(A, tag, objects); 97 | } 98 | 99 | 100 | private static void printLog(int type, String tagStr, Object... objects) { 101 | 102 | if (!IS_SHOW_LOG) { 103 | return; 104 | } 105 | 106 | String[] contents = wrapperContent(tagStr, objects); 107 | String tag = contents[0]; 108 | String msg = contents[1]; 109 | String headString = contents[2]; 110 | 111 | switch (type) { 112 | case V: 113 | case D: 114 | case I: 115 | case W: 116 | case E: 117 | case A: 118 | printDefault(type, tag, headString + msg); 119 | break; 120 | } 121 | } 122 | 123 | 124 | private static String[] wrapperContent(String tagStr, Object... objects) { 125 | 126 | StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); 127 | int index = 5; 128 | String className = stackTrace[index].getFileName(); 129 | String methodName = stackTrace[index].getMethodName(); 130 | int lineNumber = stackTrace[index].getLineNumber(); 131 | String methodNameShort = methodName.substring(0, 1).toUpperCase() + methodName.substring(1); 132 | String tag = (tagStr == null ? className : tagStr); 133 | String msg = (objects == null) ? NULL_TIPS : getObjectsString(objects); 134 | String headString = "[ (" + className + ":" + lineNumber + ")#" + methodNameShort + " ] "; 135 | 136 | return new String[]{tag, msg, headString}; 137 | } 138 | 139 | private static String getObjectsString(Object... objects) { 140 | 141 | if (objects.length > 1) { 142 | StringBuilder stringBuilder = new StringBuilder(); 143 | stringBuilder.append("\n"); 144 | for (int i = 0; i < objects.length; i++) { 145 | Object object = objects[i]; 146 | if (object == null) { 147 | stringBuilder.append(PARAM).append("[").append(i).append("]").append(" = ").append(NULL).append("\n"); 148 | } else { 149 | stringBuilder.append(PARAM).append("[").append(i).append("]").append(" = ").append(object.toString()).append("\n"); 150 | } 151 | } 152 | return stringBuilder.toString(); 153 | } else { 154 | Object object = objects[0]; 155 | return object == null ? NULL : object.toString(); 156 | } 157 | } 158 | 159 | public static void printDefault(int type, String tag, String msg) { 160 | 161 | int index = 0; 162 | int maxLength = 4000; 163 | int countOfSub = msg.length() / maxLength; 164 | 165 | if (countOfSub > 0) { 166 | for (int i = 0; i < countOfSub; i++) { 167 | String sub = msg.substring(index, index + maxLength); 168 | printSub(type, tag, sub); 169 | index += maxLength; 170 | } 171 | printSub(type, tag, msg.substring(index, msg.length())); 172 | } else { 173 | printSub(type, tag, msg); 174 | } 175 | } 176 | 177 | 178 | private static void printSub(int type, String tag, String sub) { 179 | switch (type) { 180 | case KLog.V: 181 | Log.v(tag, sub); 182 | break; 183 | case KLog.D: 184 | Log.d(tag, sub); 185 | break; 186 | case KLog.I: 187 | Log.i(tag, sub); 188 | break; 189 | case KLog.W: 190 | Log.w(tag, sub); 191 | break; 192 | case KLog.E: 193 | Log.e(tag, sub); 194 | break; 195 | case KLog.A: 196 | Log.wtf(tag, sub); 197 | break; 198 | } 199 | } 200 | 201 | } 202 | -------------------------------------------------------------------------------- /imageseletor/src/main/java/io/github/lijunguan/imgselector/utils/StatusBarUtil.java: -------------------------------------------------------------------------------- 1 | package io.github.lijunguan.imgselector.utils; 2 | 3 | import android.app.Activity; 4 | import android.content.Context; 5 | import android.os.Build; 6 | import android.view.View; 7 | import android.view.ViewGroup; 8 | import android.view.WindowManager; 9 | import android.widget.LinearLayout; 10 | 11 | public class StatusBarUtil { 12 | 13 | public static final int DEFAULT_STATUS_BAR_ALPHA = 60; 14 | 15 | /** 16 | * 设置状态栏颜色 17 | * 18 | * @param activity 需要设置的 activity 19 | * @param color 状态栏颜色值 20 | */ 21 | public static void setColor(Activity activity, int color) { 22 | setColor(activity, color, DEFAULT_STATUS_BAR_ALPHA); 23 | } 24 | 25 | /** 26 | * 设置状态栏颜色 27 | * 28 | * @param activity 需要设置的activity 29 | * @param color 状态栏颜色值 30 | * @param statusBarAlpha 状态栏透明度 31 | */ 32 | public static void setColor(Activity activity, int color, int statusBarAlpha) { 33 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 34 | activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); 35 | activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); 36 | activity.getWindow().setStatusBarColor(calculateStatusColor(color, statusBarAlpha)); 37 | } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { 38 | activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); 39 | // 生成一个状态栏大小的矩形 40 | View statusView = createStatusBarView(activity, color, statusBarAlpha); 41 | // 添加 statusView 到布局中 42 | ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView(); 43 | decorView.addView(statusView); 44 | setRootView(activity); 45 | } 46 | } 47 | 48 | 49 | /** 50 | * 生成一个和状态栏大小相同的半透明矩形条 51 | * 52 | * @param activity 需要设置的activity 53 | * @param color 状态栏颜色值 54 | * @param alpha 透明值 55 | * @return 状态栏矩形条 56 | */ 57 | private static View createStatusBarView(Activity activity, int color, int alpha) { 58 | // 绘制一个和状态栏一样高的矩形 59 | View statusBarView = new View(activity); 60 | LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 61 | getStatusBarHeight(activity)); 62 | statusBarView.setLayoutParams(params); 63 | statusBarView.setBackgroundColor(calculateStatusColor(color, alpha)); 64 | return statusBarView; 65 | } 66 | 67 | /** 68 | * 设置根布局参数 69 | */ 70 | private static void setRootView(Activity activity) { 71 | ViewGroup rootView = (ViewGroup) ((ViewGroup) activity.findViewById(android.R.id.content)).getChildAt(0); 72 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { 73 | rootView.setFitsSystemWindows(true); 74 | } 75 | rootView.setClipToPadding(true); 76 | } 77 | 78 | /** 79 | * 获取状态栏高度 80 | * 81 | * @param context context 82 | * @return 状态栏高度 83 | */ 84 | private static int getStatusBarHeight(Context context) { 85 | // 获得状态栏高度 86 | int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); 87 | return context.getResources().getDimensionPixelSize(resourceId); 88 | } 89 | 90 | /** 91 | * 计算状态栏颜色 92 | * 93 | * @param color color值 94 | * @param alpha alpha值 95 | * @return 最终的状态栏颜色 96 | */ 97 | private static int calculateStatusColor(int color, int alpha) { 98 | float a = 1 - alpha / 255f; 99 | int red = color >> 16 & 0xff; 100 | int green = color >> 8 & 0xff; 101 | int blue = color & 0xff; 102 | red = (int) (red * a + 0.5); 103 | green = (int) (green * a + 0.5); 104 | blue = (int) (blue * a + 0.5); 105 | return 0xff << 24 | red << 16 | green << 8 | blue; 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /imageseletor/src/main/res/drawable-v21/ic_add_a_photo_grey_100_36dp.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /imageseletor/src/main/res/drawable-v21/ic_photo_library_white_24dp.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 11 | -------------------------------------------------------------------------------- /imageseletor/src/main/res/drawable/action_btn.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /imageseletor/src/main/res/drawable/button_bg.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /imageseletor/src/main/res/drawable/divider_bg.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /imageseletor/src/main/res/drawable/ic_add_a_photo_grey_100_36dp.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /imageseletor/src/main/res/drawable/ic_photo_library_white_24dp.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 11 | -------------------------------------------------------------------------------- /imageseletor/src/main/res/drawable/placeholder.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Raynor999/AlbumSelector/e6126a7da077510615f0a2200daa0e94767484c8/imageseletor/src/main/res/drawable/placeholder.png -------------------------------------------------------------------------------- /imageseletor/src/main/res/layout/activity_album.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /imageseletor/src/main/res/layout/activity_crop.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /imageseletor/src/main/res/layout/crop_view.xml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /imageseletor/src/main/res/layout/fragment_album.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 12 | 13 | 14 | 15 | 16 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /imageseletor/src/main/res/layout/fragmetn_image_detail.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 10 | 11 | 17 | 18 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /imageseletor/src/main/res/layout/item_album_folder_list.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 16 | 17 | 23 | 24 | 32 | 33 | 40 | 41 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /imageseletor/src/main/res/layout/item_camera.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | > 7 | 17 | -------------------------------------------------------------------------------- /imageseletor/src/main/res/layout/item_image_detail.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | -------------------------------------------------------------------------------- /imageseletor/src/main/res/layout/item_image_grid.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 12 | 13 | 14 | 20 | 21 | 26 | 27 | -------------------------------------------------------------------------------- /imageseletor/src/main/res/layout/layout_album_list.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 15 | 16 | 19 | 20 | 26 | 27 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /imageseletor/src/main/res/layout/layout_appbar.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 15 | 16 |